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