commit:     8ff5a7978a1804b786e850a60610b657962052e2
Author:     Devan Franchini <twitch153 <AT> gentoo <DOT> org>
AuthorDate: Wed May 14 23:58:29 2014 +0000
Commit:     Devan Franchini <twitch153 <AT> gentoo <DOT> org>
CommitDate: Thu May 15 20:44:49 2014 +0000
URL:        
http://git.overlays.gentoo.org/gitweb/?p=proj/layman.git;a=commit;h=8ff5a797

argsparser.py: Migrates from optparse to argparse

Included with this patch is another flag, -C for config dir as well
as default values for configdir, config, and overlay_defs. Also
included is interpolation of these variables, because argparse lacks
the necessary interpolation.

---
 layman/argsparser.py | 363 ++++++++++++++++++++++++++-------------------------
 1 file changed, 184 insertions(+), 179 deletions(-)

diff --git a/layman/argsparser.py b/layman/argsparser.py
index dd1cc85..6e5fee3 100644
--- a/layman/argsparser.py
+++ b/layman/argsparser.py
@@ -31,7 +31,7 @@ __version__ = "$Id: config.py 286 2007-01-09 17:48:23Z wrobel 
$"
 
 import sys
 
-from optparse import OptionParser, OptionGroup
+from argparse import ArgumentParser
 
 from layman.config import BareConfig
 from layman.constants import OFF
@@ -71,178 +71,182 @@ class ArgsParser(BareConfig):
 
         BareConfig.__init__(self, stdout=stdout, stderr=stderr,
                             stdin=stdin, root=root)
-        if args == None:
-            args = sys.argv
 
         # get a couple BareConfig items
         self.defaults = self.get_defaults()
         self.output = self.get_option('output')
 
-        self.parser = OptionParser(
-            usage   = _USAGE,
-            version = VERSION)
+        self.parser = ArgumentParser(
+            usage   = _USAGE)
 
