Gentoo Archives: gentoo-catalyst

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

Replies

Subject Author
Re: [gentoo-catalyst] [PATCH 4/4] main: switch to argparse Brian Dolbec <dolsen@g.o>