Gentoo Archives: gentoo-catalyst

From: Brian Dolbec <dolsen@g.o>
To: gentoo-catalyst@l.g.o
Subject: Re: [gentoo-catalyst] [PATCH 4/4] main: switch to argparse
Date: Tue, 06 Oct 2015 16:54:56
Message-Id: 20151006095401.63c90216.dolsen@gentoo.org
In Reply to: [gentoo-catalyst] [PATCH 4/4] main: switch to argparse by Mike Frysinger
1 On Tue, 6 Oct 2015 12:46:29 -0400
2 Mike Frysinger <vapier@g.o> wrote:
3
4 > Switch from ad-hoc getopt parsing to the more powerful/standard
5 > argparse. ---
6 > catalyst/main.py | 191
7 > +++++++++++++++++++++++++------------------------------ 1 file
8 > changed, 85 insertions(+), 106 deletions(-)
9 >
10 > diff --git a/catalyst/main.py b/catalyst/main.py
11 > index 604c6ab..2a25df4 100644
12 > --- a/catalyst/main.py
13 > +++ b/catalyst/main.py
14 > @@ -6,9 +6,9 @@
15 > # Chris Gianelloni <wolf31o2@××××××××.org>
16 > # $Id$
17 >
18 > +import argparse
19 > import os
20 > import sys
21 > -import getopt
22 > import os.path
23 >
24 > __selfpath__ = os.path.abspath(os.path.dirname(__file__))
25 > @@ -28,35 +28,6 @@ from catalyst.version import get_version
26 > conf_values={}
27 >
28 >
29 > -def usage():
30 > - print """Usage catalyst [options] [-C variable=value...]
31 > [ -s identifier]
32 > - -a --clear-autoresume clear autoresume flags
33 > - -c --config use specified configuration file
34 > - -C --cli catalyst commandline (MUST BE LAST OPTION)
35 > - -d --debug enable debugging
36 > - -f --file read specfile
37 > - -F --fetchonly fetch files only
38 > - -h --help print this help message
39 > - -p --purge clear tmp dirs,package cache, autoresume
40 > flags
41 > - -P --purgeonly clear tmp dirs,package cache, autoresume
42 > flags and exit
43 > - -T --purgetmponly clear tmp dirs and autoresume flags and exit
44 > - -s --snapshot generate a release snapshot
45 > - -V --version display version information
46 > - -v --verbose verbose output
47 > -
48 > -Usage examples:
49 > -
50 > -Using the commandline option (-C, --cli) to build a Portage snapshot:
51 > -catalyst -C target=snapshot version_stamp=my_date
52 > -
53 > -Using the snapshot option (-s, --snapshot) to build a release
54 > snapshot: -catalyst -s 20071121"
55 > -
56 > -Using the specfile option (-f, --file) to build a stage target:
57 > -catalyst -f stage1-specfile.spec
58 > -"""
59 > -
60 > -
61 > def version():
62 > print get_version()
63 > print "Copyright 2003-2008 Gentoo Foundation"
64 > @@ -167,96 +138,104 @@ def build_target(addlargs):
65 > return target.run()
66 >
67 >
68 > -def main():
69 > - # we need some options in order to work correctly
70 > - if len(sys.argv) < 2:
71 > - usage()
72 > - sys.exit(2)
73 > -
74 > - # parse out the command line arguments
75 > - try:
76 > - opts, _args = getopt.getopt(sys.argv[1:],
77 > "apPThvdc:C:f:FVs:", ["purge", "purgeonly", "purgetmponly", "help",
78 > "version", "debug",
79 > - "clear-autoresume", "config=", "cli=",
80 > "file=", "fetch", "verbose","snapshot="]) -
81 > - except getopt.GetoptError:
82 > - usage()
83 > - sys.exit(2)
84 > -
85 > - myconfig=""
86 > - myspecfile=""
87 > - mycmdline=[]
88 > -
89 > - # check preconditions
90 > - if len(opts) == 0:
91 > - print "!!! catalyst: please specify one of either -f
92 > or -C\n"
93 > - usage()
94 > - sys.exit(2)
95 > -
96 > - options = set()
97 > -
98 > - run = False
99 > - for o, a in opts:
100 > - if o in ("-h", "--help"):
101 > - version()
102 > - usage()
103 > - sys.exit(1)
104 > +class FilePath(object):
105 > + """Argparse type for getting a path to a file."""
106 >
107 > - if o in ("-V", "--version"):
108 > - print get_version()
109 > - sys.exit(1)
110 > + def __init__(self, exists=True):
111 > + self.exists = exists
112 >
113 > - if o in ("-d", "--debug"):
114 > - conf_values["DEBUG"] = True
115 > - conf_values["VERBOSE"] = True
116 > + def __call__(self, string):
117 > + if not os.path.exists(string):
118 > + raise argparse.ArgumentTypeError('file does
119 > not exist: %s' % string)
120 > + return string
121 >
122 > - if o in ("-c", "--config"):
123 > - myconfig=a
124 > + def __repr__(self):
125 > + return '%s(exists=%s)' % (type(self).__name__,
126 > self.exists)
127 > - if o in ("-C", "--cli"):
128 > - run = True
129 > - x=sys.argv.index(o)+1
130 > - while x < len(sys.argv):
131 > - mycmdline.append(sys.argv[x])
132 > - x=x+1
133 >
134 > - if o in ("-f", "--file"):
135 > - run = True
136 > - myspecfile=a
137 > +def get_parser():
138 > + """Return an argument parser"""
139 > + epilog = """Usage examples:
140 >
141 > - if o in ("-F", "--fetchonly"):
142 > - options.add("fetch")
143 > +Using the commandline option (-C, --cli) to build a Portage snapshot:
144 > +$ catalyst -C target=snapshot version_stamp=my_date
145 >
146 > - if o in ("-v", "--verbose"):
147 > - conf_values["VERBOSE"]="1"
148 > +Using the snapshot option (-s, --snapshot) to build a release
149 > snapshot: +$ catalyst -s 20071121
150 >
151 > - if o in ("-s", "--snapshot"):
152 > - if len(sys.argv) < 3:
153 > - print "!!! catalyst: missing
154 > snapshot identifier\n"
155 > - usage()
156 > - sys.exit(2)
157 > - else:
158 > - run = True
159 > - mycmdline.append("target=snapshot")
160 > - mycmdline.append("version_stamp="+a)
161 > +Using the specfile option (-f, --file) to build a stage target:
162 > +$ catalyst -f stage1-specfile.spec"""
163 > +
164 > + parser = argparse.ArgumentParser(epilog=epilog,
165 > formatter_class=argparse.RawDescriptionHelpFormatter)
166 > + parser.add_argument('-d', '--debug',
167 > + default=False, action='store_true',
168 > + help='enable debugging')
169 > + parser.add_argument('-v', '--verbose',
170 > + default=False, action='store_true',
171 > + help='verbose output')
172 > + parser.add_argument('-c', '--config',
173 > + type=FilePath(),
174 > + help='use specified configuration file')
175 > + parser.add_argument('-f', '--file',
176 > + type=FilePath(),
177 > + help='read specfile')
178 > + parser.add_argument('-F', '--fetchonly',
179 > + default=False, action='store_true',
180 > + help='fetch files only')
181 > + parser.add_argument('-a', '--clear-autoresume',
182 > + default=False, action='store_true',
183 > + help='clear autoresume flags')
184 > + parser.add_argument('-p', '--purge',
185 > + default=False, action='store_true',
186 > + help='clear tmp dirs, package cache, autoresume
187 > flags')
188 > + parser.add_argument('-P', '--purgeonly',
189 > + default=False, action='store_true',
190 > + help='clear tmp dirs, package cache, autoresume
191 > flags and exit')
192 > + parser.add_argument('-T', '--purgetmponly',
193 > + default=False, action='store_true',
194 > + help='clear tmp dirs and autoresume flags and exit')
195 > + parser.add_argument('-s', '--snapshot',
196 > + help='generate a release snapshot')
197 > + parser.add_argument('-V', '--version',
198 > + action='version', version=get_version(),
199 > + help='display version information')
200 > + parser.add_argument('-C', '--cli',
201 > + default=[], nargs=argparse.REMAINDER,
202 > + help='catalyst commandline (MUST BE LAST OPTION)')
203 > + return parser
204 >
205 > - if o in ("-p", "--purge"):
206 > - options.add("purge")
207 >
208 > - if o in ("-P", "--purgeonly"):
209 > - options.add("purgeonly")
210 > +def main():
211 > + parser = get_parser()
212 > + opts = parser.parse_args(sys.argv[1:])
213 >
214 > - if o in ("-T", "--purgetmponly"):
215 > - options.add("purgetmponly")
216 > + # Parse the command line options.
217 > + myconfig = opts.config
218 > + myspecfile = opts.file
219 > + mycmdline = opts.cli[:]
220 >
221 > - if o in ("-a", "--clear-autoresume"):
222 > - options.add("clear-autoresume")
223 > + if opts.snapshot:
224 > + mycmdline.append('target=snapshot')
225 > + mycmdline.append('version_stamp=' + opts.snapshot)
226 >
227 > - #print "MAIN: cli options =", options
228 > + conf_values['DEBUG'] = opts.debug
229 > + conf_values['VERBOSE'] = opts.debug or opts.verbose
230 >
231 > - if not run:
232 > - print "!!! catalyst: please specify one of either -f
233 > or -C\n"
234 > - usage()
235 > - sys.exit(2)
236 > + options = set()
237 > + if opts.fetchonly:
238 > + options.add('fetch')
239 > + if opts.purge:
240 > + options.add('purge')
241 > + if opts.purgeonly:
242 > + options.add('purgeonly')
243 > + if opts.purgetmponly:
244 > + options.add('purgetmponly')
245 > + if opts.clear_autoresume:
246 > + options.add('clear-autoresume')
247 > +
248 > + # Make sure we have some work before moving further.
249 > + if not myspecfile and not mycmdline:
250 > + parser.error('please specify one of either -f or -C
251 > or -s')
252 > # made it this far so start by outputting our version info
253 > version()
254
255 Wow, your chipping away at the long TODO list at a fast pace :)
256
257 all 4 are good to merge.
258
259 --
260 Brian Dolbec <dolsen>