[PATCH] teach createrepo to use optparse

James Bowes <[email protected]>
Newsgroups gmane.linux.rpm.metadata
Message-ID <[email protected]>
Hi all:

The attached patch switches createrepo from using getopt to optparse.

-James

_______________________________________________
Rpm-metadata mailing list
[email protected]
https://lists.dulug.duke.edu/mailman/listinfo/rpm-metadata
createrepo-use-optparse.patch (text/x-patch, 9.5 KB)
? .genpkgmetadata.py.swp
Index: genpkgmetadata.py
===================================================================
RCS file: /cvsroot/metadata/cvs-root/generate/genpkgmetadata.py,v
retrieving revision 1.69
diff -u -r1.69 genpkgmetadata.py
--- genpkgmetadata.py	16 May 2007 08:05:44 -0000	1.69
+++ genpkgmetadata.py	24 May 2007 00:10:42 -0000
@@ -29,6 +29,8 @@
 import fnmatch
 import shutil
 
+from optparse import OptionParser
+
 import dumpMetadata
 from dumpMetadata import _gzipOpen
 __version__ = '0.4.9'
@@ -40,30 +42,8 @@
     """Stub function for translation"""
     return args
 
-def usage(retval=1):
-    print _("""
-    createrepo [options] directory-of-packages
-
-    Options:
-     -u, --baseurl <url> = optional base url location for all files
-     -o, --outputdir <dir> = optional directory to output to
-     -x, --exclude = files globs to exclude, can be specified multiple times
-     -q, --quiet = run quietly
-     -n, --noepoch = don't add zero epochs for non-existent epochs
-                    (incompatible with yum and smart but required for
-                     systems with rpm < 4.2.1)
-     -g, --groupfile <filename> to point to for group information (precreated)
-                    (<filename> relative to directory-of-packages)
-     -v, --verbose = run verbosely
-     -c, --cachedir <dir> = specify which dir to use for the checksum cache
-     -C, --checkts = don't generate repo metadata, if their ctimes are newer
-                     than the rpm ctimes.
-     -h, --help = show this help
-     -V, --version = output version
-     -p, --pretty = output xml files in pretty format.
-     -d, --database = generate the sqlite databases.
-    """)
-
+def usage(parser, retval=1):
+    parser.print_usage()
     sys.exit(retval)
 
 class MetaDataGenerator:
