Factored out _find_paper() function
authorDmitriy Morozov <dmitriy@mrzv.org>
Tue, 15 Sep 2009 13:56:35 -0700
changeset 28 7ddd1989eb00
parent 27 d65a9450109d
child 29 c85b9ac4880d
Factored out _find_paper() function
alexandria.py
--- a/alexandria.py	Wed Sep 02 18:58:52 2009 -0700
+++ b/alexandria.py	Tue Sep 15 13:56:35 2009 -0700
@@ -93,8 +93,9 @@
          usage = '%name HASH [-t TITLE] [-l LABEL]* [-a AUTHOR]*')
 def update(cfg, hash, path = None, **opts):
     """Update paper by hash"""
-    
-    p = Paper.query.filter(Paper.md5.startswith(hash)).one()
+ 
+    p = _find_paper(hash)
+    if not p: return
     if path: p.path = _short_path(cfg, path)
     _set_options(p, opts)
     session.commit()
@@ -105,19 +106,8 @@
 def view(cfg, hash, viewer = None, **opts):
     """View paper by hash"""
 
-    p = Paper.query.filter(Paper.md5.startswith(hash)).all()
-    if not p: 
-        print _colorize_string('error', 'No such paper')
-        return
-    if len(p) > 1:
-        print _colorize_string('error', 'Too many choices')
-        for pp in p: 
-            print
-            _show_paper(pp)
-        return
-    else:
-        p = p[0]
-    
+    p = _find_paper(hash)
+    if not p: return
     viewer = viewer or cfg['default_viewer']
     os.system('%s %s' % (viewer, os.path.join(cfg['commonpath'], p.path.strip('/'))))
     
@@ -126,7 +116,7 @@
 def remove(cfg, hash):
     """Remove paper by hash"""
     
-    p = Paper.query.filter(Paper.md5.startswith(hash)).one()
+    p = _find_paper(hash)
     if not p: return
     print "Removing"
     _show_paper(p)
@@ -330,6 +320,20 @@
 def _colorize_string(clr, str):
     return '%s%s%s' % (color[clr], str, color['normal'])
 
+def _find_paper(hash):
+    p = Paper.query.filter(Paper.md5.startswith(hash)).all()
+    if not p: 
+        print _colorize_string('error', 'No such paper')
+        return None
+    if len(p) > 1:
+        print _colorize_string('error', 'Too many choices')
+        for pp in p: 
+            print
+            _show_paper(pp)
+        return None
+    else:
+        return p[0]
+
 
 # Decorator that parses config and initializes the database
 def init(func):