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

Python code coverage for Lib/distutils/fancy_getopt.py

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