@@ -363,108 +343,74 @@
        Parse the command line args return a commands dict and directory.
        Sanity check all the things being passed in.
     """
+    parser = OptionParser(version=__version__,
+            usage="%prog [options] directory-of-packages")
+    parser.add_option('-u', '--baseurl',
+            help='optional base url location for all files')
+    parser.add_option('-o', '--outputdir', default='',
+            help='optional directory to output to')
+    parser.add_option('-x', '--exclude', action='append', default=[],
+            help='files globs to exclude, can be specified multiple times')
+    parser.add_option('-q', '--quiet', action='store_true', help='run quietly')
+    parser.add_option('-n', '--noepoch', action='store_true',
+            help="don't add zero epochs for non-existent epochs "
+            "(incompatible with yum and smart but required for systems with "
+            "rpm < 4.2.1)")
+    parser.add_option('-g', '--groupfile', help='file to point to for group '
+            'information (precreated) relative to directory-of-packages')
+    parser.add_option('-v', '--verbose', action='store_true',
+            help='run verbosely')
+    parser.add_option('-c', '--cachedir',
+            help='specify which dir to use for the checksum cache')
+    parser.add_option('-C', '--checkts', action='store_true',
+            help="don't generate repo metadata, if their ctimes are newer "
+            "than the rpm ctimes.")
+    parser.add_option('-p', '--pretty', action='store_true',
+            help='output xml files in pretty format.')
+    parser.add_option('-d', '--database', action='store_true',
+            help='generate the sqlite databases.')
+    parser.add_option('--split', action='store_true')
+    parser.add_option('-S', '--skip-symlinks', action='store_true')
+    parser.add_option('--basedir', default=os.getcwd())
+    parser.add_option('-s', '--checksum', action='store_true',
+            help="This option is deprecated")
+
+    opts, argsleft = parser.parse_args(args)
+
     cmds = {}
-    cmds['quiet'] = 0
-    cmds['verbose'] = 0
-    cmds['excludes'] = []
-    cmds['baseurl'] = None
-    cmds['groupfile'] = None
+    cmds['quiet'] = opts.quiet
+    cmds['verbose'] = opts.verbose
+    cmds['excludes'] = opts.exclude
+    cmds['baseurl'] = opts.baseurl
+    cmds['groupfile'] = opts.groupfile
+    cmds['noepoch'] = opts.noepoch
+    cmds['pretty'] = opts.pretty
+    cmds['cachedir'] = opts.cachedir
+    cmds['basedir'] = opts.basedir
+    cmds['cache'] = opts.cachedir is not None
+    cmds['checkts'] = opts.checkts
+    cmds['split'] = opts.split
+    cmds['database'] = opts.database
+    cmds['outputdir'] = opts.outputdir
+    cmds['skip-symlinks'] = opts.skip_symlinks
+    
     cmds['sumtype'] = 'sha'
-    cmds['noepoch'] = False
-    cmds['pretty'] = 0
-#    cmds['updategroupsonly'] = 0
-    cmds['cachedir'] = None
-    cmds['basedir'] = os.getcwd()
-    cmds['cache'] = False
-    cmds['checkts'] = False
     cmds['mdtimestamp'] = 0
-    cmds['split'] = False
-    cmds['outputdir'] = ""
-    cmds['database'] = False
     cmds['file-pattern-match'] = ['.*bin\/.*', '^\/etc\/.*', '^\/usr\/lib\/sendmail$']
     cmds['dir-pattern-match'] = ['.*bin\/.*', '^\/etc\/.*']
-    cmds['skip-symlinks'] = False
-
-    try:
-        gopts, argsleft = getopt.getopt(args, 'phqVvndg:s:x:u:c:o:CS', ['help', 'exclude=',
-                                                                  'quiet', 'verbose', 'cachedir=', 'basedir=',
-                                                                  'baseurl=', 'groupfile=', 'checksum=',
-                                                                  'version', 'pretty', 'split', 'outputdir=',
-                                                                  'noepoch', 'checkts', 'database', 
-                                                                  'skip-symlinks'])
-    except getopt.error, e:
-        errorprint(_('Options Error: %s.') % e)
-        usage()
-
-    try:
-        for arg,a in gopts:
-            if arg in ['-h','--help']:
-                usage(retval=0)
-            elif arg in ['-V', '--version']:
-                print '%s' % __version__
-                sys.exit(0)
-            elif arg == '--split':
-                cmds['split'] = True
-    except ValueError, e:
-        errorprint(_('Options Error: %s') % e)
-        usage()
-
 
     # make sure our dir makes sense before we continue
     if len(argsleft) > 1 and not cmds['split']:
         errorprint(_('Error: Only one directory allowed per run.'))
-        usage()
+        usage(parser)
     elif len(argsleft) == 0:
         errorprint(_('Error: Must specify a directory to index.'))
-        usage()
+        usage(parser)
     else:
         directories = argsleft
 
-    try:
-        for arg,a in gopts:
-            if arg in ['-v', '--verbose']:
-                cmds['verbose'] = 1
-            elif arg in ["-q", '--quiet']:
-                cmds['quiet'] = 1
-            elif arg in ['-u', '--baseurl']:
-                if cmds['baseurl'] is not None:
-                    errorprint(_('Error: Only one baseurl allowed.'))
-                    usage()
-                else:
-                    cmds['baseurl'] = a
-            elif arg in ['-g', '--groupfile']:
-                if cmds['groupfile'] is not None:
-                    errorprint(_('Error: Only one groupfile allowed.'))
-                    usage()
-                else:
-                    cmds['groupfile'] = a
-            elif arg in ['-x', '--exclude']:
-                cmds['excludes'].append(a)
-            elif arg in ['-p', '--pretty']:
-                cmds['pretty'] = 1
-#            elif arg in ['--update-groups-only']:
-#                cmds['updategroupsonly'] = 1
-            elif arg in ['-s', '--checksum']:
-                errorprint(_('This option is deprecated'))
-            elif arg in ['-c', '--cachedir']:
-                cmds['cache'] = True
-                cmds['cachedir'] = a
-            elif arg in ['-C', '--checkts']:
-                cmds['checkts'] = True
-            elif arg == '--basedir':
-                cmds['basedir'] = a
-            elif arg in ['-o','--outputdir']:
-                cmds['outputdir'] = a
-            elif arg in ['-n', '--noepoch']:
-                cmds['noepoch'] = True
-            elif arg in ['-d', '--database']:
-                cmds['database'] = True
-            elif arg in ['-S', '--skip-symlinks']:
-                cmds['skip-symlinks'] = True
-                
-    except ValueError, e:
-        errorprint(_('Options Error: %s') % e)
-        usage()
+    if opts.checksum:
+        errorprint(_('This option is deprecated'))
 
     if cmds['split'] and cmds['checkts']:
         errorprint(_('--split and --checkts options are mutually exclusive'))
@@ -490,7 +436,7 @@
             a = os.path.join(cmds['basedir'], directory, cmds['groupfile'])
         if not os.path.exists(a):
             errorprint(_('Error: groupfile %s cannot be found.' % a))
-            usage()
+            usage(parser)
         cmds['groupfile'] = a
     if cmds['cachedir']:
         a = cmds ['cachedir']
@@ -498,7 +444,7 @@
             a = os.path.join(cmds['outputdir'] ,a)
         if not checkAndMakeDir(a):
             errorprint(_('Error: cannot open/write to cache dir %s' % a))
-            usage()
+            usage(parser)
         cmds['cachedir'] = a
 
     #setup some defaults
@@ -552,7 +498,7 @@
             if os.path.exists(filepath):
                 if not os.access(filepath, os.W_OK):
                     errorprint(_('error in must be able to write to metadata files:\n  -> %s') % filepath)
-                    usage()
+                    usage(parser)
                 if cmds['checkts']:
                     ts = os.path.getctime(filepath)
                     if ts > cmds['mdtimestamp']:
signature.asc (application/pgp-signature, 189 B)
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.7 (GNU/Linux)

iD8DBQFGVNnsk5ELBPTV5gERAvjIAJ47BZeKG2EXcVx4gSy3uH4YmqdpmQCfYUB0
yXSHfRVygFEoMju8w9lu2Ok=
=IeRd
-----END PGP SIGNATURE-----
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.