1. John Mulligan
  2. vanity

Commits

John Mulligan  committed 26e592d

cli: internally use an Option object for options

this can be convert from a tuple, dict or Option object

  • Participants
  • Parent commits 290f39d
  • Branches default

Comments (0)

Files changed (1)

File vanity/cli.py

View file
     for label in disp:
         desc = cmds.get(label)[3]
         yield (label, desc)
-    
 
 
+class Option(object):
+    """A thin class representing a cli option.
 
+    Parameters: name, long, short, default, help
+    """
+
+    def __init__(self, name, short=None, default=None, help=None):
+        self.name = self.long = name
+        self.short = short
+        self.default = default
+        self.help = help
+
+    @classmethod
+    def convert(cls, obj):
+        """Convert a tuple, list or dictionary to an Option object.
+        Returns an Option object, if the given object is an Option
+        the same object will be returned.
+        """
+        if hasattr(obj, 'keys'):
+            return cls(**obj)
+        if isinstance(obj, cls):
+            return obj
+        return cls(*obj)
+
+
+def _stripldashes(txt):
+    ii = 0
+    while txt[ii] == '-':
+        ii += 1
+    return txt[ii:]
 
 
 class OptionTable(object):
     """
     def __init__(self, table):
         self._table = {}
-        for (long, short, default, desc) in table:
-            self._table[long] = dict(
-                long=long,
-                short=short,
-                default=default,
-                desc=desc,
-                )
+        for opt in table:
+            opt = Option.convert(opt)
+            self._table[opt.name] = opt
 
     def table(self):
         """Generate the stored options table.
         """
         for opt in self._table.values():
-            yield (opt['long'], opt['short'], opt['default'], opt['desc'])
+            yield (opt.long, opt.short, opt.default, opt.help)
 
     def __contains__(self, value):
         return (value in self._table)
     def shortopts(self):
         """Generates a list of the short options
         """
-        return (og['short'] for og in self._table.values() if og['short'])
+        return (og.short for og in self._table.values() if og.short)
 
     def __iter__(self):
         return self._table.itervalues()
         """
         spec = []
         for opt in self:
-            if opt['default'] is None:
-                spec.append('%s' % opt['long'])
+            if opt.default is None:
+                spec.append('%s' % opt.long)
             else:
-                spec.append('%s=' % opt['long'])
+                spec.append('%s=' % opt.long)
         return spec
 
     def shortoptspec(self):
         """
         spec = []
         for opt in self:
-            if not opt['short']:
+            if not opt.short:
                 continue
-            if opt['default'] is None:
-                spec.append('%s' % opt['short'])
+            if opt.default is None:
+                spec.append('%s' % opt.short)
             else:
-                spec.append('%s:' % opt['short'])
+                spec.append('%s:' % opt.short)
         return ''.join(spec)
 
     def getlong(self, key):
         """Returns the long option belonging to the named
         table entry.
         """
-        while key.startswith('-'):
-            key = key[1:]
-        return self._table[key]
+        return self._table[_stripldashes(key)]
 
     def getshort(self, key):
         """Returns the short option belonging to the named
         table entry.
         """
-        while key.startswith('-'):
-            key = key[1:]
+        key = _stripldashes(key)
         for opt in self:
-            if key == opt['short']:
+            if key == opt.short:
                 return opt
         raise KeyError('unknown short option: %s' % key)
 
         """
         values = {}
         for opt in self:
-            name = opt['long']
-            if opt['default'] is None:
-                values[name] = None
-            elif hasattr(opt['default'], 'append'):
-                values[name] = list()
+            if opt.default is None:
+                values[opt.name] = None
+            elif hasattr(opt.default, 'append'):
+                values[opt.name] = list(opt.default)
             else:
-                values[name] = str(opt['default'])
+                values[opt.name] = str(opt.default)
         return values
 
     def assemble(self, opts):
                 option = fetcher(opt)
             except KeyError:
                 raise InvalidOption(opt)
-            name = option['long']
+            name = option.name
             if assembled[name] is None:
                 assembled[name] = True
             elif hasattr(assembled[name], 'append'):
         return assembled
 
     def __add__(self, other):
-        newtable = OptionTable([])
+        newtable = self.__class__([])
         newtable._table.update(self._table)
         newtable._table.update(other._table)
         return newtable