Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

usage.py 34KB

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