]> arthur.barton.de Git - bup.git/commitdiff
lib/options: Add an onabort argument to Options()
authorGabriel Filion <lelutin@gmail.com>
Tue, 27 Jul 2010 03:52:33 +0000 (23:52 -0400)
committerAvery Pennarun <apenwarr@gmail.com>
Tue, 27 Jul 2010 07:49:27 +0000 (03:49 -0400)
Some times, we may want to parse a list of arguments and not have the
call to Options.parse() exit the program when it finds an unknown
argument.

Add an argument to the class' __init__ method that can be either a
function or a class (must be an exception class). If calling the
function or class constructor returns an object, this object will be
raised on abort.

Also add a convenience exception class named Fatal that can be
passed to Options() to exclusively catch situations in which
Options.parse() would have caused the program to exit.

Finally, set the default value to the onabort argument to call
sys.exit(97) as was previously the case.

Signed-off-by: Gabriel Filion <lelutin@gmail.com>
lib/bup/options.py

index c1a1455d476cddf3aed42db31f81f21d19b3cdc1..dc4be49905ae59c122d50bc6f5b5dade22b09f60 100644 (file)
@@ -14,17 +14,23 @@ class OptDict:
         return self[k]
 
 
+def _default_onabort(msg):
+    sys.exit(97)
+
+
 class Options:
-    def __init__(self, exe, optspec, optfunc=getopt.gnu_getopt):
+    def __init__(self, exe, optspec, optfunc=getopt.gnu_getopt,
+                 onabort=_default_onabort):
         self.exe = exe
         self.optspec = optspec
+        self._onabort = onabort
         self.optfunc = optfunc
         self._aliases = {}
         self._shortopts = 'h?'
         self._longopts = ['help']
         self._hasparms = {}
         self._usagestr = self._gen_usage()
-        
+
     def _gen_usage(self):
         out = []
         lines = self.optspec.strip().split('\n')
@@ -74,15 +80,18 @@ class Options:
             else:
                 out.append('\n')
         return ''.join(out).rstrip() + '\n'
-    
-    def usage(self):
+
+    def usage(self, msg=""):
         sys.stderr.write(self._usagestr)
-        sys.exit(97)
+        e = self._onabort and self._onabort(msg) or None
+        if e:
+            raise e
 
     def fatal(self, s):
-        sys.stderr.write('error: %s\n' % s)
-        return self.usage()
-        
+        msg = 'error: %s\n' % s
+        sys.stderr.write(msg)
+        return self.usage(msg)
+
     def parse(self, args):
         try:
             (flags,extra) = self.optfunc(args, self._shortopts, self._longopts)