-        self.parser.add_option('-H',
+        self.parser.add_argument('-V',
+                          '--version',
+                          action = 'version',
+                          version = VERSION)
+
+        self.parser.add_argument('-H',
                         '--setup_help',
                         action = 'store_true',
                         help = 'Print the NEW INSTALL help messages.')
 
-
         #-----------------------------------------------------------------
         # Main Options
 
-        group = OptionGroup(self.parser,
-                            '<Actions>')
-
-        group.add_option('-a',
-                         '--add',
-                         action = 'append',
-                         help = 'Add the given overlay from the cached remote 
li'
-                         'st to your locally installed overlays.. Specify 
"ALL" '
-                         'to add all overlays from the remote list.')
-
-        group.add_option('-d',
-                         '--delete',
-                         action = 'append',
-                         help = 'Remove the given overlay from your locally 
inst'
-                         'alled overlays. Specify "ALL" to remove all 
overlays')
-
-        group.add_option('-s',
-                         '--sync',
-                         action = 'append',
-                         help = 'Update the specified overlay. Use "ALL" as 
para'
-                         'meter to synchronize all overlays')
-
-        group.add_option('-i',
-                         '--info',
-                         action = 'append',
-                         help = 'Display information about the specified 
overlay'
-                         '.')
-
-        group.add_option('-S',
-                         '--sync-all',
-                         action = 'store_true',
-                         help = 'Update all overlays.')
-
-        group.add_option('-L',
-                         '--list',
-                         action = 'store_true',
-                         help = 'List the contents of the remote list.')
-
-        group.add_option('-l',
-                         '--list-local',
-                         action = 'store_true',
-                         help = 'List the locally installed overlays.')
-
-        group.add_option('-f',
-                         '--fetch',
-                         action = 'store_true',
-                         help = 'Fetch a remote list of overlays. This option 
is'
-                         ' deprecated. The fetch operation will be performed 
by '
-                         'default when you run sync, sync-all, or list.')
-
-        group.add_option('-n',
-                         '--nofetch',
-                         action = 'store_true',
-                         help = 'Do not fetch a remote list of overlays.')
-
-        group.add_option('-p',
-                         '--priority',
-                         action = 'store',
-                         help = 'Use this with the --add switch to set the 
prior'
-                         'ity of the added overlay. This will influence the 
sort'
-                         'ing order of the overlays in the PORTDIR_OVERLAY 
varia'
-                         'ble.')
-
-        self.parser.add_option_group(group)
+        actions = self.parser.add_argument_group('<Actions>')
+
+        actions.add_argument('-a',
+                             '--add',
+                             action = 'append',
+                             help = 'Add the given overlay from the cached 
remote li'
+                             'st to your locally installed overlays.. Specify 
"ALL" '
+                             'to add all overlays from the remote list.')
+
+        actions.add_argument('-d',
+                             '--delete',
+                             action = 'append',
+                             help = 'Remove the given overlay from your 
locally inst'
+                             'alled overlays. Specify "ALL" to remove all 
overlays.')
+
+        actions.add_argument('-s',
+                             '--sync',
+                             action = 'append',
+                             help = 'Update the specified overlay. Use "ALL" 
as para'
+                            'meter to synchronize all overlays.')
+
+        actions.add_argument('-i',
+                             '--info',
+                             action = 'append',
+                             help = 'Display information about the specified 
overlay'
+                             '.')
+
+        actions.add_argument('-S',
+                             '--sync-all',
+                             action = 'store_true',
+                             help = 'Update all overlays.')
+
+        actions.add_argument('-L',
+                             '--list',
+                             action = 'store_true',
+                             help = 'List the contents of the remote list.')
+
+        actions.add_argument('-l',
+                             '--list-local',
+                             action = 'store_true',
+                             help = 'List the locally installed overlays.')
+
+        actions.add_argument('-f',
+                             '--fetch',
+                             action = 'store_true',
+                             help = 'Fetch a remote list of overlays. This 
option is'
+                             ' deprecated. The fetch operation will be 
performed by '
+                             'default when you run sync, sync-all, or list.')
+
+        actions.add_argument('-n',
+                             '--nofetch',
+                             action = 'store_true',
+                             help = 'Do not fetch a remote list of overlays.')
+
+        actions.add_argument('-p',
+                             '--priority',
+                             action = 'store',
+                             help = 'Use this with the --add switch to set the 
prior'
+                             'ity of the added overlay. This will influence 
the sort'
+                             'ing order of the overlays in the PORTDIR_OVERLAY 
varia'
+                             'ble.')
 
         #-----------------------------------------------------------------
         # Additional Options
 
-        group = OptionGroup(self.parser,
-                            '<Path options>')
+        path_opts = self.parser.add_argument_group('<Path options>')
+
+        path_opts.add_argument('-C',
+                               '--configdir',
+                               action = 'store',
+                               default = '/etc/layman',
+                               help = 'Directory path to user for all layman 
configu'
+                               'ration information [default: /etc/layman].')
+
+        path_opts.add_argument('-c',
+                               '--config',
+                               action = 'store',
+                               default = self.defaults['config'],
+                               # Force interpolation (to prevent argparse 
tracebacks)
+                               help = 'Path to the config file [default: '
+                               '%s].' % (self.defaults['config'] 
%self.defaults))
 
-        group.add_option('-c',
-                         '--config',
-                         action = 'store',
-                         help = 'Path to the config file [default: ' \
-                         + self.defaults['config'] + '].')
 
-        group.add_option('-O',
-                         '--overlay_defs',
-                         action = 'store',
-                         help = 'Path to aditional overlay.xml files [default: 
'\
-                         + self.defaults['overlay_defs'] + '].')
 
-        group.add_option('-o',
-                         '--overlays',
-                         action = 'append',
-                         help = 'The list of overlays [default: ' \
-                         + self.defaults['overlays'] + '].')
+        path_opts.add_argument('-O',
+                               '--overlay_defs',
+                               action = 'store',
+                               default = self.defaults['overlay_defs'],
+                               # Force interpolation (to prevent argparse 
tracebacks)
+                               help = 'Path to aditional overlay.xml files 
[default: '
+                               '%s].' % (self.defaults['overlay_defs'] 
%self.defaults))
 
-        self.parser.add_option_group(group)
+        path_opts.add_argument('-o',
+                               '--overlays',
+                               action = 'append',
+                               help = 'The list of overlays [default: ' \
+                               + self.defaults['overlays'] + '].')
 
         #-----------------------------------------------------------------
         # Output Options
 
-        group = OptionGroup(self.parser,
-                            '<Output options>')
-
-        group.add_option('-v',
-                         '--verbose',
-                         action = 'store_true',
-                         help = 'Increase the amount of output and describe 
the '
-                         'overlays.')
-
-        group.add_option('-q',
-                         '--quiet',
-                         action = 'store_true',
-                         help = 'Yield no output. Please be careful with this 
op'
-                         'tion: If the processes spawned by layman when adding 
o'
-                         'r synchronizing overlays require any input layman 
will'
-                         ' hang without telling you why. This might happen for 
e'
-                         'xample if your overlay resides in subversion and the 
S'
-                         'SL certificate of the server needs acceptance.')
-
-        group.add_option('-N',
-                         '--nocolor',
-                         action = 'store_true',
-                         help = 'Remove color codes from the layman output.')
-
-        group.add_option('-Q',
-                         '--quietness',
-                         action = 'store',
-                         type = 'int',
-                         default = '4',
-                         help = 'Set the level of output (0-4). Default: 4. 
Once'
-                         ' you set this below 2 the same warning as given for 
--'
-                         'quiet applies! ')
-
-        group.add_option('-W',
-                         '--width',
-                         action = 'store',
-                         type = 'int',
-                         default = '0',
-                         help = 'Sets the screen width. This setting is 
usually '
-                         'not required as layman is capable of detecting the '
-                         'available number of columns automatically.')
-
-        group.add_option('-k',
-                         '--nocheck',
-                         action = 'store_true',
-                         help = 'Do not check overlay definitions and do not i'
-                         'ssue a warning if description or contact information'
-                         ' are missing.')
-
-        group.add_option('--debug-level',
-                         action = 'store',
-                         type = 'int',
-                         help = 'A value between 0 and 10. 0 means no 
debugging '
-                         'messages will be selected, 10 selects all debugging 
me'
-                         'ssages. Default is "4".')
-
-
-        self.parser.add_option_group(group)
+        out_opts = self.parser.add_argument_group('<Output options>')
+
+        out_opts.add_argument('-v',
+                              '--verbose',
+                              action = 'store_true',
+                              help = 'Increase the amount of output and 
describe the '
+                              'overlays.')
+
+        out_opts.add_argument('-q',
+                              '--quiet',
+                              action = 'store_true',
+                              help = 'Yield no output. Please be careful with 
this op'
+                              'tion: If the processes spawned by layman when 
adding o'
+                              'r synchronizing overlays require any input 
layman will'
+                              ' hang without telling you why. This might 
happen for e'
+                              'xample if your overlay resides in subversion 
and the S'
+                              'SL certificate of the server needs acceptance.')
+
+        out_opts.add_argument('-N',
+                              '--nocolor',
+                              action = 'store_true',
+                              help = 'Remove color codes from the layman 
output.')
+
+        out_opts.add_argument('-Q',
+                              '--quietness',
+                              action = 'store',
+                              type = int,
+                              default = 4,
+                              help = 'Set the level of output (0-4). Default: 
4. Once'
+                              ' you set this below 2 the same warning as given 
for --'
+                              'quiet applies!')
+
+        out_opts.add_argument('-W',
+                              '--width',
+                              action = 'store',
+                              type = int,
+                              default = 0,
+                              help = 'Sets the screen width. This setting is 
usually '
+                              'not required as layman is capable of detecting 
the '
+                              'available number of columns automatically.')
+
+        out_opts.add_argument('-k',
+                              '--nocheck',
+                              action = 'store_true',
+                              help = 'Do not check overlay definitions and do 
not i'
+                              'ssue a warning if description or contact 
information'
+                              ' are missing.')
+
+        out_opts.add_argument('--debug-level',
+                              action = 'store',
+                              type = int,
+                              help = 'A value between 0 and 10. 0 means no 
debugging '
+                              'messages will be selected, 10 selects all 
debugging me'
+                              'ssages. Default is "4".')
 
         #-----------------------------------------------------------------
         # Debug Options
@@ -251,45 +255,46 @@ class ArgsParser(BareConfig):
 
         # Parse the command line first since we need to get the config
         # file option.
-        if len(args) == 1:
-            self.output.notice('Usage:%s' % _USAGE)
-            sys.exit(0)
 
-        (self.options, remain_args) = self.parser.parse_args(args)
-        # remain_args starts with something like "bin/layman" ...
-        if len(remain_args) > 1:
-            self.parser.error("ArgsParser(): Unhandled parameters: %s"
-                % ', '.join(('"%s"' % e) for e in remain_args[1:]))
+        # If no flags are present print out usage
+        if len(sys.argv) == 1:
+            self.output.notice('usage:%s' % _USAGE)
+            sys.exit(0)
 
-        # handle debugging
-        #self.output.cli_handle(self.options)
+        self.options = self.parser.parse_args()
+        self.options = vars(self.options)
+        # Applying interpolation of values
+        for v in ['configdir', 'config', 'overlay_defs']:
+            self.options[v] = self.options[v] % self.options
+            self.defaults[v] = self.options[v]
 
-        if (self.options.__dict__.has_key('debug_level') and
-            self.options.__dict__['debug_level']):
-            dbglvl = int(self.options.__dict__['debug_level'])
+        if ('debug_level' in self.options and
+            self.options['debug_level']):
+            dbglvl = int(self.options['debug_level'])
             if dbglvl < 0:
                 dbglvl = 0
             if dbglvl > 10:
                 dbglvl = 10
             self.output.set_debug_level(dbglvl)
 
-        if self.options.__dict__['nocolor']:
+        if self.options['nocolor']:
             self.output.set_colorize(OFF)
 
         # Set only alternate config settings from the options
-        if self.options.__dict__['config'] is not None:
-            self.defaults['config'] = self.options.__dict__['config']
+        if self.options['config'] is not None:
+            self.defaults['config'] = self.options['config']
             self.output.debug('ARGSPARSER: Got config file at ' + \
                 self.defaults['config'], 8)
         else: # fix the config path
             self.defaults['config'] = self.defaults['config'] \
                 % {'configdir': self.defaults['configdir']}
-        if self.options.__dict__['overlay_defs'] is not None:
-            self.defaults['overlay_defs'] = 
self.options.__dict__['overlay_defs']
+
+        if self.options['overlay_defs'] is not None:
+            self.defaults['overlay_defs'] = self.options['overlay_defs']
             self.output.debug('ARGSPARSER: Got overlay_defs location at ' + \
                 self.defaults['overlay_defs'], 8)
 
-        self._options['setup_help'] = self.options.__dict__['setup_help']
+        self._options['setup_help'] = self.options['setup_help']
 
         # Now parse the config file
         self.output.debug('ARGSPARSER: Reading config file at ' + \
@@ -297,19 +302,19 @@ class ArgsParser(BareConfig):
         self.read_config(self.defaults)
 
         # handle quietness
-        if self.options.__dict__['quiet']:
+        if self.options['quiet']:
             self.set_option('quiet', True)
-        elif self.options.__dict__['quietness']:
-            self.set_option('quietness', self.options.__dict__['quietness'])
+        elif self.options['quietness']:
+            self.set_option('quietness', self.options['quietness'])
 
 
     def __getitem__(self, key):
 
         if key == 'overlays':
             overlays = ''
-            if (key in list(self.options.__dict__.keys())
-                and not self.options.__dict__[key] is None):
-                overlays = '\n'.join(self.options.__dict__[key])
+            if (key in list(self.options.keys())
+                and not self.options[key] is None):
+                overlays = '\n'.join(self.options[key])
             if self.config.has_option('MAIN', 'overlays'):
                 overlays += '\n' + self.config.get('MAIN', 'overlays')
             if len(overlays):
@@ -317,9 +322,9 @@ class ArgsParser(BareConfig):
 
         self.output.debug('ARGSPARSER: Retrieving options option: %s' % key, 9)
 
-        if (key in list(self.options.__dict__.keys())
-            and not self.options.__dict__[key] is None):
-            return self.options.__dict__[key]
+        if (key in list(self.options.keys())
+            and not self.options[key] is False):
+            return self.options[key]
 
         self.output.debug('ARGSPARSER: Retrieving config option: %s' % key, 9)
 
@@ -346,8 +351,9 @@ class ArgsParser(BareConfig):
 
         self.output.debug('ARGSPARSER: Retrieving keys', 9)
 
-        keys = [i for i in list(self.options.__dict__.keys())
-                if not self.options.__dict__[i] is None]
+        keys = [i for i in list(self.options)
+                if not self.options[i] is False
+                and not self.options[i] is None]
 
         self.output.debug('ARGSPARSER: Retrieving keys 2', 9)
 
@@ -358,7 +364,6 @@ class ArgsParser(BareConfig):
 
         keys += [i for i in list(self.defaults.keys())
                  if not i in keys]
-
         self.output.debug('ARGSPARSER: Returning keys', 9)
 
         return keys

Reply via email to