]> arthur.barton.de Git - bup.git/blobdiff - lib/bup/options.py
options.py: o.fatal(): print error after, not before, usage message.
[bup.git] / lib / bup / options.py
index 17d1eef88183ace39182d25bd48745c6ff87a871..c9a6cf52ea59a2542558c1ddbf5cb39146dfa3e3 100644 (file)
@@ -1,9 +1,42 @@
 """Command-line options parser.
 With the help of an options spec string, easily parse command-line options.
+
+An options spec is made up of two parts, separated by a line with two dashes.
+The first part is the synopsis of the command and the second one specifies
+options, one per line.
+
+Each non-empty line in the synopsis gives a set of options that can be used
+together.
+
+Option flags must be at the begining of the line and multiple flags are
+separated by commas. Usually, options have a short, one character flag, and a
+longer one, but the short one can be omitted.
+
+Long option flags are used as the option's key for the OptDict produced when
+parsing options.
+
+When the flag definition is ended with an equal sign, the option takes one
+string as an argument. Otherwise, the option does not take an argument and
+corresponds to a boolean flag that is true when the option is given on the
+command line.
+
+The option's description is found at the right of its flags definition, after
+one or more spaces. The description ends at the end of the line. If the
+description contains text enclosed in square brackets, the enclosed text will
+be used as the option's default value.
+
+Options can be put in different groups. Options in the same group must be on
+consecutive lines. Groups are formed by inserting a line that begins with a
+space. The text on that line will be output after an empty line.
 """
 import sys, os, textwrap, getopt, re, struct
 
 class OptDict:
+    """Dictionary that exposes keys as attributes.
+
+    Keys can bet set or accessed with a "no-" or "no_" prefix to negate the
+    value.
+    """
     def __init__(self):
         self._opts = {}
 
@@ -60,15 +93,14 @@ def _tty_width():
     except (IOError, ImportError):
         return _atoi(os.environ.get('WIDTH')) or 70
     (ysize,xsize,ypix,xpix) = struct.unpack('HHHH', s)
-    return xsize
+    return xsize or 70
 
 
 class Options:
     """Option parser.
-    When constructed, two strings are mandatory. The first one is the command
-    name showed before error messages. The second one is a string called an
-    optspec that specifies the synopsis and option flags and their description.
-    For more information about optspecs, consult the bup-options(1) man page.
+    When constructed, a string called an option spec must be given. It
+    specifies the synopsis and option flags and their description.  For more
+    information about option specs, see the docstring at the top of this file.
 
     Two optional arguments specify an alternative parsing function and an
     alternative behaviour on abort (after having output the usage string).
@@ -83,7 +115,7 @@ class Options:
         self.optfunc = optfunc
         self._aliases = {}
         self._shortopts = 'h?'
-        self._longopts = ['help']
+        self._longopts = ['help', 'usage']
         self._hasparms = {}
         self._defaults = {}
         self._usagestr = self._gen_usage()
@@ -121,8 +153,8 @@ class Options:
                     defval = None
                 flagl = flags.split(',')
                 flagl_nice = []
-                for f in flagl:
-                    f,dvi = _remove_negative_kv(f, _intify(defval))
+                for _f in flagl:
+                    f,dvi = _remove_negative_kv(_f, _intify(defval))
                     self._aliases[f] = _remove_negative_k(flagl[0])
                     self._hasparms[f] = has_parm
                     self._defaults[f] = dvi
@@ -134,7 +166,7 @@ class Options:
                         self._aliases[f_nice] = _remove_negative_k(flagl[0])
                         self._longopts.append(f + (has_parm and '=' or ''))
                         self._longopts.append('no-' + f)
-                        flagl_nice.append('--' + f)
+                        flagl_nice.append('--' + _f)
                 flags_nice = ', '.join(flagl_nice)
                 if has_parm:
                     flags_nice += ' ...'
@@ -152,14 +184,15 @@ class Options:
     def usage(self, msg=""):
         """Print usage string to stderr and abort."""
         sys.stderr.write(self._usagestr)
+        if msg:
+            sys.stderr.write(msg)
         e = self._onabort and self._onabort(msg) or None
         if e:
             raise e
 
-    def fatal(self, s):
+    def fatal(self, msg):
         """Print an error message to stderr and abort with usage string."""
-        msg = 'error: %s\n' % s
-        sys.stderr.write(msg)
+        msg = '\nerror: %s\n' % msg
         return self.usage(msg)
 
     def parse(self, args):
@@ -182,7 +215,7 @@ class Options:
 
         for (k,v) in flags:
             k = k.lstrip('-')
-            if k in ('h', '?', 'help'):
+            if k in ('h', '?', 'help', 'usage'):
                 self.usage()
             if k.startswith('no-'):
                 k = self._aliases[k[3:]]