usage.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997
  1. # -*- test-case-name: twisted.test.test_usage -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. twisted.python.usage is a module for parsing/handling the
  6. command line of your program.
  7. For information on how to use it, see
  8. U{http://twistedmatrix.com/projects/core/documentation/howto/options.html},
  9. or doc/core/howto/options.xhtml in your Twisted directory.
  10. """
  11. from __future__ import print_function
  12. from __future__ import division, absolute_import
  13. # System Imports
  14. import inspect
  15. import os
  16. import sys
  17. import getopt
  18. from os import path
  19. import textwrap
  20. # Sibling Imports
  21. from twisted.python import reflect, util
  22. from twisted.python.compat import _PY3
  23. class UsageError(Exception):
  24. pass
  25. error = UsageError
  26. class CoerceParameter(object):
  27. """
  28. Utility class that can corce a parameter before storing it.
  29. """
  30. def __init__(self, options, coerce):
  31. """
  32. @param options: parent Options object
  33. @param coerce: callable used to coerce the value.
  34. """
  35. self.options = options
  36. self.coerce = coerce
  37. self.doc = getattr(self.coerce, 'coerceDoc', '')
  38. def dispatch(self, parameterName, value):
  39. """
  40. When called in dispatch, do the coerce for C{value} and save the
  41. returned value.
  42. """
  43. if value is None:
  44. raise UsageError("Parameter '%s' requires an argument."
  45. % (parameterName,))
  46. try:
  47. value = self.coerce(value)
  48. except ValueError as e:
  49. raise UsageError("Parameter type enforcement failed: %s" % (e,))
  50. self.options.opts[parameterName] = value
  51. class Options(dict):
  52. """
  53. An option list parser class
  54. C{optFlags} and C{optParameters} are lists of available parameters
  55. which your program can handle. The difference between the two
  56. is the 'flags' have an on(1) or off(0) state (off by default)
  57. whereas 'parameters' have an assigned value, with an optional
  58. default. (Compare '--verbose' and '--verbosity=2')
  59. optFlags is assigned a list of lists. Each list represents
  60. a flag parameter, as so::
  61. optFlags = [['verbose', 'v', 'Makes it tell you what it doing.'],
  62. ['quiet', 'q', 'Be vewy vewy quiet.']]
  63. As you can see, the first item is the long option name
  64. (prefixed with '--' on the command line), followed by the
  65. short option name (prefixed with '-'), and the description.
  66. The description is used for the built-in handling of the
  67. --help switch, which prints a usage summary.
  68. C{optParameters} is much the same, except the list also contains
  69. a default value::
  70. optParameters = [['outfile', 'O', 'outfile.log', 'Description...']]
  71. A coerce function can also be specified as the last element: it will be
  72. called with the argument and should return the value that will be stored
  73. for the option. This function can have a C{coerceDoc} attribute which
  74. will be appended to the documentation of the option.
  75. subCommands is a list of 4-tuples of (command name, command shortcut,
  76. parser class, documentation). If the first non-option argument found is
  77. one of the given command names, an instance of the given parser class is
  78. instantiated and given the remainder of the arguments to parse and
  79. self.opts[command] is set to the command name. For example::
  80. subCommands = [
  81. ['inquisition', 'inquest', InquisitionOptions,
  82. 'Perform an inquisition'],
  83. ['holyquest', 'quest', HolyQuestOptions,
  84. 'Embark upon a holy quest']
  85. ]
  86. In this case, C{"<program> holyquest --horseback --for-grail"} will cause
  87. C{HolyQuestOptions} to be instantiated and asked to parse
  88. C{['--horseback', '--for-grail']}. Currently, only the first sub-command
  89. is parsed, and all options following it are passed to its parser. If a
  90. subcommand is found, the subCommand attribute is set to its name and the
  91. subOptions attribute is set to the Option instance that parses the
  92. remaining options. If a subcommand is not given to parseOptions,
  93. the subCommand attribute will be None. You can also mark one of
  94. the subCommands to be the default::
  95. defaultSubCommand = 'holyquest'
  96. In this case, the subCommand attribute will never be None, and
  97. the subOptions attribute will always be set.
  98. If you want to handle your own options, define a method named
  99. C{opt_paramname} that takes C{(self, option)} as arguments. C{option}
  100. will be whatever immediately follows the parameter on the
  101. command line. Options fully supports the mapping interface, so you
  102. can do things like C{'self["option"] = val'} in these methods.
  103. Shell tab-completion is supported by this class, for zsh only at present.
  104. Zsh ships with a stub file ("completion function") which, for Twisted
  105. commands, performs tab-completion on-the-fly using the support provided
  106. by this class. The stub file lives in our tree at
  107. C{twisted/python/twisted-completion.zsh}, and in the Zsh tree at
  108. C{Completion/Unix/Command/_twisted}.
  109. Tab-completion is based upon the contents of the optFlags and optParameters
  110. lists. And, optionally, additional metadata may be provided by assigning a
  111. special attribute, C{compData}, which should be an instance of
  112. C{Completions}. See that class for details of what can and should be
  113. included - and see the howto for additional help using these features -
  114. including how third-parties may take advantage of tab-completion for their
  115. own commands.
  116. Advanced functionality is covered in the howto documentation,
  117. available at
  118. U{http://twistedmatrix.com/projects/core/documentation/howto/options.html},
  119. or doc/core/howto/options.xhtml in your Twisted directory.
  120. """
  121. subCommand = None
  122. defaultSubCommand = None
  123. parent = None
  124. completionData = None
  125. _shellCompFile = sys.stdout # file to use if shell completion is requested
  126. def __init__(self):
  127. super(Options, self).__init__()
  128. self.opts = self
  129. self.defaults = {}
  130. # These are strings/lists we will pass to getopt
  131. self.longOpt = []
  132. self.shortOpt = ''
  133. self.docs = {}
  134. self.synonyms = {}
  135. self._dispatch = {}
  136. collectors = [
  137. self._gather_flags,
  138. self._gather_parameters,
  139. self._gather_handlers,
  140. ]
  141. for c in collectors:
  142. (longOpt, shortOpt, docs, settings, synonyms, dispatch) = c()
  143. self.longOpt.extend(longOpt)
  144. self.shortOpt = self.shortOpt + shortOpt
  145. self.docs.update(docs)
  146. self.opts.update(settings)
  147. self.defaults.update(settings)
  148. self.synonyms.update(synonyms)
  149. self._dispatch.update(dispatch)
  150. __hash__ = object.__hash__
  151. def opt_help(self):
  152. """
  153. Display this help and exit.
  154. """
  155. print(self.__str__())
  156. sys.exit(0)
  157. def opt_version(self):
  158. """
  159. Display Twisted version and exit.
  160. """
  161. from twisted import copyright
  162. print("Twisted version:", copyright.version)
  163. sys.exit(0)
  164. #opt_h = opt_help # this conflicted with existing 'host' options.
  165. def parseOptions(self, options=None):
  166. """
  167. The guts of the command-line parser.
  168. """
  169. if options is None:
  170. options = sys.argv[1:]
  171. # we really do need to place the shell completion check here, because
  172. # if we used an opt_shell_completion method then it would be possible
  173. # for other opt_* methods to be run first, and they could possibly
  174. # raise validation errors which would result in error output on the
  175. # terminal of the user performing shell completion. Validation errors
  176. # would occur quite frequently, in fact, because users often initiate
  177. # tab-completion while they are editing an unfinished command-line.
  178. if len(options) > 1 and options[-2] == "--_shell-completion":
  179. from twisted.python import _shellcomp
  180. cmdName = path.basename(sys.argv[0])
  181. _shellcomp.shellComplete(self, cmdName, options,
  182. self._shellCompFile)
  183. sys.exit(0)
  184. try:
  185. opts, args = getopt.getopt(options,
  186. self.shortOpt, self.longOpt)
  187. except getopt.error as e:
  188. raise UsageError(str(e))
  189. for opt, arg in opts:
  190. if opt[1] == '-':
  191. opt = opt[2:]
  192. else:
  193. opt = opt[1:]
  194. optMangled = opt
  195. if optMangled not in self.synonyms:
  196. optMangled = opt.replace("-", "_")
  197. if optMangled not in self.synonyms:
  198. raise UsageError("No such option '%s'" % (opt,))
  199. optMangled = self.synonyms[optMangled]
  200. if isinstance(self._dispatch[optMangled], CoerceParameter):
  201. self._dispatch[optMangled].dispatch(optMangled, arg)
  202. else:
  203. self._dispatch[optMangled](optMangled, arg)
  204. if (getattr(self, 'subCommands', None)
  205. and (args or self.defaultSubCommand is not None)):
  206. if not args:
  207. args = [self.defaultSubCommand]
  208. sub, rest = args[0], args[1:]
  209. for (cmd, short, parser, doc) in self.subCommands:
  210. if sub == cmd or sub == short:
  211. self.subCommand = cmd
  212. self.subOptions = parser()
  213. self.subOptions.parent = self
  214. self.subOptions.parseOptions(rest)
  215. break
  216. else:
  217. raise UsageError("Unknown command: %s" % sub)
  218. else:
  219. try:
  220. self.parseArgs(*args)
  221. except TypeError:
  222. raise UsageError("Wrong number of arguments.")
  223. self.postOptions()
  224. def postOptions(self):
  225. """
  226. I am called after the options are parsed.
  227. Override this method in your subclass to do something after
  228. the options have been parsed and assigned, like validate that
  229. all options are sane.
  230. """
  231. def parseArgs(self):
  232. """
  233. I am called with any leftover arguments which were not options.
  234. Override me to do something with the remaining arguments on
  235. the command line, those which were not flags or options. e.g.
  236. interpret them as a list of files to operate on.
  237. Note that if there more arguments on the command line
  238. than this method accepts, parseArgs will blow up with
  239. a getopt.error. This means if you don't override me,
  240. parseArgs will blow up if I am passed any arguments at
  241. all!
  242. """
  243. def _generic_flag(self, flagName, value=None):
  244. if value not in ('', None):
  245. raise UsageError("Flag '%s' takes no argument."
  246. " Not even \"%s\"." % (flagName, value))
  247. self.opts[flagName] = 1
  248. def _gather_flags(self):
  249. """
  250. Gather up boolean (flag) options.
  251. """
  252. longOpt, shortOpt = [], ''
  253. docs, settings, synonyms, dispatch = {}, {}, {}, {}
  254. flags = []
  255. reflect.accumulateClassList(self.__class__, 'optFlags', flags)
  256. for flag in flags:
  257. long, short, doc = util.padTo(3, flag)
  258. if not long:
  259. raise ValueError("A flag cannot be without a name.")
  260. docs[long] = doc
  261. settings[long] = 0
  262. if short:
  263. shortOpt = shortOpt + short
  264. synonyms[short] = long
  265. longOpt.append(long)
  266. synonyms[long] = long
  267. dispatch[long] = self._generic_flag
  268. return longOpt, shortOpt, docs, settings, synonyms, dispatch
  269. def _gather_parameters(self):
  270. """
  271. Gather options which take a value.
  272. """
  273. longOpt, shortOpt = [], ''
  274. docs, settings, synonyms, dispatch = {}, {}, {}, {}
  275. parameters = []
  276. reflect.accumulateClassList(self.__class__, 'optParameters',
  277. parameters)
  278. synonyms = {}
  279. for parameter in parameters:
  280. long, short, default, doc, paramType = util.padTo(5, parameter)
  281. if not long:
  282. raise ValueError("A parameter cannot be without a name.")
  283. docs[long] = doc
  284. settings[long] = default
  285. if short:
  286. shortOpt = shortOpt + short + ':'
  287. synonyms[short] = long
  288. longOpt.append(long + '=')
  289. synonyms[long] = long
  290. if paramType is not None:
  291. dispatch[long] = CoerceParameter(self, paramType)
  292. else:
  293. dispatch[long] = CoerceParameter(self, str)
  294. return longOpt, shortOpt, docs, settings, synonyms, dispatch
  295. def _gather_handlers(self):
  296. """
  297. Gather up options with their own handler methods.
  298. This returns a tuple of many values. Amongst those values is a
  299. synonyms dictionary, mapping all of the possible aliases (C{str})
  300. for an option to the longest spelling of that option's name
  301. C({str}).
  302. Another element is a dispatch dictionary, mapping each user-facing
  303. option name (with - substituted for _) to a callable to handle that
  304. option.
  305. """
  306. longOpt, shortOpt = [], ''
  307. docs, settings, synonyms, dispatch = {}, {}, {}, {}
  308. dct = {}
  309. reflect.addMethodNamesToDict(self.__class__, dct, "opt_")
  310. for name in dct.keys():
  311. method = getattr(self, 'opt_'+name)
  312. takesArg = not flagFunction(method, name)
  313. prettyName = name.replace('_', '-')
  314. doc = getattr(method, '__doc__', None)
  315. if doc:
  316. ## Only use the first line.
  317. #docs[name] = doc.split('\n')[0]
  318. docs[prettyName] = doc
  319. else:
  320. docs[prettyName] = self.docs.get(prettyName)
  321. synonyms[prettyName] = prettyName
  322. # A little slight-of-hand here makes dispatching much easier
  323. # in parseOptions, as it makes all option-methods have the
  324. # same signature.
  325. if takesArg:
  326. fn = lambda name, value, m=method: m(value)
  327. else:
  328. # XXX: This won't raise a TypeError if it's called
  329. # with a value when it shouldn't be.
  330. fn = lambda name, value=None, m=method: m()
  331. dispatch[prettyName] = fn
  332. if len(name) == 1:
  333. shortOpt = shortOpt + name
  334. if takesArg:
  335. shortOpt = shortOpt + ':'
  336. else:
  337. if takesArg:
  338. prettyName = prettyName + '='
  339. longOpt.append(prettyName)
  340. reverse_dct = {}
  341. # Map synonyms
  342. for name in dct.keys():
  343. method = getattr(self, 'opt_' + name)
  344. if method not in reverse_dct:
  345. reverse_dct[method] = []
  346. reverse_dct[method].append(name.replace('_', '-'))
  347. for method, names in reverse_dct.items():
  348. if len(names) < 2:
  349. continue
  350. longest = max(names, key=len)
  351. for name in names:
  352. synonyms[name] = longest
  353. return longOpt, shortOpt, docs, settings, synonyms, dispatch
  354. def __str__(self):
  355. return self.getSynopsis() + '\n' + self.getUsage(width=None)
  356. def getSynopsis(self):
  357. """
  358. Returns a string containing a description of these options and how to
  359. pass them to the executed file.
  360. """
  361. default = "%s%s" % (path.basename(sys.argv[0]),
  362. (self.longOpt and " [options]") or '')
  363. if self.parent is None:
  364. default = "Usage: %s%s" % (path.basename(sys.argv[0]),
  365. (self.longOpt and " [options]") or '')
  366. else:
  367. default = '%s' % ((self.longOpt and "[options]") or '')
  368. synopsis = getattr(self, "synopsis", default)
  369. synopsis = synopsis.rstrip()
  370. if self.parent is not None:
  371. synopsis = ' '.join((self.parent.getSynopsis(),
  372. self.parent.subCommand, synopsis))
  373. return synopsis
  374. def getUsage(self, width=None):
  375. # If subOptions exists by now, then there was probably an error while
  376. # parsing its options.
  377. if hasattr(self, 'subOptions'):
  378. return self.subOptions.getUsage(width=width)
  379. if not width:
  380. width = int(os.environ.get('COLUMNS', '80'))
  381. if hasattr(self, 'subCommands'):
  382. cmdDicts = []
  383. for (cmd, short, parser, desc) in self.subCommands:
  384. cmdDicts.append(
  385. {'long': cmd,
  386. 'short': short,
  387. 'doc': desc,
  388. 'optType': 'command',
  389. 'default': None
  390. })
  391. chunks = docMakeChunks(cmdDicts, width)
  392. commands = 'Commands:\n' + ''.join(chunks)
  393. else:
  394. commands = ''
  395. longToShort = {}
  396. for key, value in self.synonyms.items():
  397. longname = value
  398. if (key != longname) and (len(key) == 1):
  399. longToShort[longname] = key
  400. else:
  401. if longname not in longToShort:
  402. longToShort[longname] = None
  403. else:
  404. pass
  405. optDicts = []
  406. for opt in self.longOpt:
  407. if opt[-1] == '=':
  408. optType = 'parameter'
  409. opt = opt[:-1]
  410. else:
  411. optType = 'flag'
  412. optDicts.append(
  413. {'long': opt,
  414. 'short': longToShort[opt],
  415. 'doc': self.docs[opt],
  416. 'optType': optType,
  417. 'default': self.defaults.get(opt, None),
  418. 'dispatch': self._dispatch.get(opt, None)
  419. })
  420. if not (getattr(self, "longdesc", None) is None):
  421. longdesc = self.longdesc
  422. else:
  423. import __main__
  424. if getattr(__main__, '__doc__', None):
  425. longdesc = __main__.__doc__
  426. else:
  427. longdesc = ''
  428. if longdesc:
  429. longdesc = ('\n' +
  430. '\n'.join(textwrap.wrap(longdesc, width)).strip()
  431. + '\n')
  432. if optDicts:
  433. chunks = docMakeChunks(optDicts, width)
  434. s = "Options:\n%s" % (''.join(chunks))
  435. else:
  436. s = "Options: None\n"
  437. return s + longdesc + commands
  438. #def __repr__(self):
  439. # XXX: It'd be cool if we could return a succinct representation
  440. # of which flags and options are set here.
  441. _ZSH = 'zsh'
  442. _BASH = 'bash'
  443. class Completer(object):
  444. """
  445. A completion "action" - provides completion possibilities for a particular
  446. command-line option. For example we might provide the user a fixed list of
  447. choices, or files/dirs according to a glob.
  448. This class produces no completion matches itself - see the various
  449. subclasses for specific completion functionality.
  450. """
  451. _descr = None
  452. def __init__(self, descr=None, repeat=False):
  453. """
  454. @type descr: C{str}
  455. @param descr: An optional descriptive string displayed above matches.
  456. @type repeat: C{bool}
  457. @param repeat: A flag, defaulting to False, indicating whether this
  458. C{Completer} should repeat - that is, be used to complete more
  459. than one command-line word. This may ONLY be set to True for
  460. actions in the C{extraActions} keyword argument to C{Completions}.
  461. And ONLY if it is the LAST (or only) action in the C{extraActions}
  462. list.
  463. """
  464. if descr is not None:
  465. self._descr = descr
  466. self._repeat = repeat
  467. def _getRepeatFlag(self):
  468. if self._repeat:
  469. return "*"
  470. else:
  471. return ""
  472. _repeatFlag = property(_getRepeatFlag)
  473. def _description(self, optName):
  474. if self._descr is not None:
  475. return self._descr
  476. else:
  477. return optName
  478. def _shellCode(self, optName, shellType):
  479. """
  480. Fetch a fragment of shell code representing this action which is
  481. suitable for use by the completion system in _shellcomp.py
  482. @type optName: C{str}
  483. @param optName: The long name of the option this action is being
  484. used for.
  485. @type shellType: C{str}
  486. @param shellType: One of the supported shell constants e.g.
  487. C{twisted.python.usage._ZSH}
  488. """
  489. if shellType == _ZSH:
  490. return "%s:%s:" % (self._repeatFlag,
  491. self._description(optName))
  492. raise NotImplementedError("Unknown shellType %r" % (shellType,))
  493. class CompleteFiles(Completer):
  494. """
  495. Completes file names based on a glob pattern
  496. """
  497. def __init__(self, globPattern='*', **kw):
  498. Completer.__init__(self, **kw)
  499. self._globPattern = globPattern
  500. def _description(self, optName):
  501. if self._descr is not None:
  502. return "%s (%s)" % (self._descr, self._globPattern)
  503. else:
  504. return "%s (%s)" % (optName, self._globPattern)
  505. def _shellCode(self, optName, shellType):
  506. if shellType == _ZSH:
  507. return "%s:%s:_files -g \"%s\"" % (self._repeatFlag,
  508. self._description(optName),
  509. self._globPattern,)
  510. raise NotImplementedError("Unknown shellType %r" % (shellType,))
  511. class CompleteDirs(Completer):
  512. """
  513. Completes directory names
  514. """
  515. def _shellCode(self, optName, shellType):
  516. if shellType == _ZSH:
  517. return "%s:%s:_directories" % (self._repeatFlag,
  518. self._description(optName))
  519. raise NotImplementedError("Unknown shellType %r" % (shellType,))
  520. class CompleteList(Completer):
  521. """
  522. Completes based on a fixed list of words
  523. """
  524. def __init__(self, items, **kw):
  525. Completer.__init__(self, **kw)
  526. self._items = items
  527. def _shellCode(self, optName, shellType):
  528. if shellType == _ZSH:
  529. return "%s:%s:(%s)" % (self._repeatFlag,
  530. self._description(optName),
  531. " ".join(self._items,))
  532. raise NotImplementedError("Unknown shellType %r" % (shellType,))
  533. class CompleteMultiList(Completer):
  534. """
  535. Completes multiple comma-separated items based on a fixed list of words
  536. """
  537. def __init__(self, items, **kw):
  538. Completer.__init__(self, **kw)
  539. self._items = items
  540. def _shellCode(self, optName, shellType):
  541. if shellType == _ZSH:
  542. return "%s:%s:_values -s , '%s' %s" % (self._repeatFlag,
  543. self._description(optName),
  544. self._description(optName),
  545. " ".join(self._items))
  546. raise NotImplementedError("Unknown shellType %r" % (shellType,))
  547. class CompleteUsernames(Completer):
  548. """
  549. Complete usernames
  550. """
  551. def _shellCode(self, optName, shellType):
  552. if shellType == _ZSH:
  553. return "%s:%s:_users" % (self._repeatFlag,
  554. self._description(optName))
  555. raise NotImplementedError("Unknown shellType %r" % (shellType,))
  556. class CompleteGroups(Completer):
  557. """
  558. Complete system group names
  559. """
  560. _descr = 'group'
  561. def _shellCode(self, optName, shellType):
  562. if shellType == _ZSH:
  563. return "%s:%s:_groups" % (self._repeatFlag,
  564. self._description(optName))
  565. raise NotImplementedError("Unknown shellType %r" % (shellType,))
  566. class CompleteHostnames(Completer):
  567. """
  568. Complete hostnames
  569. """
  570. def _shellCode(self, optName, shellType):
  571. if shellType == _ZSH:
  572. return "%s:%s:_hosts" % (self._repeatFlag,
  573. self._description(optName))
  574. raise NotImplementedError("Unknown shellType %r" % (shellType,))
  575. class CompleteUserAtHost(Completer):
  576. """
  577. A completion action which produces matches in any of these forms::
  578. <username>
  579. <hostname>
  580. <username>@<hostname>
  581. """
  582. _descr = 'host | user@host'
  583. def _shellCode(self, optName, shellType):
  584. if shellType == _ZSH:
  585. # Yes this looks insane but it does work. For bonus points
  586. # add code to grep 'Hostname' lines from ~/.ssh/config
  587. return ('%s:%s:{_ssh;if compset -P "*@"; '
  588. 'then _wanted hosts expl "remote host name" _ssh_hosts '
  589. '&& ret=0 elif compset -S "@*"; then _wanted users '
  590. 'expl "login name" _ssh_users -S "" && ret=0 '
  591. 'else if (( $+opt_args[-l] )); then tmp=() '
  592. 'else tmp=( "users:login name:_ssh_users -qS@" ) fi; '
  593. '_alternative "hosts:remote host name:_ssh_hosts" "$tmp[@]"'
  594. ' && ret=0 fi}' % (self._repeatFlag,
  595. self._description(optName)))
  596. raise NotImplementedError("Unknown shellType %r" % (shellType,))
  597. class CompleteNetInterfaces(Completer):
  598. """
  599. Complete network interface names
  600. """
  601. def _shellCode(self, optName, shellType):
  602. if shellType == _ZSH:
  603. return "%s:%s:_net_interfaces" % (self._repeatFlag,
  604. self._description(optName))
  605. raise NotImplementedError("Unknown shellType %r" % (shellType,))
  606. class Completions(object):
  607. """
  608. Extra metadata for the shell tab-completion system.
  609. @type descriptions: C{dict}
  610. @ivar descriptions: ex. C{{"foo" : "use this description for foo instead"}}
  611. A dict mapping long option names to alternate descriptions. When this
  612. variable is defined, the descriptions contained here will override
  613. those descriptions provided in the optFlags and optParameters
  614. variables.
  615. @type multiUse: C{list}
  616. @ivar multiUse: ex. C{ ["foo", "bar"] }
  617. An iterable containing those long option names which may appear on the
  618. command line more than once. By default, options will only be completed
  619. one time.
  620. @type mutuallyExclusive: C{list} of C{tuple}
  621. @ivar mutuallyExclusive: ex. C{ [("foo", "bar"), ("bar", "baz")] }
  622. A sequence of sequences, with each sub-sequence containing those long
  623. option names that are mutually exclusive. That is, those options that
  624. cannot appear on the command line together.
  625. @type optActions: C{dict}
  626. @ivar optActions: A dict mapping long option names to shell "actions".
  627. These actions define what may be completed as the argument to the
  628. given option. By default, all files/dirs will be completed if no
  629. action is given. For example::
  630. {"foo" : CompleteFiles("*.py", descr="python files"),
  631. "bar" : CompleteList(["one", "two", "three"]),
  632. "colors" : CompleteMultiList(["red", "green", "blue"])}
  633. Callables may instead be given for the values in this dict. The
  634. callable should accept no arguments, and return a C{Completer}
  635. instance used as the action in the same way as the literal actions in
  636. the example above.
  637. As you can see in the example above. The "foo" option will have files
  638. that end in .py completed when the user presses Tab. The "bar"
  639. option will have either of the strings "one", "two", or "three"
  640. completed when the user presses Tab.
  641. "colors" will allow multiple arguments to be completed, separated by
  642. commas. The possible arguments are red, green, and blue. Examples::
  643. my_command --foo some-file.foo --colors=red,green
  644. my_command --colors=green
  645. my_command --colors=green,blue
  646. Descriptions for the actions may be given with the optional C{descr}
  647. keyword argument. This is separate from the description of the option
  648. itself.
  649. Normally Zsh does not show these descriptions unless you have
  650. "verbose" completion turned on. Turn on verbosity with this in your
  651. ~/.zshrc::
  652. zstyle ':completion:*' verbose yes
  653. zstyle ':completion:*:descriptions' format '%B%d%b'
  654. @type extraActions: C{list}
  655. @ivar extraActions: Extra arguments are those arguments typically
  656. appearing at the end of the command-line, which are not associated
  657. with any particular named option. That is, the arguments that are
  658. given to the parseArgs() method of your usage.Options subclass. For
  659. example::
  660. [CompleteFiles(descr="file to read from"),
  661. Completer(descr="book title")]
  662. In the example above, the 1st non-option argument will be described as
  663. "file to read from" and all file/dir names will be completed (*). The
  664. 2nd non-option argument will be described as "book title", but no
  665. actual completion matches will be produced.
  666. See the various C{Completer} subclasses for other types of things which
  667. may be tab-completed (users, groups, network interfaces, etc).
  668. Also note the C{repeat=True} flag which may be passed to any of the
  669. C{Completer} classes. This is set to allow the C{Completer} instance
  670. to be re-used for subsequent command-line words. See the C{Completer}
  671. docstring for details.
  672. """
  673. def __init__(self, descriptions={}, multiUse=[],
  674. mutuallyExclusive=[], optActions={}, extraActions=[]):
  675. self.descriptions = descriptions
  676. self.multiUse = multiUse
  677. self.mutuallyExclusive = mutuallyExclusive
  678. self.optActions = optActions
  679. self.extraActions = extraActions
  680. def docMakeChunks(optList, width=80):
  681. """
  682. Makes doc chunks for option declarations.
  683. Takes a list of dictionaries, each of which may have one or more
  684. of the keys 'long', 'short', 'doc', 'default', 'optType'.
  685. Returns a list of strings.
  686. The strings may be multiple lines,
  687. all of them end with a newline.
  688. """
  689. # XXX: sanity check to make sure we have a sane combination of keys.
  690. maxOptLen = 0
  691. for opt in optList:
  692. optLen = len(opt.get('long', ''))
  693. if optLen:
  694. if opt.get('optType', None) == "parameter":
  695. # these take up an extra character
  696. optLen = optLen + 1
  697. maxOptLen = max(optLen, maxOptLen)
  698. colWidth1 = maxOptLen + len(" -s, -- ")
  699. colWidth2 = width - colWidth1
  700. # XXX - impose some sane minimum limit.
  701. # Then if we don't have enough room for the option and the doc
  702. # to share one line, they can take turns on alternating lines.
  703. colFiller1 = " " * colWidth1
  704. optChunks = []
  705. seen = {}
  706. for opt in optList:
  707. if opt.get('short', None) in seen or opt.get('long', None) in seen:
  708. continue
  709. for x in opt.get('short', None), opt.get('long', None):
  710. if x is not None:
  711. seen[x] = 1
  712. optLines = []
  713. comma = " "
  714. if opt.get('short', None):
  715. short = "-%c" % (opt['short'],)
  716. else:
  717. short = ''
  718. if opt.get('long', None):
  719. long = opt['long']
  720. if opt.get("optType", None) == "parameter":
  721. long = long + '='
  722. long = "%-*s" % (maxOptLen, long)
  723. if short:
  724. comma = ","
  725. else:
  726. long = " " * (maxOptLen + len('--'))
  727. if opt.get('optType', None) == 'command':
  728. column1 = ' %s ' % long
  729. else:
  730. column1 = " %2s%c --%s " % (short, comma, long)
  731. if opt.get('doc', ''):
  732. doc = opt['doc'].strip()
  733. else:
  734. doc = ''
  735. if (opt.get("optType", None) == "parameter") \
  736. and not (opt.get('default', None) is None):
  737. doc = "%s [default: %s]" % (doc, opt['default'])
  738. if (opt.get("optType", None) == "parameter") \
  739. and opt.get('dispatch', None) is not None:
  740. d = opt['dispatch']
  741. if isinstance(d, CoerceParameter) and d.doc:
  742. doc = "%s. %s" % (doc, d.doc)
  743. if doc:
  744. column2_l = textwrap.wrap(doc, colWidth2)
  745. else:
  746. column2_l = ['']
  747. optLines.append("%s%s\n" % (column1, column2_l.pop(0)))
  748. for line in column2_l:
  749. optLines.append("%s%s\n" % (colFiller1, line))
  750. optChunks.append(''.join(optLines))
  751. return optChunks
  752. def flagFunction(method, name=None):
  753. """
  754. Determine whether a function is an optional handler for a I{flag} or an
  755. I{option}.
  756. A I{flag} handler takes no additional arguments. It is used to handle
  757. command-line arguments like I{--nodaemon}.
  758. An I{option} handler takes one argument. It is used to handle command-line
  759. arguments like I{--path=/foo/bar}.
  760. @param method: The bound method object to inspect.
  761. @param name: The name of the option for which the function is a handle.
  762. @type name: L{str}
  763. @raise UsageError: If the method takes more than one argument.
  764. @return: If the method is a flag handler, return C{True}. Otherwise return
  765. C{False}.
  766. """
  767. if _PY3:
  768. reqArgs = len(inspect.signature(method).parameters)
  769. if reqArgs > 1:
  770. raise UsageError('Invalid Option function for %s' %
  771. (name or method.__name__))
  772. if reqArgs == 1:
  773. return False
  774. else:
  775. reqArgs = len(inspect.getargspec(method).args)
  776. if reqArgs > 2:
  777. raise UsageError('Invalid Option function for %s' %
  778. (name or method.__name__))
  779. if reqArgs == 2:
  780. return False
  781. return True
  782. def portCoerce(value):
  783. """
  784. Coerce a string value to an int port number, and checks the validity.
  785. """
  786. value = int(value)
  787. if value < 0 or value > 65535:
  788. raise ValueError("Port number not in range: %s" % (value,))
  789. return value
  790. portCoerce.coerceDoc = "Must be an int between 0 and 65535."