Package SCons :: Package compat :: Module _scons_optparse
[hide private]
[frames] | no frames]

Source Code for Module SCons.compat._scons_optparse

   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 string 
  70  import sys, os 
  71  import types 
  72  import textwrap 
  73   
74 -def _repr(self):
75 return "<%s at 0x%x: %s>" % (self.__class__.__name__, id(self), self)
76 77 78 try: 79 sys.getdefaultencoding 80 except AttributeError:
81 - def fake_getdefaultencoding():
82 return None
83 sys.getdefaultencoding = fake_getdefaultencoding 84 85 try: 86 ''.encode 87 except AttributeError:
88 - def encode_wrapper(s, encoding, replacement):
89 return s
90 else:
91 - def encode_wrapper(s, encoding, replacement):
92 return s.encode(encoding, replacement)
93 94 95 # This file was generated from: 96 # Id: option_parser.py 527 2006-07-23 15:21:30Z greg 97 # Id: option.py 522 2006-06-11 16:22:03Z gward 98 # Id: help.py 527 2006-07-23 15:21:30Z greg 99 # Id: errors.py 509 2006-04-20 00:58:24Z gward 100 101 try: 102 from gettext import gettext 103 except ImportError:
104 - def gettext(message):
105 return message
106 _ = gettext 107 108
109 -class OptParseError (Exception):
110 - def __init__(self, msg):
111 self.msg = msg
112
113 - def __str__(self):
114 return self.msg
115 116
117 -class OptionError (OptParseError):
118 """ 119 Raised if an Option instance is created with invalid or 120 inconsistent arguments. 121 """ 122
123 - def __init__(self, msg, option):
124 self.msg = msg 125 self.option_id = str(option)
126
127 - def __str__(self):
128 if self.option_id: 129 return "option %s: %s" % (self.option_id, self.msg) 130 else: 131 return self.msg
132
133 -class OptionConflictError (OptionError):
134 """ 135 Raised if conflicting options are added to an OptionParser. 136 """
137
138 -class OptionValueError (OptParseError):
139 """ 140 Raised if an invalid option value is encountered on the command 141 line. 142 """
143
144 -class BadOptionError (OptParseError):
145 """ 146 Raised if an invalid option is seen on the command line. 147 """
148 - def __init__(self, opt_str):
149 self.opt_str = opt_str
150
151 - def __str__(self):
152 return _("no such option: %s") % self.opt_str
153
154 -class AmbiguousOptionError (BadOptionError):
155 """ 156 Raised if an ambiguous option is seen on the command line. 157 """
158 - def __init__(self, opt_str, possibilities):
159 BadOptionError.__init__(self, opt_str) 160 self.possibilities = possibilities
161
162 - def __str__(self):
163 return (_("ambiguous option: %s (%s?)") 164 % (self.opt_str, string.join(self.possibilities, ", ")))
165 166
167 -class HelpFormatter:
168 169 """ 170 Abstract base class for formatting option help. OptionParser 171 instances should use one of the HelpFormatter subclasses for 172 formatting help; by default IndentedHelpFormatter is used. 173 174 Instance attributes: 175 parser : OptionParser 176 the controlling OptionParser instance 177 indent_increment : int 178 the number of columns to indent per nesting level 179 max_help_position : int 180 the maximum starting column for option help text 181 help_position : int 182 the calculated starting column for option help text; 183 initially the same as the maximum 184 width : int 185 total number of columns for output (pass None to constructor for 186 this value to be taken from the $COLUMNS environment variable) 187 level : int 188 current indentation level 189 current_indent : int 190 current indentation level (in columns) 191 help_width : int 192 number of columns available for option help text (calculated) 193 default_tag : str 194 text to replace with each option's default value, "%default" 195 by default. Set to false value to disable default value expansion. 196 option_strings : { Option : str } 197 maps Option instances to the snippet of help text explaining 198 the syntax of that option, e.g. "-h, --help" or 199 "-fFILE, --file=FILE" 200 _short_opt_fmt : str 201 format string controlling how short options with values are 202 printed in help text. Must be either "%s%s" ("-fFILE") or 203 "%s %s" ("-f FILE"), because those are the two syntaxes that 204 Optik supports. 205 _long_opt_fmt : str 206 similar but for long options; must be either "%s %s" ("--file FILE") 207 or "%s=%s" ("--file=FILE"). 208 """ 209 210 NO_DEFAULT_VALUE = "none" 211
212 - def __init__(self, 213 indent_increment, 214 max_help_position, 215 width, 216 short_first):
217 self.parser = None 218 self.indent_increment = indent_increment 219 self.help_position = self.max_help_position = max_help_position 220 if width is None: 221 try: 222 width = int(os.environ['COLUMNS']) 223 except (KeyError, ValueError): 224 width = 80 225 width = width - 2 226 self.width = width 227 self.current_indent = 0 228 self.level = 0 229 self.help_width = None # computed later 230 self.short_first = short_first 231 self.default_tag = "%default" 232 self.option_strings = {} 233 self._short_opt_fmt = "%s %s" 234 self._long_opt_fmt = "%s=%s"
235
236 - def set_parser(self, parser):
237 self.parser = parser
238
239 - def set_short_opt_delimiter(self, delim):
240 if delim not in ("", " "): 241 raise ValueError( 242 "invalid metavar delimiter for short options: %r" % delim) 243 self._short_opt_fmt = "%s" + delim + "%s"
244
245 - def set_long_opt_delimiter(self, delim):
246 if delim not in ("=", " "): 247 raise ValueError( 248 "invalid metavar delimiter for long options: %r" % delim) 249 self._long_opt_fmt = "%s" + delim + "%s"
250
251 - def indent(self):
252 self.current_indent = self.current_indent + self.indent_increment 253 self.level = self.level + 1
254
255 - def dedent(self):
256 self.current_indent = self.current_indent - self.indent_increment 257 assert self.current_indent >= 0, "Indent decreased below 0." 258 self.level = self.level - 1
259
260 - def format_usage(self, usage):
261 raise NotImplementedError, "subclasses must implement"
262
263 - def format_heading(self, heading):
264 raise NotImplementedError, "subclasses must implement"
265
266 - def _format_text(self, text):
267 """ 268 Format a paragraph of free-form text for inclusion in the 269 help output at the current indentation level. 270 """ 271 text_width = self.width - self.current_indent 272 indent = " "*self.current_indent 273 return textwrap.fill(text, 274 text_width, 275 initial_indent=indent, 276 subsequent_indent=indent)
277
278 - def format_description(self, description):
279 if description: 280 return self._format_text(description) + "\n" 281 else: 282 return ""
283
284 - def format_epilog(self, epilog):
285 if epilog: 286 return "\n" + self._format_text(epilog) + "\n" 287 else: 288 return ""
289 290
291 - def expand_default(self, option):
292 if self.parser is None or not self.default_tag: 293 return option.help 294 295 default_value = self.parser.defaults.get(option.dest) 296 if default_value is NO_DEFAULT or default_value is None: 297 default_value = self.NO_DEFAULT_VALUE 298 299 return string.replace(option.help, self.default_tag, str(default_value))
300
301 - def format_option(self, option):
302 # The help for each option consists of two parts: 303 # * the opt strings and metavars 304 # eg. ("-x", or "-fFILENAME, --file=FILENAME") 305 # * the user-supplied help string 306 # eg. ("turn on expert mode", "read data from FILENAME") 307 # 308 # If possible, we write both of these on the same line: 309 # -x turn on expert mode 310 # 311 # But if the opt string list is too long, we put the help 312 # string on a second line, indented to the same column it would 313 # start in if it fit on the first line. 314 # -fFILENAME, --file=FILENAME 315 # read data from FILENAME 316 result = [] 317 opts = self.option_strings[option] 318 opt_width = self.help_position - self.current_indent - 2 319 if len(opts) > opt_width: 320 opts = "%*s%s\n" % (self.current_indent, "", opts) 321 indent_first = self.help_position 322 else: # start help on same line as opts 323 opts = "%*s%-*s " % (self.current_indent, "", opt_width, opts) 324 indent_first = 0 325 result.append(opts) 326 if option.help: 327 help_text = self.expand_default(option) 328 help_lines = textwrap.wrap(help_text, self.help_width) 329 result.append("%*s%s\n" % (indent_first, "", help_lines[0])) 330 for line in help_lines[1:]: 331 result.append("%*s%s\n" % (self.help_position, "", line)) 332 elif opts[-1] != "\n": 333 result.append("\n") 334 return string.join(result, "")
335
336 - def store_option_strings(self, parser):
337 self.indent() 338 max_len = 0 339 for opt in parser.option_list: 340 strings = self.format_option_strings(opt) 341 self.option_strings[opt] = strings 342 max_len = max(max_len, len(strings) + self.current_indent) 343 self.indent() 344 for group in parser.option_groups: 345 for opt in group.option_list: 346 strings = self.format_option_strings(opt) 347 self.option_strings[opt] = strings 348 max_len = max(max_len, len(strings) + self.current_indent) 349 self.dedent() 350 self.dedent() 351 self.help_position = min(max_len + 2, self.max_help_position) 352 self.help_width = self.width - self.help_position
353
354 - def format_option_strings(self, option):
355 """Return a comma-separated list of option strings & metavariables.""" 356 if option.takes_value(): 357 metavar = option.metavar or string.upper(option.dest) 358 short_opts = [] 359 for sopt in option._short_opts: 360 short_opts.append(self._short_opt_fmt % (sopt, metavar)) 361 long_opts = [] 362 for lopt in option._long_opts: 363 long_opts.append(self._long_opt_fmt % (lopt, metavar)) 364 else: 365 short_opts = option._short_opts 366 long_opts = option._long_opts 367 368 if self.short_first: 369 opts = short_opts + long_opts 370 else: 371 opts = long_opts + short_opts 372 373 return string.join(opts, ", ")
374
375 -class IndentedHelpFormatter (HelpFormatter):
376 """Format help with indented section bodies. 377 """ 378
379 - def __init__(self, 380 indent_increment=2, 381 max_help_position=24, 382 width=None, 383 short_first=1):
384 HelpFormatter.__init__( 385 self, indent_increment, max_help_position, width, short_first)
386
387 - def format_usage(self, usage):
388 return _("Usage: %s\n") %