ยปCore Development>Code coverage>Lib/packaging/fancy_getopt.py

Python code coverage for Lib/packaging/fancy_getopt.py

#countcontent
1n/a"""Command line parsing machinery.
2n/a
3n/aThe FancyGetopt class is a Wrapper around the getopt module that
4n/aprovides the following additional features:
5n/a * short and long options are tied together
6n/a * options have help strings, so fancy_getopt could potentially
7n/a create a complete usage summary
8n/a * options set attributes of a passed-in object.
9n/a
10n/aIt is used under the hood by the command classes. Do not use directly.
11n/a"""
12n/a
13n/aimport getopt
14n/aimport re
15n/aimport sys
16n/aimport textwrap
17n/a
18n/afrom packaging.errors import PackagingGetoptError, PackagingArgError
19n/a
20n/a# Much like command_re in packaging.core, this is close to but not quite
21n/a# the same as a Python NAME -- except, in the spirit of most GNU
22n/a# utilities, we use '-' in place of '_'. (The spirit of LISP lives on!)
23n/a# The similarities to NAME are again not a coincidence...
24n/alongopt_pat = r'[a-zA-Z](?:[a-zA-Z0-9-]*)'
25n/alongopt_re = re.compile(r'^%s$' % longopt_pat)
26n/a
27n/a# For recognizing "negative alias" options, eg. "quiet=!verbose"
28n/aneg_alias_re = re.compile("^(%s)=!(%s)$" % (longopt_pat, longopt_pat))
29n/a
30n/a
31n/aclass FancyGetopt:
32n/a """Wrapper around the standard 'getopt()' module that provides some
33n/a handy extra functionality:
34n/a * short and long options are tied together
35n/a * options have help strings, and help text can be assembled
36n/a from them
37n/a * options set attributes of a passed-in object
38n/a * boolean options can have "negative aliases" -- eg. if
39n/a --quiet is the "negative alias" of --verbose, then "--quiet"
40n/a on the command line sets 'verbose' to false
41n/a """
42n/a
43n/a def __init__(self, option_table=None):
44n/a
45n/a # The option table is (currently) a list of tuples. The
46n/a # tuples may have 3 or four values:
47n/a # (long_option, short_option, help_string [, repeatable])
48n/a # if an option takes an argument, its long_option should have '='
49n/a # appended; short_option should just be a single character, no ':'
50n/a # in any case. If a long_option doesn't have a corresponding
51n/a # short_option, short_option should be None. All option tuples
52n/a # must have long options.
53n/a self.option_table = option_table
54n/a
55n/a # 'option_index' maps long option names to entries in the option
56n/a # table (ie. those 3-tuples).
57n/a self.option_index = {}
58n/a if self.option_table:
59n/a self._build_index()
60n/a
61n/a # 'alias' records (duh) alias options; {'foo': 'bar'} means
62n/a # --foo is an alias for --bar
63n/a self.alias = {}
64n/a
65n/a # 'negative_alias' keeps track of options that are the boolean
66n/a # opposite of some other option
67n/a self.negative_alias = {}
68n/a
69n/a # These keep track of the information in the option table. We
70n/a # don't actually populate these structures until we're ready to
71n/a # parse the command line, since the 'option_table' passed in here
72n/a # isn't necessarily the final word.
73n/a self.short_opts = []
74n/a self.long_opts = []
75n/a self.short2long = {}
76n/a self.attr_name = {}
77n/a self.takes_arg = {}
78n/a
79n/a # And 'option_order' is filled up in 'getopt()'; it records the
80n/a # original order of options (and their values) on the command line,
81n/a # but expands short options, converts aliases, etc.
82n/a self.option_order = []
83n/a
84n/a def _build_index(self):
85n/a self.option_index.clear()
86n/a for option in self.option_table:
87n/a self.option_index[option[0]] = option
88n/a
89n/a def set_option_table(self, option_table):
90n/a self.option_table = option_table
91n/a self._build_index()
92n/a
93n/a def add_option(self, long_option, short_option=None, help_string=None):
94n/a if long_option in self.option_index:
95n/a raise PackagingGetoptError(
96n/a "option conflict: already an option '%s'" % long_option)
97n/a else:
98n/a option = (long_option, short_option, help_string)
99n/a self.option_table.append(option)
100n/a self.option_index[long_option] = option
101n/a
102n/a def has_option(self, long_option):
103n/a """Return true if the option table for this parser has an
104n/a option with long name 'long_option'."""
105n/a return long_option in self.option_index
106n/a
107n/a def _check_alias_dict(self, aliases, what):
108n/a assert isinstance(aliases, dict)
109n/a for alias, opt in aliases.items():
110n/a if alias not in self.option_index:
111n/a raise PackagingGetoptError(
112n/a ("invalid %s '%s': "
113n/a "option '%s' not defined") % (what, alias, alias))
114n/a if opt not in self.option_index:
115n/a raise PackagingGetoptError(
116n/a ("invalid %s '%s': "
117n/a "aliased option '%s' not defined") % (what, alias, opt))
118n/a
119n/a def set_aliases(self, alias):
120n/a """Set the aliases for this option parser."""
121n/a self._check_alias_dict(alias, "alias")
122n/a self.alias = alias
123n/a
124n/a def set_negative_aliases(self, negative_alias):
125n/a """Set the negative aliases for this option parser.
126n/a 'negative_alias' should be a dictionary mapping option names to
127n/a option names, both the key and value must already be defined
128n/a in the option table."""
129n/a self._check_alias_dict(negative_alias, "negative alias")
130n/a self.negative_alias = negative_alias
131n/a
132n/a def _grok_option_table(self):
133n/a """Populate the various data structures that keep tabs on the
134n/a option table. Called by 'getopt()' before it can do anything
135n/a worthwhile.
136n/a """
137n/a self.long_opts = []
138n/a self.short_opts = []
139n/a self.short2long.clear()
140n/a self.repeat = {}
141n/a
142n/a for option in self.option_table:
143n/a if len(option) == 3:
144n/a longopt, short, help = option
145n/a repeat = 0
146n/a elif len(option) == 4:
147n/a longopt, short, help, repeat = option
148n/a else:
149n/a # the option table is part of the code, so simply
150n/a # assert that it is correct
151n/a raise ValueError("invalid option tuple: %r" % option)
152n/a
153n/a # Type- and value-check the option names
154n/a if not isinstance(longopt, str) or len(longopt) < 2:
155n/a raise PackagingGetoptError(
156n/a ("invalid long option '%s': "
157n/a "must be a string of length >= 2") % longopt)
158n/a
159n/a if (not ((short is None) or
160n/a (isinstance(short, str) and len(short) == 1))):
161n/a raise PackagingGetoptError(
162n/a ("invalid short option '%s': "
163n/a "must be a single character or None") % short)
164n/a
165n/a self.repeat[longopt] = repeat
166n/a self.long_opts.append(longopt)
167n/a
168n/a if longopt[-1] == '=': # option takes an argument?
169n/a if short:
170n/a short = short + ':'
171n/a longopt = longopt[0:-1]
172n/a self.takes_arg[longopt] = 1
173n/a else:
174n/a
175n/a # Is option is a "negative alias" for some other option (eg.
176n/a # "quiet" == "!verbose")?
177n/a alias_to = self.negative_alias.get(longopt)
178n/a if alias_to is not None:
179n/a if self.takes_arg[alias_to]:
180n/a raise PackagingGetoptError(
181n/a ("invalid negative alias '%s': "
182n/a "aliased option '%s' takes a value") % \
183n/a (longopt, alias_to))
184n/a
185n/a self.long_opts[-1] = longopt # XXX redundant?!
186n/a self.takes_arg[longopt] = 0
187n/a
188n/a else:
189n/a self.takes_arg[longopt] = 0
190n/a
191n/a # If this is an alias option, make sure its "takes arg" flag is
192n/a # the same as the option it's aliased to.
193n/a alias_to = self.alias.get(longopt)
194n/a if alias_to is not None:
195n/a if self.takes_arg[longopt] != self.takes_arg[alias_to]:
196n/a raise PackagingGetoptError(
197n/a ("invalid alias '%s': inconsistent with "
198n/a "aliased option '%s' (one of them takes a value, "
199n/a "the other doesn't") % (longopt, alias_to))
200n/a
201n/a # Now enforce some bondage on the long option name, so we can
202n/a # later translate it to an attribute name on some object. Have
203n/a # to do this a bit late to make sure we've removed any trailing
204n/a # '='.
205n/a if not longopt_re.match(longopt):
206n/a raise PackagingGetoptError(
207n/a ("invalid long option name '%s' " +
208n/a "(must be letters, numbers, hyphens only") % longopt)
209n/a
210n/a self.attr_name[longopt] = longopt.replace('-', '_')
211n/a if short:
212n/a self.short_opts.append(short)
213n/a self.short2long[short[0]] = longopt
214n/a
215n/a def getopt(self, args=None, object=None):
216n/a """Parse command-line options in args. Store as attributes on object.
217n/a
218n/a If 'args' is None or not supplied, uses 'sys.argv[1:]'. If
219n/a 'object' is None or not supplied, creates a new OptionDummy
220n/a object, stores option values there, and returns a tuple (args,
221n/a object). If 'object' is supplied, it is modified in place and
222n/a 'getopt()' just returns 'args'; in both cases, the returned
223n/a 'args' is a modified copy of the passed-in 'args' list, which
224n/a is left untouched.
225n/a """
226n/a if args is None:
227n/a args = sys.argv[1:]
228n/a if object is None:
229n/a object = OptionDummy()
230n/a created_object = 1
231n/a else:
232n/a created_object = 0
233n/a
234n/a self._grok_option_table()
235n/a
236n/a short_opts = ' '.join(self.short_opts)
237n/a
238n/a try:
239n/a opts, args = getopt.getopt(args, short_opts, self.long_opts)
240n/a except getopt.error as msg:
241n/a raise PackagingArgError(msg)
242n/a
243n/a for opt, val in opts:
244n/a if len(opt) == 2 and opt[0] == '-': # it's a short option
245n/a opt = self.short2long[opt[1]]
246n/a else:
247n/a assert len(opt) > 2 and opt[:2] == '--'
248n/a opt = opt[2:]
249n/a
250n/a alias = self.alias.get(opt)
251n/a if alias:
252n/a opt = alias
253n/a
254n/a if not self.takes_arg[opt]: # boolean option?
255n/a assert val == '', "boolean option can't have value"
256n/a alias = self.negative_alias.get(opt)
257n/a if alias:
258n/a opt = alias
259n/a val = 0
260n/a else:
261n/a val = 1
262n/a
263n/a attr = self.attr_name[opt]
264n/a # The only repeating option at the moment is 'verbose'.
265n/a # It has a negative option -q quiet, which should set verbose = 0.
266n/a if val and self.repeat.get(attr) is not None:
267n/a val = getattr(object, attr, 0) + 1
268n/a setattr(object, attr, val)
269n/a self.option_order.append((opt, val))
270n/a
271n/a # for opts
272n/a if created_object:
273n/a return args, object
274n/a else:
275n/a return args
276n/a
277n/a def get_option_order(self):
278n/a """Returns the list of (option, value) tuples processed by the
279n/a previous run of 'getopt()'. Raises RuntimeError if
280n/a 'getopt()' hasn't been called yet.
281n/a """
282n/a if self.option_order is None:
283n/a raise RuntimeError("'getopt()' hasn't been called yet")
284n/a else:
285n/a return self.option_order
286n/a
287n/a return self.option_order
288n/a
289n/a def generate_help(self, header=None):
290n/a """Generate help text (a list of strings, one per suggested line of
291n/a output) from the option table for this FancyGetopt object.
292n/a """
293n/a # Blithely assume the option table is good: probably wouldn't call
294n/a # 'generate_help()' unless you've already called 'getopt()'.
295n/a
296n/a # First pass: determine maximum length of long option names
297n/a max_opt = 0
298n/a for option in self.option_table:
299n/a longopt = option[0]
300n/a short = option[1]
301n/a l = len(longopt)
302n/a if longopt[-1] == '=':
303n/a l = l - 1
304n/a if short is not None:
305n/a l = l + 5 # " (-x)" where short == 'x'
306n/a if l > max_opt:
307n/a max_opt = l
308n/a
309n/a opt_width = max_opt + 2 + 2 + 2 # room for indent + dashes + gutter
310n/a
311n/a # Typical help block looks like this:
312n/a # --foo controls foonabulation
313n/a # Help block for longest option looks like this:
314n/a # --flimflam set the flim-flam level
315n/a # and with wrapped text:
316n/a # --flimflam set the flim-flam level (must be between
317n/a # 0 and 100, except on Tuesdays)
318n/a # Options with short names will have the short name shown (but
319n/a # it doesn't contribute to max_opt):
320n/a # --foo (-f) controls foonabulation
321n/a # If adding the short option would make the left column too wide,
322n/a # we push the explanation off to the next line
323n/a # --flimflam (-l)
324n/a # set the flim-flam level
325n/a # Important parameters:
326n/a # - 2 spaces before option block start lines
327n/a # - 2 dashes for each long option name
328n/a # - min. 2 spaces between option and explanation (gutter)
329n/a # - 5 characters (incl. space) for short option name
330n/a
331n/a # Now generate lines of help text. (If 80 columns were good enough
332n/a # for Jesus, then 78 columns are good enough for me!)
333n/a line_width = 78
334n/a text_width = line_width - opt_width
335n/a big_indent = ' ' * opt_width
336n/a if header:
337n/a lines = [header]
338n/a else:
339n/a lines = ['Option summary:']
340n/a
341n/a for option in self.option_table:
342n/a longopt, short, help = option[:3]
343n/a text = textwrap.wrap(help, text_width)
344n/a
345n/a # Case 1: no short option at all (makes life easy)
346n/a if short is None:
347n/a if text:
348n/a lines.append(" --%-*s %s" % (max_opt, longopt, text[0]))
349n/a else:
350n/a lines.append(" --%-*s " % (max_opt, longopt))
351n/a
352n/a # Case 2: we have a short option, so we have to include it
353n/a # just after the long option
354n/a else:
355n/a opt_names = "%s (-%s)" % (longopt, short)
356n/a if text:
357n/a lines.append(" --%-*s %s" %
358n/a (max_opt, opt_names, text[0]))
359n/a else:
360n/a lines.append(" --%-*s" % opt_names)
361n/a
362n/a for l in text[1:]:
363n/a lines.append(big_indent + l)
364n/a
365n/a return lines
366n/a
367n/a def print_help(self, header=None, file=None):
368n/a if file is None:
369n/a file = sys.stdout
370n/a for line in self.generate_help(header):
371n/a file.write(line + "\n")
372n/a
373n/a
374n/adef fancy_getopt(options, negative_opt, object, args):
375n/a parser = FancyGetopt(options)
376n/a parser.set_negative_aliases(negative_opt)
377n/a return parser.getopt(args, object)
378n/a
379n/a
380n/aclass OptionDummy:
381n/a """Dummy class just used as a place to hold command-line option
382n/a values as instance attributes."""
383n/a
384n/a def __init__(self, options=[]):
385n/a """Create a new OptionDummy instance. The attributes listed in
386n/a 'options' will be initialized to None."""
387n/a for opt in options:
388n/a setattr(self, opt, None)