PageRenderTime 46ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

/lib-python/2/distutils/fancy_getopt.py

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