9c3df525aff62cd10779233820e86b4d25e5b257
[scons.git] / src / engine / SCons / compat / _scons_optparse.py
1 """optparse - a powerful, extensible, and easy-to-use option parser.
2
3 By Greg Ward <gward@python.net>
4
5 Originally distributed as Optik; see http://optik.sourceforge.net/ .
6
7 If you have problems with this module, please do not file bugs,
8 patches, or feature requests with Python; instead, use Optik's
9 SourceForge project page:
10   http://sourceforge.net/projects/optik
11
12 For support, use the optik-users@lists.sourceforge.net mailing list
13 (http://lists.sourceforge.net/lists/listinfo/optik-users).
14 """
15
16 # Python developers: please do not make changes to this file, since
17 # it is automatically generated from the Optik source code.
18
19 __version__ = "1.5.3"
20
21 __all__ = ['Option',
22            'SUPPRESS_HELP',
23            'SUPPRESS_USAGE',
24            'Values',
25            'OptionContainer',
26            'OptionGroup',
27            'OptionParser',
28            'HelpFormatter',
29            'IndentedHelpFormatter',
30            'TitledHelpFormatter',
31            'OptParseError',
32            'OptionError',
33            'OptionConflictError',
34            'OptionValueError',
35            'BadOptionError']
36
37 __copyright__ = """
38 Copyright (c) 2001-2006 Gregory P. Ward.  All rights reserved.
39 Copyright (c) 2002-2006 Python Software Foundation.  All rights reserved.
40
41 Redistribution and use in source and binary forms, with or without
42 modification, are permitted provided that the following conditions are
43 met:
44
45   * Redistributions of source code must retain the above copyright
46     notice, this list of conditions and the following disclaimer.
47
48   * Redistributions in binary form must reproduce the above copyright
49     notice, this list of conditions and the following disclaimer in the
50     documentation and/or other materials provided with the distribution.
51
52   * Neither the name of the author nor the names of its
53     contributors may be used to endorse or promote products derived from
54     this software without specific prior written permission.
55
56 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
57 IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
58 TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
59 PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR
60 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
61 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
62 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
63 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
64 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
65 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
66 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
67 """
68
69 import sys, os
70 import types
71 import textwrap
72
73 def _repr(self):
74     return "<%s at 0x%x: %s>" % (self.__class__.__name__, id(self), self)
75
76
77 try:
78     sys.getdefaultencoding
79 except AttributeError:
80     def fake_getdefaultencoding():
81         return None
82     sys.getdefaultencoding = fake_getdefaultencoding
83
84 try:
85     ''.encode
86 except AttributeError:
87     def encode_wrapper(s, encoding, replacement):
88         return s
89 else:
90     def encode_wrapper(s, encoding, replacement):
91         return s.encode(encoding, replacement)
92
93
94 # This file was generated from:
95 #   Id: option_parser.py 527 2006-07-23 15:21:30Z greg
96 #   Id: option.py 522 2006-06-11 16:22:03Z gward
97 #   Id: help.py 527 2006-07-23 15:21:30Z greg
98 #   Id: errors.py 509 2006-04-20 00:58:24Z gward
99
100 try:
101     from gettext import gettext
102 except ImportError:
103     def gettext(message):
104         return message
105 _ = gettext
106
107
108 class OptParseError (Exception):
109     def __init__(self, msg):
110         self.msg = msg
111
112     def __str__(self):
113         return self.msg
114
115
116 class OptionError (OptParseError):
117     """
118     Raised if an Option instance is created with invalid or
119     inconsistent arguments.
120     """
121
122     def __init__(self, msg, option):
123         self.msg = msg
124         self.option_id = str(option)
125
126     def __str__(self):
127         if self.option_id:
128             return "option %s: %s" % (self.option_id, self.msg)
129         else:
130             return self.msg
131
132 class OptionConflictError (OptionError):
133     """
134     Raised if conflicting options are added to an OptionParser.
135     """
136
137 class OptionValueError (OptParseError):
138     """
139     Raised if an invalid option value is encountered on the command
140     line.
141     """
142
143 class BadOptionError (OptParseError):
144     """
145     Raised if an invalid option is seen on the command line.
146     """
147     def __init__(self, opt_str):
148         self.opt_str = opt_str
149
150     def __str__(self):
151         return _("no such option: %s") % self.opt_str
152
153 class AmbiguousOptionError (BadOptionError):
154     """
155     Raised if an ambiguous option is seen on the command line.
156     """
157     def __init__(self, opt_str, possibilities):
158         BadOptionError.__init__(self, opt_str)
159         self.possibilities = possibilities
160
161     def __str__(self):
162         return (_("ambiguous option: %s (%s?)")
163                 % (self.opt_str, ", ".join(self.possibilities)))
164
165
166 class HelpFormatter:
167
168     """
169     Abstract base class for formatting option help.  OptionParser
170     instances should use one of the HelpFormatter subclasses for
171     formatting help; by default IndentedHelpFormatter is used.
172
173     Instance attributes:
174       parser : OptionParser
175         the controlling OptionParser instance
176       indent_increment : int
177         the number of columns to indent per nesting level
178       max_help_position : int
179         the maximum starting column for option help text
180       help_position : int
181         the calculated starting column for option help text;
182         initially the same as the maximum
183       width : int
184         total number of columns for output (pass None to constructor for
185         this value to be taken from the $COLUMNS environment variable)
186       level : int
187         current indentation level
188       current_indent : int
189         current indentation level (in columns)
190       help_width : int
191         number of columns available for option help text (calculated)
192       default_tag : str
193         text to replace with each option's default value, "%default"
194         by default.  Set to false value to disable default value expansion.
195       option_strings : { Option : str }
196         maps Option instances to the snippet of help text explaining
197         the syntax of that option, e.g. "-h, --help" or
198         "-fFILE, --file=FILE"
199       _short_opt_fmt : str
200         format string controlling how short options with values are
201         printed in help text.  Must be either "%s%s" ("-fFILE") or
202         "%s %s" ("-f FILE"), because those are the two syntaxes that
203         Optik supports.
204       _long_opt_fmt : str
205         similar but for long options; must be either "%s %s" ("--file FILE")
206         or "%s=%s" ("--file=FILE").
207     """
208
209     NO_DEFAULT_VALUE = "none"
210
211     def __init__(self,
212                  indent_increment,
213                  max_help_position,
214                  width,
215                  short_first):
216         self.parser = None
217         self.indent_increment = indent_increment
218         self.help_position = self.max_help_position = max_help_position
219         if width is None:
220             try:
221                 width = int(os.environ['COLUMNS'])
222             except (KeyError, ValueError):
223                 width = 80
224             width = width - 2
225         self.width = width
226         self.current_indent = 0
227         self.level = 0
228         self.help_width = None          # computed later
229         self.short_first = short_first
230         self.default_tag = "%default"
231         self.option_strings = {}
232         self._short_opt_fmt = "%s %s"
233         self._long_opt_fmt = "%s=%s"
234
235     def set_parser(self, parser):
236         self.parser = parser
237
238     def set_short_opt_delimiter(self, delim):
239         if delim not in ("", " "):
240             raise ValueError(
241                 "invalid metavar delimiter for short options: %r" % delim)
242         self._short_opt_fmt = "%s" + delim + "%s"
243
244     def set_long_opt_delimiter(self, delim):
245         if delim not in ("=", " "):
246             raise ValueError(
247                 "invalid metavar delimiter for long options: %r" % delim)
248         self._long_opt_fmt = "%s" + delim + "%s"
249
250     def indent(self):
251         self.current_indent = self.current_indent + self.indent_increment
252         self.level = self.level + 1
253
254     def dedent(self):
255         self.current_indent = self.current_indent - self.indent_increment
256         assert self.current_indent >= 0, "Indent decreased below 0."
257         self.level = self.level - 1
258
259     def format_usage(self, usage):
260         raise NotImplementedError, "subclasses must implement"
261
262     def format_heading(self, heading):
263         raise NotImplementedError, "subclasses must implement"
264
265     def _format_text(self, text):
266         """
267         Format a paragraph of free-form text for inclusion in the
268         help output at the current indentation level.
269         """
270         text_width = self.width - self.current_indent
271         indent = " "*self.current_indent
272         return textwrap.fill(text,
273                              text_width,
274                              initial_indent=indent,
275                              subsequent_indent=indent)
276
277     def format_description(self, description):
278         if description:
279             return self._format_text(description) + "\n"
280         else:
281             return ""
282
283     def format_epilog(self, epilog):
284         if epilog:
285             return "\n" + self._format_text(epilog) + "\n"
286         else:
287             return ""
288
289
290     def expand_default(self, option):
291         if self.parser is None or not self.default_tag:
292             return option.help
293
294         default_value = self.parser.defaults.get(option.dest)
295         if default_value is NO_DEFAULT or default_value is None:
296             default_value = self.NO_DEFAULT_VALUE
297
298         return option.help.replace(self.default_tag, str(default_value))
299
300     def format_option(self, option):
301         # The help for each option consists of two parts:
302         #   * the opt strings and metavars
303         #     eg. ("-x", or "-fFILENAME, --file=FILENAME")
304         #   * the user-supplied help string
305         #     eg. ("turn on expert mode", "read data from FILENAME")
306         #
307         # If possible, we write both of these on the same line:
308         #   -x      turn on expert mode
309         #
310         # But if the opt string list is too long, we put the help
311         # string on a second line, indented to the same column it would
312         # start in if it fit on the first line.
313         #   -fFILENAME, --file=FILENAME
314         #           read data from FILENAME
315         result = []
316         opts = self.option_strings[option]
317         opt_width = self.help_position - self.current_indent - 2
318         if len(opts) > opt_width:
319             opts = "%*s%s\n" % (self.current_indent, "", opts)
320             indent_first = self.help_position
321         else:                       # start help on same line as opts
322             opts = "%*s%-*s  " % (self.current_indent, "", opt_width, opts)
323             indent_first = 0
324         result.append(opts)
325         if option.help:
326             help_text = self.expand_default(option)
327             help_lines = textwrap.wrap(help_text, self.help_width)
328             result.append("%*s%s\n" % (indent_first, "", help_lines[0]))
329             for line in help_lines[1:]:
330                 result.append("%*s%s\n" % (self.help_position, "", line))
331         elif opts[-1] != "\n":
332             result.append("\n")
333         return "".join(result)
334
335     def store_option_strings(self, parser):
336         self.indent()
337         max_len = 0
338         for opt in parser.option_list:
339             strings = self.format_option_strings(opt)
340             self.option_strings[opt] = strings
341             max_len = max(max_len, len(strings) + self.current_indent)
342         self.indent()
343         for group in parser.option_groups:
344             for opt in group.option_list:
345                 strings = self.format_option_strings(opt)
346                 self.option_strings[opt] = strings
347                 max_len = max(max_len, len(strings) + self.current_indent)
348         self.dedent()
349         self.dedent()
350         self.help_position = min(max_len + 2, self.max_help_position)
351         self.help_width = self.width - self.help_position
352
353     def format_option_strings(self, option):
354         """Return a comma-separated list of option strings & metavariables."""
355         if option.takes_value():
356             metavar = option.metavar or option.dest.upper()
357             short_opts = []
358             for sopt in option._short_opts:
359                 short_opts.append(self._short_opt_fmt % (sopt, metavar))
360             long_opts = []
361             for lopt in option._long_opts:
362                 long_opts.append(self._long_opt_fmt % (lopt, metavar))
363         else:
364             short_opts = option._short_opts
365             long_opts = option._long_opts
366
367         if self.short_first:
368             opts = short_opts + long_opts
369         else:
370             opts = long_opts + short_opts
371
372         return ", ".join(opts)
373
374 class IndentedHelpFormatter (HelpFormatter):
375     """Format help with indented section bodies.
376     """
377
378     def __init__(self,
379                  indent_increment=2,
380                  max_help_position=24,
381                  width=None,
382                  short_first=1):
383         HelpFormatter.__init__(
384             self, indent_increment, max_help_position, width, short_first)
385
386     def format_usage(self, usage):
387         return _("Usage: %s\n") % usage
388
389     def format_heading(self, heading):
390         return "%*s%s:\n" % (self.current_indent, "", heading)
391
392
393 class TitledHelpFormatter (HelpFormatter):
394     """Format help with underlined section headers.
395     """
396
397     def __init__(self,
398                  indent_increment=0,
399                  max_help_position=24,
400                  width=None,
401                  short_first=0):
402         HelpFormatter.__init__ (
403             self, indent_increment, max_help_position, width, short_first)
404
405     def format_usage(self, usage):
406         return "%s  %s\n" % (self.format_heading(_("Usage")), usage)
407
408     def format_heading(self, heading):
409         return "%s\n%s\n" % (heading, "=-"[self.level] * len(heading))
410
411
412 def _parse_num(val, type):
413     if val[:2].lower() == "0x":         # hexadecimal
414         radix = 16
415     elif val[:2].lower() == "0b":       # binary
416         radix = 2
417         val = val[2:] or "0"            # have to remove "0b" prefix
418     elif val[:1] == "0":                # octal
419         radix = 8
420     else:                               # decimal
421         radix = 10
422
423     return type(val, radix)
424
425 def _parse_int(val):
426     return _parse_num(val, int)
427
428 def _parse_long(val):
429     return _parse_num(val, long)
430
431 try:
432     int('0', 10)
433 except TypeError:
434     # Python 1.5.2 doesn't allow a radix value to be passed to int().
435     _parse_int = int
436
437 try:
438     long('0', 10)
439 except TypeError:
440     # Python 1.5.2 doesn't allow a radix value to be passed to long().
441     _parse_long = long
442
443 _builtin_cvt = { "int" : (_parse_int, _("integer")),
444                  "long" : (_parse_long, _("long integer")),
445                  "float" : (float, _("floating-point")),
446                  "complex" : (complex, _("complex")) }
447
448 def check_builtin(option, opt, value):
449     (cvt, what) = _builtin_cvt[option.type]
450     try:
451         return cvt(value)
452     except ValueError:
453         raise OptionValueError(
454             _("option %s: invalid %s value: %r") % (opt, what, value))
455
456 def check_choice(option, opt, value):
457     if value in option.choices:
458         return value
459     else:
460         choices = ", ".join(map(repr, option.choices))
461         raise OptionValueError(
462             _("option %s: invalid choice: %r (choose from %s)")
463             % (opt, value, choices))
464
465 # Not supplying a default is different from a default of None,
466 # so we need an explicit "not supplied" value.
467 NO_DEFAULT = ("NO", "DEFAULT")
468
469
470 class Option:
471     """
472     Instance attributes:
473       _short_opts : [string]
474       _long_opts : [string]
475
476       action : string
477       type : string
478       dest : string
479       default : any
480       nargs : int
481       const : any
482       choices : [string]
483       callback : function
484       callback_args : (any*)
485       callback_kwargs : { string : any }
486       help : string
487       metavar : string
488     """
489
490     # The list of instance attributes that may be set through
491     # keyword args to the constructor.
492     ATTRS = ['action',
493              'type',
494              'dest',
495              'default',
496              'nargs',
497              'const',
498              'choices',
499              'callback',
500              'callback_args',
501              'callback_kwargs',
502              'help',
503              'metavar']
504
505     # The set of actions allowed by option parsers.  Explicitly listed
506     # here so the constructor can validate its arguments.
507     ACTIONS = ("store",
508                "store_const",
509                "store_true",
510                "store_false",
511                "append",
512                "append_const",
513                "count",
514                "callback",
515                "help",
516                "version")
517
518     # The set of actions that involve storing a value somewhere;
519     # also listed just for constructor argument validation.  (If
520     # the action is one of these, there must be a destination.)
521     STORE_ACTIONS = ("store",
522                      "store_const",
523                      "store_true",
524                      "store_false",
525                      "append",
526                      "append_const",
527                      "count")
528
529     # The set of actions for which it makes sense to supply a value
530     # type, ie. which may consume an argument from the command line.
531     TYPED_ACTIONS = ("store",
532                      "append",
533                      "callback")
534
535     # The set of actions which *require* a value type, ie. that
536     # always consume an argument from the command line.
537     ALWAYS_TYPED_ACTIONS = ("store",
538                             "append")
539
540     # The set of actions which take a 'const' attribute.
541     CONST_ACTIONS = ("store_const",
542                      "append_const")
543
544     # The set of known types for option parsers.  Again, listed here for
545     # constructor argument validation.
546     TYPES = ("string", "int", "long", "float", "complex", "choice")
547
548     # Dictionary of argument checking functions, which convert and
549     # validate option arguments according to the option type.
550     #
551     # Signature of checking functions is:
552     #   check(option : Option, opt : string, value : string) -> any
553     # where
554     #   option is the Option instance calling the checker
555     #   opt is the actual option seen on the command-line
556     #     (eg. "-a", "--file")
557     #   value is the option argument seen on the command-line
558     #
559     # The return value should be in the appropriate Python type
560     # for option.type -- eg. an integer if option.type == "int".
561     #
562     # If no checker is defined for a type, arguments will be
563     # unchecked and remain strings.
564     TYPE_CHECKER = { "int"    : check_builtin,
565                      "long"   : check_builtin,
566                      "float"  : check_builtin,
567                      "complex": check_builtin,
568                      "choice" : check_choice,
569                    }
570
571
572     # CHECK_METHODS is a list of unbound method objects; they are called
573     # by the constructor, in order, after all attributes are
574     # initialized.  The list is created and filled in later, after all
575     # the methods are actually defined.  (I just put it here because I
576     # like to define and document all class attributes in the same
577     # place.)  Subclasses that add another _check_*() method should
578     # define their own CHECK_METHODS list that adds their check method
579     # to those from this class.
580     CHECK_METHODS = None
581
582
583     # -- Constructor/initialization methods ----------------------------
584
585     def __init__(self, *opts, **attrs):
586         # Set _short_opts, _long_opts attrs from 'opts' tuple.
587         # Have to be set now, in case no option strings are supplied.
588         self._short_opts = []
589         self._long_opts = []
590         opts = self._check_opt_strings(opts)
591         self._set_opt_strings(opts)
592
593         # Set all other attrs (action, type, etc.) from 'attrs' dict
594         self._set_attrs(attrs)
595
596         # Check all the attributes we just set.  There are lots of
597         # complicated interdependencies, but luckily they can be farmed
598         # out to the _check_*() methods listed in CHECK_METHODS -- which
599         # could be handy for subclasses!  The one thing these all share
600         # is that they raise OptionError if they discover a problem.
601         for checker in self.CHECK_METHODS:
602             checker(self)
603
604     def _check_opt_strings(self, opts):
605         # Filter out None because early versions of Optik had exactly
606         # one short option and one long option, either of which
607         # could be None.
608         opts = [_f for _f in opts if _f]
609         if not opts:
610             raise TypeError("at least one option string must be supplied")
611         return opts
612
613     def _set_opt_strings(self, opts):
614         for opt in opts:
615             if len(opt) < 2:
616                 raise OptionError(
617                     "invalid option string %r: "
618                     "must be at least two characters long" % opt, self)
619             elif len(opt) == 2:
620                 if not (opt[0] == "-" and opt[1] != "-"):
621                     raise OptionError(
622                         "invalid short option string %r: "
623                         "must be of the form -x, (x any non-dash char)" % opt,
624                         self)
625                 self._short_opts.append(opt)
626             else:
627                 if not (opt[0:2] == "--" and opt[2] != "-"):
628                     raise OptionError(
629                         "invalid long option string %r: "
630                         "must start with --, followed by non-dash" % opt,
631                         self)
632                 self._long_opts.append(opt)
633
634     def _set_attrs(self, attrs):
635         for attr in self.ATTRS:
636             if attr in attrs:
637                 setattr(self, attr, attrs[attr])
638                 del attrs[attr]
639             else:
640                 if attr == 'default':
641                     setattr(self, attr, NO_DEFAULT)
642                 else:
643                     setattr(self, attr, None)
644         if attrs:
645             attrs = sorted(attrs.keys())
646             raise OptionError(
647                 "invalid keyword arguments: %s" % ", ".join(attrs),
648                 self)
649
650
651     # -- Constructor validation methods --------------------------------
652
653     def _check_action(self):
654         if self.action is None:
655             self.action = "store"
656         elif self.action not in self.ACTIONS:
657             raise OptionError("invalid action: %r" % self.action, self)
658
659     def _check_type(self):
660         if self.type is None:
661             if self.action in self.ALWAYS_TYPED_ACTIONS:
662                 if self.choices is not None:
663                     # The "choices" attribute implies "choice" type.
664                     self.type = "choice"
665                 else:
666                     # No type given?  "string" is the most sensible default.
667                     self.type = "string"
668         else:
669             # Allow type objects or builtin type conversion functions
670             # (int, str, etc.) as an alternative to their names.
671             if isinstance(self.type, type):
672                 self.type = self.type.__name__
673
674             if self.type == "str":
675                 self.type = "string"
676
677             if self.type not in self.TYPES:
678                 raise OptionError("invalid option type: %r" % self.type, self)
679             if self.action not in self.TYPED_ACTIONS:
680                 raise OptionError(
681                     "must not supply a type for action %r" % self.action, self)
682
683     def _check_choice(self):
684         if self.type == "choice":
685             if self.choices is None:
686                 raise OptionError(
687                     "must supply a list of choices for type 'choice'", self)
688             elif type(self.choices) not in (tuple, list):
689                 raise OptionError(
690                     "choices must be a list of strings ('%s' supplied)"
691                     % str(type(self.choices)).split("'")[1], self)
692         elif self.choices is not None:
693             raise OptionError(
694                 "must not supply choices for type %r" % self.type, self)
695
696     def _check_dest(self):
697         # No destination given, and we need one for this action.  The
698         # self.type check is for callbacks that take a value.
699         takes_value = (self.action in self.STORE_ACTIONS or
700                        self.type is not None)
701         if self.dest is None and takes_value:
702
703             # Glean a destination from the first long option string,
704             # or from the first short option string if no long options.
705             if self._long_opts:
706                 # eg. "--foo-bar" -> "foo_bar"
707                 self.dest = self._long_opts[0][2:].replace('-', '_')
708             else:
709                 self.dest = self._short_opts[0][1]
710
711     def _check_const(self):
712         if self.action not in self.CONST_ACTIONS and self.const is not None:
713             raise OptionError(
714                 "'const' must not be supplied for action %r" % self.action,
715                 self)
716
717     def _check_nargs(self):
718         if self.action in self.TYPED_ACTIONS:
719             if self.nargs is None:
720                 self.nargs = 1
721         elif self.nargs is not None:
722             raise OptionError(
723                 "'nargs' must not be supplied for action %r" % self.action,
724                 self)
725
726     def _check_callback(self):
727         if self.action == "callback":
728             if not callable(self.callback):
729                 raise OptionError(
730                     "callback not callable: %r" % self.callback, self)
731             if (self.callback_args is not None and
732                 not isinstance(self.callback_args, tuple)):
733                 raise OptionError(
734                     "callback_args, if supplied, must be a tuple: not %r"
735                     % self.callback_args, self)
736             if (self.callback_kwargs is not None and
737                 not isinstance(self.callback_kwargs, dict)):
738                 raise OptionError(
739                     "callback_kwargs, if supplied, must be a dict: not %r"
740                     % self.callback_kwargs, self)
741         else:
742             if self.callback is not None:
743                 raise OptionError(
744                     "callback supplied (%r) for non-callback option"
745                     % self.callback, self)
746             if self.callback_args is not None:
747                 raise OptionError(
748                     "callback_args supplied for non-callback option", self)
749             if self.callback_kwargs is not None:
750                 raise OptionError(
751                     "callback_kwargs supplied for non-callback option", self)
752
753
754     CHECK_METHODS = [_check_action,
755                      _check_type,
756                      _check_choice,
757                      _check_dest,
758                      _check_const,
759                      _check_nargs,
760                      _check_callback]
761
762
763     # -- Miscellaneous methods -----------------------------------------
764
765     def __str__(self):
766         return "/".join(self._short_opts + self._long_opts)
767
768     __repr__ = _repr
769
770     def takes_value(self):
771         return self.type is not None
772
773     def get_opt_string(self):
774         if self._long_opts:
775             return self._long_opts[0]
776         else:
777             return self._short_opts[0]
778
779
780     # -- Processing methods --------------------------------------------
781
782     def check_value(self, opt, value):
783         checker = self.TYPE_CHECKER.get(self.type)
784         if checker is None:
785             return value
786         else:
787             return checker(self, opt, value)
788
789     def convert_value(self, opt, value):
790         if value is not None:
791             if self.nargs == 1:
792                 return self.check_value(opt, value)
793             else:
794                 return tuple([self.check_value(opt, v) for v in value])
795
796     def process(self, opt, value, values, parser):
797
798         # First, convert the value(s) to the right type.  Howl if any
799         # value(s) are bogus.
800         value = self.convert_value(opt, value)
801
802         # And then take whatever action is expected of us.
803         # This is a separate method to make life easier for
804         # subclasses to add new actions.
805         return self.take_action(
806             self.action, self.dest, opt, value, values, parser)
807
808     def take_action(self, action, dest, opt, value, values, parser):
809         if action == "store":
810             setattr(values, dest, value)
811         elif action == "store_const":
812             setattr(values, dest, self.const)
813         elif action == "store_true":
814             setattr(values, dest, True)
815         elif action == "store_false":
816             setattr(values, dest, False)
817         elif action == "append":
818             values.ensure_value(dest, []).append(value)
819         elif action == "append_const":
820             values.ensure_value(dest, []).append(self.const)
821         elif action == "count":
822             setattr(values, dest, values.ensure_value(dest, 0) + 1)
823         elif action == "callback":
824             args = self.callback_args or ()
825             kwargs = self.callback_kwargs or {}
826             self.callback(self, opt, value, parser, *args, **kwargs)
827         elif action == "help":
828             parser.print_help()
829             parser.exit()
830         elif action == "version":
831             parser.print_version()
832             parser.exit()
833         else:
834             raise RuntimeError, "unknown action %r" % self.action
835
836         return 1
837
838 # class Option
839
840
841 SUPPRESS_HELP = "SUPPRESS"+"HELP"
842 SUPPRESS_USAGE = "SUPPRESS"+"USAGE"
843
844 # For compatibility with Python 2.2
845 try:
846     True, False
847 except NameError:
848     (True, False) = (1, 0)
849
850 try: unicode
851 except NameError:
852     def isbasestring(x):
853         return isinstance(x, str)
854 else:
855     def isbasestring(x):
856         return isinstance(x, str) or isinstance(x, unicode)
857
858 class Values:
859
860     def __init__(self, defaults=None):
861         if defaults:
862             for (attr, val) in defaults.items():
863                 setattr(self, attr, val)
864
865     def __str__(self):
866         return str(self.__dict__)
867
868     __repr__ = _repr
869
870     def __cmp__(self, other):
871         if isinstance(other, Values):
872             return cmp(self.__dict__, other.__dict__)
873         elif isinstance(other, dict):
874             return cmp(self.__dict__, other)
875         else:
876             return -1
877
878     def _update_careful(self, dict):
879         """
880         Update the option values from an arbitrary dictionary, but only
881         use keys from dict that already have a corresponding attribute
882         in self.  Any keys in dict without a corresponding attribute
883         are silently ignored.
884         """
885         for attr in dir(self):
886             if attr in dict:
887                 dval = dict[attr]
888                 if dval is not None:
889                     setattr(self, attr, dval)
890
891     def _update_loose(self, dict):
892         """
893         Update the option values from an arbitrary dictionary,
894         using all keys from the dictionary regardless of whether
895         they have a corresponding attribute in self or not.
896         """
897         self.__dict__.update(dict)
898
899     def _update(self, dict, mode):
900         if mode == "careful":
901             self._update_careful(dict)
902         elif mode == "loose":
903             self._update_loose(dict)
904         else:
905             raise ValueError, "invalid update mode: %r" % mode
906
907     def read_module(self, modname, mode="careful"):
908         __import__(modname)
909         mod = sys.modules[modname]
910         self._update(vars(mod), mode)
911
912     def read_file(self, filename, mode="careful"):
913         vars = {}
914         exec open(filename, 'rU').read() in vars
915         self._update(vars, mode)
916
917     def ensure_value(self, attr, value):
918         if not hasattr(self, attr) or getattr(self, attr) is None:
919             setattr(self, attr, value)
920         return getattr(self, attr)
921
922
923 class OptionContainer:
924
925     """
926     Abstract base class.
927
928     Class attributes:
929       standard_option_list : [Option]
930         list of standard options that will be accepted by all instances
931         of this parser class (intended to be overridden by subclasses).
932
933     Instance attributes:
934       option_list : [Option]
935         the list of Option objects contained by this OptionContainer
936       _short_opt : { string : Option }
937         dictionary mapping short option strings, eg. "-f" or "-X",
938         to the Option instances that implement them.  If an Option
939         has multiple short option strings, it will appears in this
940         dictionary multiple times. [1]
941       _long_opt : { string : Option }
942         dictionary mapping long option strings, eg. "--file" or
943         "--exclude", to the Option instances that implement them.
944         Again, a given Option can occur multiple times in this
945         dictionary. [1]
946       defaults : { string : any }
947         dictionary mapping option destination names to default
948         values for each destination [1]
949
950     [1] These mappings are common to (shared by) all components of the
951         controlling OptionParser, where they are initially created.
952
953     """
954
955     def __init__(self, option_class, conflict_handler, description):
956         # Initialize the option list and related data structures.
957         # This method must be provided by subclasses, and it must
958         # initialize at least the following instance attributes:
959         # option_list, _short_opt, _long_opt, defaults.
960         self._create_option_list()
961
962         self.option_class = option_class
963         self.set_conflict_handler(conflict_handler)
964         self.set_description(description)
965
966     def _create_option_mappings(self):
967         # For use by OptionParser constructor -- create the master
968         # option mappings used by this OptionParser and all
969         # OptionGroups that it owns.
970         self._short_opt = {}            # single letter -> Option instance
971         self._long_opt = {}             # long option -> Option instance
972         self.defaults = {}              # maps option dest -> default value
973
974
975     def _share_option_mappings(self, parser):
976         # For use by OptionGroup constructor -- use shared option
977         # mappings from the OptionParser that owns this OptionGroup.
978         self._short_opt = parser._short_opt
979         self._long_opt = parser._long_opt
980         self.defaults = parser.defaults
981
982     def set_conflict_handler(self, handler):
983         if handler not in ("error", "resolve"):
984             raise ValueError, "invalid conflict_resolution value %r" % handler
985         self.conflict_handler = handler
986
987     def set_description(self, description):
988         self.description = description
989
990     def get_description(self):
991         return self.description
992
993
994     def destroy(self):
995         """see OptionParser.destroy()."""
996         del self._short_opt
997         del self._long_opt
998         del self.defaults
999
1000
1001     # -- Option-adding methods -----------------------------------------
1002
1003     def _check_conflict(self, option):
1004         conflict_opts = []
1005         for opt in option._short_opts:
1006             if opt in self._short_opt:
1007                 conflict_opts.append((opt, self._short_opt[opt]))
1008         for opt in option._long_opts:
1009             if opt in self._long_opt:
1010                 conflict_opts.append((opt, self._long_opt[opt]))
1011
1012         if conflict_opts:
1013             handler = self.conflict_handler
1014             if handler == "error":
1015                 raise OptionConflictError(
1016                     "conflicting option string(s): %s"
1017                     % ", ".join([co[0] for co in conflict_opts]),
1018                     option)
1019             elif handler == "resolve":
1020                 for (opt, c_option) in conflict_opts:
1021                     if opt[:2] == "--":
1022                         c_option._long_opts.remove(opt)
1023                         del self._long_opt[opt]
1024                     else:
1025                         c_option._short_opts.remove(opt)
1026                         del self._short_opt[opt]
1027                     if not (c_option._short_opts or c_option._long_opts):
1028                         c_option.container.option_list.remove(c_option)
1029
1030     def add_option(self, *args, **kwargs):
1031         """add_option(Option)
1032            add_option(opt_str, ..., kwarg=val, ...)
1033         """
1034         if isinstance(args[0], str):
1035             option = self.option_class(*args, **kwargs)
1036         elif len(args) == 1 and not kwargs:
1037             option = args[0]
1038             if not isinstance(option, Option):
1039                 raise TypeError, "not an Option instance: %r" % option
1040         else:
1041             raise TypeError, "invalid arguments"
1042
1043         self._check_conflict(option)
1044
1045         self.option_list.append(option)
1046         option.container = self
1047         for opt in option._short_opts:
1048             self._short_opt[opt] = option
1049         for opt in option._long_opts:
1050             self._long_opt[opt] = option
1051
1052         if option.dest is not None:     # option has a dest, we need a default
1053             if option.default is not NO_DEFAULT:
1054                 self.defaults[option.dest] = option.default
1055             elif option.dest not in self.defaults:
1056                 self.defaults[option.dest] = None
1057
1058         return option
1059
1060     def add_options(self, option_list):
1061         for option in option_list:
1062             self.add_option(option)
1063
1064     # -- Option query/removal methods ----------------------------------
1065
1066     def get_option(self, opt_str):
1067         return (self._short_opt.get(opt_str) or
1068                 self._long_opt.get(opt_str))
1069
1070     def has_option(self, opt_str):
1071         return (opt_str in self._short_opt or
1072                 opt_str in self._long_opt)
1073
1074     def remove_option(self, opt_str):
1075         option = self._short_opt.get(opt_str)
1076         if option is None:
1077             option = self._long_opt.get(opt_str)
1078         if option is None:
1079             raise ValueError("no such option %r" % opt_str)
1080
1081         for opt in option._short_opts:
1082             del self._short_opt[opt]
1083         for opt in option._long_opts:
1084             del self._long_opt[opt]
1085         option.container.option_list.remove(option)
1086
1087
1088     # -- Help-formatting methods ---------------------------------------
1089
1090     def format_option_help(self, formatter):
1091         if not self.option_list:
1092             return ""
1093         result = []
1094         for option in self.option_list:
1095             if not option.help is SUPPRESS_HELP:
1096                 result.append(formatter.format_option(option))
1097         return "".join(result)
1098
1099     def format_description(self, formatter):
1100         return formatter.format_description(self.get_description())
1101
1102     def format_help(self, formatter):
1103         result = []
1104         if self.description:
1105             result.append(self.format_description(formatter))
1106         if self.option_list:
1107             result.append(self.format_option_help(formatter))
1108         return "\n".join(result)
1109
1110
1111 class OptionGroup (OptionContainer):
1112
1113     def __init__(self, parser, title, description=None):
1114         self.parser = parser
1115         OptionContainer.__init__(
1116             self, parser.option_class, parser.conflict_handler, description)
1117         self.title = title
1118
1119     def _create_option_list(self):
1120         self.option_list = []
1121         self._share_option_mappings(self.parser)
1122
1123     def set_title(self, title):
1124         self.title = title
1125
1126     def destroy(self):
1127         """see OptionParser.destroy()."""
1128         OptionContainer.destroy(self)
1129         del self.option_list
1130
1131     # -- Help-formatting methods ---------------------------------------
1132
1133     def format_help(self, formatter):
1134         result = formatter.format_heading(self.title)
1135         formatter.indent()
1136         result = result + OptionContainer.format_help(self, formatter)
1137         formatter.dedent()
1138         return result
1139
1140
1141 class OptionParser (OptionContainer):
1142
1143     """
1144     Class attributes:
1145       standard_option_list : [Option]
1146         list of standard options that will be accepted by all instances
1147         of this parser class (intended to be overridden by subclasses).
1148
1149     Instance attributes:
1150       usage : string
1151         a usage string for your program.  Before it is displayed
1152         to the user, "%prog" will be expanded to the name of
1153         your program (self.prog or os.path.basename(sys.argv[0])).
1154       prog : string
1155         the name of the current program (to override
1156         os.path.basename(sys.argv[0])).
1157       epilog : string
1158         paragraph of help text to print after option help
1159
1160       option_groups : [OptionGroup]
1161         list of option groups in this parser (option groups are
1162         irrelevant for parsing the command-line, but very useful
1163         for generating help)
1164
1165       allow_interspersed_args : bool = true
1166         if true, positional arguments may be interspersed with options.
1167         Assuming -a and -b each take a single argument, the command-line
1168           -ablah foo bar -bboo baz
1169         will be interpreted the same as
1170           -ablah -bboo -- foo bar baz
1171         If this flag were false, that command line would be interpreted as
1172           -ablah -- foo bar -bboo baz
1173         -- ie. we stop processing options as soon as we see the first
1174         non-option argument.  (This is the tradition followed by
1175         Python's getopt module, Perl's Getopt::Std, and other argument-
1176         parsing libraries, but it is generally annoying to users.)
1177
1178       process_default_values : bool = true
1179         if true, option default values are processed similarly to option
1180         values from the command line: that is, they are passed to the
1181         type-checking function for the option's type (as long as the
1182         default value is a string).  (This really only matters if you
1183         have defined custom types; see SF bug #955889.)  Set it to false
1184         to restore the behaviour of Optik 1.4.1 and earlier.
1185
1186       rargs : [string]
1187         the argument list currently being parsed.  Only set when
1188         parse_args() is active, and continually trimmed down as
1189         we consume arguments.  Mainly there for the benefit of
1190         callback options.
1191       largs : [string]
1192         the list of leftover arguments that we have skipped while
1193         parsing options.  If allow_interspersed_args is false, this
1194         list is always empty.
1195       values : Values
1196         the set of option values currently being accumulated.  Only
1197         set when parse_args() is active.  Also mainly for callbacks.
1198
1199     Because of the 'rargs', 'largs', and 'values' attributes,
1200     OptionParser is not thread-safe.  If, for some perverse reason, you
1201     need to parse command-line arguments simultaneously in different
1202     threads, use different OptionParser instances.
1203
1204     """
1205
1206     standard_option_list = []
1207
1208     def __init__(self,
1209                  usage=None,
1210                  option_list=None,
1211                  option_class=Option,
1212                  version=None,
1213                  conflict_handler="error",
1214                  description=None,
1215                  formatter=None,
1216                  add_help_option=True,
1217                  prog=None,
1218                  epilog=None):
1219         OptionContainer.__init__(
1220             self, option_class, conflict_handler, description)
1221         self.set_usage(usage)
1222         self.prog = prog
1223         self.version = version
1224         self.allow_interspersed_args = True
1225         self.process_default_values = True
1226         if formatter is None:
1227             formatter = IndentedHelpFormatter()
1228         self.formatter = formatter
1229         self.formatter.set_parser(self)
1230         self.epilog = epilog
1231
1232         # Populate the option list; initial sources are the
1233         # standard_option_list class attribute, the 'option_list'
1234         # argument, and (if applicable) the _add_version_option() and
1235         # _add_help_option() methods.
1236         self._populate_option_list(option_list,
1237                                    add_help=add_help_option)
1238
1239         self._init_parsing_state()
1240
1241
1242     def destroy(self):
1243         """
1244         Declare that you are done with this OptionParser.  This cleans up
1245         reference cycles so the OptionParser (and all objects referenced by
1246         it) can be garbage-collected promptly.  After calling destroy(), the
1247         OptionParser is unusable.
1248         """
1249         OptionContainer.destroy(self)
1250         for group in self.option_groups:
1251             group.destroy()
1252         del self.option_list
1253         del self.option_groups
1254         del self.formatter
1255
1256
1257     # -- Private methods -----------------------------------------------
1258     # (used by our or OptionContainer's constructor)
1259
1260     def _create_option_list(self):
1261         self.option_list = []
1262         self.option_groups = []
1263         self._create_option_mappings()
1264
1265     def _add_help_option(self):
1266         self.add_option("-h", "--help",
1267                         action="help",
1268                         help=_("show this help message and exit"))
1269
1270     def _add_version_option(self):
1271         self.add_option("--version",
1272                         action="version",
1273                         help=_("show program's version number and exit"))
1274
1275     def _populate_option_list(self, option_list, add_help=True):
1276         if self.standard_option_list:
1277             self.add_options(self.standard_option_list)
1278         if option_list:
1279             self.add_options(option_list)
1280         if self.version:
1281             self._add_version_option()
1282         if add_help:
1283             self._add_help_option()
1284
1285     def _init_parsing_state(self):
1286         # These are set in parse_args() for the convenience of callbacks.
1287         self.rargs = None
1288         self.largs = None
1289         self.values = None
1290
1291
1292     # -- Simple modifier methods ---------------------------------------
1293
1294     def set_usage(self, usage):
1295         if usage is None:
1296             self.usage = _("%prog [options]")
1297         elif usage is SUPPRESS_USAGE:
1298             self.usage = None
1299         # For backwards compatibility with Optik 1.3 and earlier.
1300         elif usage.lower()[:7] == "usage: ":
1301             self.usage = usage[7:]
1302         else:
1303             self.usage = usage
1304
1305     def enable_interspersed_args(self):
1306         self.allow_interspersed_args = True
1307
1308     def disable_interspersed_args(self):
1309         self.allow_interspersed_args = False
1310
1311     def set_process_default_values(self, process):
1312         self.process_default_values = process
1313
1314     def set_default(self, dest, value):
1315         self.defaults[dest] = value
1316
1317     def set_defaults(self, **kwargs):
1318         self.defaults.update(kwargs)
1319
1320     def _get_all_options(self):
1321         options = self.option_list[:]
1322         for group in self.option_groups:
1323             options.extend(group.option_list)
1324         return options
1325
1326     def get_default_values(self):
1327         if not self.process_default_values:
1328             # Old, pre-Optik 1.5 behaviour.
1329             return Values(self.defaults)
1330
1331         defaults = self.defaults.copy()
1332         for option in self._get_all_options():
1333             default = defaults.get(option.dest)
1334             if isbasestring(default):
1335                 opt_str = option.get_opt_string()
1336                 defaults[option.dest] = option.check_value(opt_str, default)
1337
1338         return Values(defaults)
1339
1340
1341     # -- OptionGroup methods -------------------------------------------
1342
1343     def add_option_group(self, *args, **kwargs):
1344         # XXX lots of overlap with OptionContainer.add_option()
1345         if isinstance(args[0], str):
1346             group = OptionGroup(self, *args, **kwargs)
1347         elif len(args) == 1 and not kwargs:
1348             group = args[0]
1349             if not isinstance(group, OptionGroup):
1350                 raise TypeError, "not an OptionGroup instance: %r" % group
1351             if group.parser is not self:
1352                 raise ValueError, "invalid OptionGroup (wrong parser)"
1353         else:
1354             raise TypeError, "invalid arguments"
1355
1356         self.option_groups.append(group)
1357         return group
1358
1359     def get_option_group(self, opt_str):
1360         option = (self._short_opt.get(opt_str) or
1361                   self._long_opt.get(opt_str))
1362         if option and option.container is not self:
1363             return option.container
1364         return None
1365
1366
1367     # -- Option-parsing methods ----------------------------------------
1368
1369     def _get_args(self, args):
1370         if args is None:
1371             return sys.argv[1:]
1372         else:
1373             return args[:]              # don't modify caller's list
1374
1375     def parse_args(self, args=None, values=None):
1376         """
1377         parse_args(args : [string] = sys.argv[1:],
1378                    values : Values = None)
1379         -> (values : Values, args : [string])
1380
1381         Parse the command-line options found in 'args' (default:
1382         sys.argv[1:]).  Any errors result in a call to 'error()', which
1383         by default prints the usage message to stderr and calls
1384         sys.exit() with an error message.  On success returns a pair
1385         (values, args) where 'values' is an Values instance (with all
1386         your option values) and 'args' is the list of arguments left
1387         over after parsing options.
1388         """
1389         rargs = self._get_args(args)
1390         if values is None:
1391             values = self.get_default_values()
1392
1393         # Store the halves of the argument list as attributes for the
1394         # convenience of callbacks:
1395         #   rargs
1396         #     the rest of the command-line (the "r" stands for
1397         #     "remaining" or "right-hand")
1398         #   largs
1399         #     the leftover arguments -- ie. what's left after removing
1400         #     options and their arguments (the "l" stands for "leftover"
1401         #     or "left-hand")
1402         self.rargs = rargs
1403         self.largs = largs = []
1404         self.values = values
1405
1406         try:
1407             stop = self._process_args(largs, rargs, values)
1408         except (BadOptionError, OptionValueError), err:
1409             self.error(str(err))
1410
1411         args = largs + rargs
1412         return self.check_values(values, args)
1413
1414     def check_values(self, values, args):
1415         """
1416         check_values(values : Values, args : [string])
1417         -> (values : Values, args : [string])
1418
1419         Check that the supplied option values and leftover arguments are
1420         valid.  Returns the option values and leftover arguments
1421         (possibly adjusted, possibly completely new -- whatever you
1422         like).  Default implementation just returns the passed-in
1423         values; subclasses may override as desired.
1424         """
1425         return (values, args)
1426
1427     def _process_args(self, largs, rargs, values):
1428         """_process_args(largs : [string],
1429                          rargs : [string],
1430                          values : Values)
1431
1432         Process command-line arguments and populate 'values', consuming
1433         options and arguments from 'rargs'.  If 'allow_interspersed_args' is
1434         false, stop at the first non-option argument.  If true, accumulate any
1435         interspersed non-option arguments in 'largs'.
1436         """
1437         while rargs:
1438             arg = rargs[0]
1439             # We handle bare "--" explicitly, and bare "-" is handled by the
1440             # standard arg handler since the short arg case ensures that the
1441             # len of the opt string is greater than 1.
1442             if arg == "--":
1443                 del rargs[0]
1444                 return
1445             elif arg[0:2] == "--":
1446                 # process a single long option (possibly with value(s))
1447                 self._process_long_opt(rargs, values)
1448             elif arg[:1] == "-" and len(arg) > 1:
1449                 # process a cluster of short options (possibly with
1450                 # value(s) for the last one only)
1451                 self._process_short_opts(rargs, values)
1452             elif self.allow_interspersed_args:
1453                 largs.append(arg)
1454                 del rargs[0]
1455             else:
1456                 return                  # stop now, leave this arg in rargs
1457
1458         # Say this is the original argument list:
1459         # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)]
1460         #                            ^
1461         # (we are about to process arg(i)).
1462         #
1463         # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of
1464         # [arg0, ..., arg(i-1)] (any options and their arguments will have
1465         # been removed from largs).
1466         #
1467         # The while loop will usually consume 1 or more arguments per pass.
1468         # If it consumes 1 (eg. arg is an option that takes no arguments),
1469         # then after _process_arg() is done the situation is:
1470         #
1471         #   largs = subset of [arg0, ..., arg(i)]
1472         #   rargs = [arg(i+1), ..., arg(N-1)]
1473         #
1474         # If allow_interspersed_args is false, largs will always be
1475         # *empty* -- still a subset of [arg0, ..., arg(i-1)], but
1476         # not a very interesting subset!
1477
1478     def _match_long_opt(self, opt):
1479         """_match_long_opt(opt : string) -> string
1480
1481         Determine which long option string 'opt' matches, ie. which one
1482         it is an unambiguous abbrevation for.  Raises BadOptionError if
1483         'opt' doesn't unambiguously match any long option string.
1484         """
1485         return _match_abbrev(opt, self._long_opt)
1486
1487     def _process_long_opt(self, rargs, values):
1488         arg = rargs.pop(0)
1489
1490         # Value explicitly attached to arg?  Pretend it's the next
1491         # argument.
1492         if "=" in arg:
1493             (opt, next_arg) = arg.split("=", 1)
1494             rargs.insert(0, next_arg)
1495             had_explicit_value = True
1496         else:
1497             opt = arg
1498             had_explicit_value = False
1499
1500         opt = self._match_long_opt(opt)
1501         option = self._long_opt[opt]
1502         if option.takes_value():
1503             nargs = option.nargs
1504             if len(rargs) < nargs:
1505                 if nargs == 1:
1506                     self.error(_("%s option requires an argument") % opt)
1507                 else:
1508                     self.error(_("%s option requires %d arguments")
1509                                % (opt, nargs))
1510             elif nargs == 1:
1511                 value = rargs.pop(0)
1512             else:
1513                 value = tuple(rargs[0:nargs])
1514                 del rargs[0:nargs]
1515
1516         elif had_explicit_value:
1517             self.error(_("%s option does not take a value") % opt)
1518
1519         else:
1520             value = None
1521
1522         option.process(opt, value, values, self)
1523
1524     def _process_short_opts(self, rargs, values):
1525         arg = rargs.pop(0)
1526         stop = False
1527         i = 1
1528         for ch in arg[1:]:
1529             opt = "-" + ch
1530             option = self._short_opt.get(opt)
1531             i = i + 1                      # we have consumed a character
1532
1533             if not option:
1534                 raise BadOptionError(opt)
1535             if option.takes_value():
1536                 # Any characters left in arg?  Pretend they're the
1537                 # next arg, and stop consuming characters of arg.
1538                 if i < len(arg):
1539                     rargs.insert(0, arg[i:])
1540                     stop = True
1541
1542                 nargs = option.nargs
1543                 if len(rargs) < nargs:
1544                     if nargs == 1:
1545                         self.error(_("%s option requires an argument") % opt)
1546                     else:
1547                         self.error(_("%s option requires %d arguments")
1548                                    % (opt, nargs))
1549                 elif nargs == 1:
1550                     value = rargs.pop(0)
1551                 else:
1552                     value = tuple(rargs[0:nargs])
1553                     del rargs[0:nargs]
1554
1555             else:                       # option doesn't take a value
1556                 value = None
1557
1558             option.process(opt, value, values, self)
1559
1560             if stop:
1561                 break
1562
1563
1564     # -- Feedback methods ----------------------------------------------
1565
1566     def get_prog_name(self):
1567         if self.prog is None:
1568             return os.path.basename(sys.argv[0])
1569         else:
1570             return self.prog
1571
1572     def expand_prog_name(self, s):
1573         return s.replace("%prog", self.get_prog_name())
1574
1575     def get_description(self):
1576         return self.expand_prog_name(self.description)
1577
1578     def exit(self, status=0, msg=None):
1579         if msg:
1580             sys.stderr.write(msg)
1581         sys.exit(status)
1582
1583     def error(self, msg):
1584         """error(msg : string)
1585
1586         Print a usage message incorporating 'msg' to stderr and exit.
1587         If you override this in a subclass, it should not return -- it
1588         should either exit or raise an exception.
1589         """
1590         self.print_usage(sys.stderr)
1591         self.exit(2, "%s: error: %s\n" % (self.get_prog_name(), msg))
1592
1593     def get_usage(self):
1594         if self.usage:
1595             return self.formatter.format_usage(
1596                 self.expand_prog_name(self.usage))
1597         else:
1598             return ""
1599
1600     def print_usage(self, file=None):
1601         """print_usage(file : file = stdout)
1602
1603         Print the usage message for the current program (self.usage) to
1604         'file' (default stdout).  Any occurence of the string "%prog" in
1605         self.usage is replaced with the name of the current program
1606         (basename of sys.argv[0]).  Does nothing if self.usage is empty
1607         or not defined.
1608         """
1609         if self.usage:
1610             file.write(self.get_usage() + '\n')
1611
1612     def get_version(self):
1613         if self.version:
1614             return self.expand_prog_name(self.version)
1615         else:
1616             return ""
1617
1618     def print_version(self, file=None):
1619         """print_version(file : file = stdout)
1620
1621         Print the version message for this program (self.version) to
1622         'file' (default stdout).  As with print_usage(), any occurence
1623         of "%prog" in self.version is replaced by the current program's
1624         name.  Does nothing if self.version is empty or undefined.
1625         """
1626         if self.version:
1627             file.write(self.get_version() + '\n')
1628
1629     def format_option_help(self, formatter=None):
1630         if formatter is None:
1631             formatter = self.formatter
1632         formatter.store_option_strings(self)
1633         result = []
1634         result.append(formatter.format_heading(_("Options")))
1635         formatter.indent()
1636         if self.option_list:
1637             result.append(OptionContainer.format_option_help(self, formatter))
1638             result.append("\n")
1639         for group in self.option_groups:
1640             result.append(group.format_help(formatter))
1641             result.append("\n")
1642         formatter.dedent()
1643         # Drop the last "\n", or the header if no options or option groups:
1644         return "".join(result[:-1])
1645
1646     def format_epilog(self, formatter):
1647         return formatter.format_epilog(self.epilog)
1648
1649     def format_help(self, formatter=None):
1650         if formatter is None:
1651             formatter = self.formatter
1652         result = []
1653         if self.usage:
1654             result.append(self.get_usage() + "\n")
1655         if self.description:
1656             result.append(self.format_description(formatter) + "\n")
1657         result.append(self.format_option_help(formatter))
1658         result.append(self.format_epilog(formatter))
1659         return "".join(result)
1660
1661     # used by test suite
1662     def _get_encoding(self, file):
1663         encoding = getattr(file, "encoding", None)
1664         if not encoding:
1665             encoding = sys.getdefaultencoding()
1666         return encoding
1667
1668     def print_help(self, file=None):
1669         """print_help(file : file = stdout)
1670
1671         Print an extended help message, listing all options and any
1672         help text provided with them, to 'file' (default stdout).
1673         """
1674         if file is None:
1675             file = sys.stdout
1676         encoding = self._get_encoding(file)
1677         file.write(encode_wrapper(self.format_help(), encoding, "replace"))
1678
1679 # class OptionParser
1680
1681
1682 def _match_abbrev(s, wordmap):
1683     """_match_abbrev(s : string, wordmap : {string : Option}) -> string
1684
1685     Return the string key in 'wordmap' for which 's' is an unambiguous
1686     abbreviation.  If 's' is found to be ambiguous or doesn't match any of
1687     'words', raise BadOptionError.
1688     """
1689     # Is there an exact match?
1690     if s in wordmap:
1691         return s
1692     else:
1693         # Isolate all words with s as a prefix.
1694         possibilities = [w for w in wordmap.keys() if w[:len(s)] == s]
1695         # No exact match, so there had better be just one possibility.
1696         if len(possibilities) == 1:
1697             return possibilities[0]
1698         elif not possibilities:
1699             raise BadOptionError(s)
1700         else:
1701             # More than one possible completion: ambiguous prefix.
1702             possibilities.sort()
1703             raise AmbiguousOptionError(s, possibilities)
1704
1705
1706 # Some day, there might be many Option classes.  As of Optik 1.3, the
1707 # preferred way to instantiate Options is indirectly, via make_option(),
1708 # which will become a factory function when there are many Option
1709 # classes.
1710 make_option = Option
1711
1712 # Local Variables:
1713 # tab-width:4
1714 # indent-tabs-mode:nil
1715 # End:
1716 # vim: set expandtab tabstop=4 shiftwidth=4: