core.py 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030
  1. import errno
  2. import inspect
  3. import os
  4. import sys
  5. from contextlib import contextmanager
  6. from functools import update_wrapper
  7. from itertools import repeat
  8. from ._compat import isidentifier
  9. from ._compat import iteritems
  10. from ._compat import PY2
  11. from ._compat import string_types
  12. from ._unicodefun import _check_for_unicode_literals
  13. from ._unicodefun import _verify_python3_env
  14. from .exceptions import Abort
  15. from .exceptions import BadParameter
  16. from .exceptions import ClickException
  17. from .exceptions import Exit
  18. from .exceptions import MissingParameter
  19. from .exceptions import UsageError
  20. from .formatting import HelpFormatter
  21. from .formatting import join_options
  22. from .globals import pop_context
  23. from .globals import push_context
  24. from .parser import OptionParser
  25. from .parser import split_opt
  26. from .termui import confirm
  27. from .termui import prompt
  28. from .termui import style
  29. from .types import BOOL
  30. from .types import convert_type
  31. from .types import IntRange
  32. from .utils import echo
  33. from .utils import get_os_args
  34. from .utils import make_default_short_help
  35. from .utils import make_str
  36. from .utils import PacifyFlushWrapper
  37. _missing = object()
  38. SUBCOMMAND_METAVAR = "COMMAND [ARGS]..."
  39. SUBCOMMANDS_METAVAR = "COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]..."
  40. DEPRECATED_HELP_NOTICE = " (DEPRECATED)"
  41. DEPRECATED_INVOKE_NOTICE = "DeprecationWarning: The command %(name)s is deprecated."
  42. def _maybe_show_deprecated_notice(cmd):
  43. if cmd.deprecated:
  44. echo(style(DEPRECATED_INVOKE_NOTICE % {"name": cmd.name}, fg="red"), err=True)
  45. def fast_exit(code):
  46. """Exit without garbage collection, this speeds up exit by about 10ms for
  47. things like bash completion.
  48. """
  49. sys.stdout.flush()
  50. sys.stderr.flush()
  51. os._exit(code)
  52. def _bashcomplete(cmd, prog_name, complete_var=None):
  53. """Internal handler for the bash completion support."""
  54. if complete_var is None:
  55. complete_var = "_{}_COMPLETE".format(prog_name.replace("-", "_").upper())
  56. complete_instr = os.environ.get(complete_var)
  57. if not complete_instr:
  58. return
  59. from ._bashcomplete import bashcomplete
  60. if bashcomplete(cmd, prog_name, complete_var, complete_instr):
  61. fast_exit(1)
  62. def _check_multicommand(base_command, cmd_name, cmd, register=False):
  63. if not base_command.chain or not isinstance(cmd, MultiCommand):
  64. return
  65. if register:
  66. hint = (
  67. "It is not possible to add multi commands as children to"
  68. " another multi command that is in chain mode."
  69. )
  70. else:
  71. hint = (
  72. "Found a multi command as subcommand to a multi command"
  73. " that is in chain mode. This is not supported."
  74. )
  75. raise RuntimeError(
  76. "{}. Command '{}' is set to chain and '{}' was added as"
  77. " subcommand but it in itself is a multi command. ('{}' is a {}"
  78. " within a chained {} named '{}').".format(
  79. hint,
  80. base_command.name,
  81. cmd_name,
  82. cmd_name,
  83. cmd.__class__.__name__,
  84. base_command.__class__.__name__,
  85. base_command.name,
  86. )
  87. )
  88. def batch(iterable, batch_size):
  89. return list(zip(*repeat(iter(iterable), batch_size)))
  90. def invoke_param_callback(callback, ctx, param, value):
  91. code = getattr(callback, "__code__", None)
  92. args = getattr(code, "co_argcount", 3)
  93. if args < 3:
  94. from warnings import warn
  95. warn(
  96. "Parameter callbacks take 3 args, (ctx, param, value). The"
  97. " 2-arg style is deprecated and will be removed in 8.0.".format(callback),
  98. DeprecationWarning,
  99. stacklevel=3,
  100. )
  101. return callback(ctx, value)
  102. return callback(ctx, param, value)
  103. @contextmanager
  104. def augment_usage_errors(ctx, param=None):
  105. """Context manager that attaches extra information to exceptions."""
  106. try:
  107. yield
  108. except BadParameter as e:
  109. if e.ctx is None:
  110. e.ctx = ctx
  111. if param is not None and e.param is None:
  112. e.param = param
  113. raise
  114. except UsageError as e:
  115. if e.ctx is None:
  116. e.ctx = ctx
  117. raise
  118. def iter_params_for_processing(invocation_order, declaration_order):
  119. """Given a sequence of parameters in the order as should be considered
  120. for processing and an iterable of parameters that exist, this returns
  121. a list in the correct order as they should be processed.
  122. """
  123. def sort_key(item):
  124. try:
  125. idx = invocation_order.index(item)
  126. except ValueError:
  127. idx = float("inf")
  128. return (not item.is_eager, idx)
  129. return sorted(declaration_order, key=sort_key)
  130. class Context(object):
  131. """The context is a special internal object that holds state relevant
  132. for the script execution at every single level. It's normally invisible
  133. to commands unless they opt-in to getting access to it.
  134. The context is useful as it can pass internal objects around and can
  135. control special execution features such as reading data from
  136. environment variables.
  137. A context can be used as context manager in which case it will call
  138. :meth:`close` on teardown.
  139. .. versionadded:: 2.0
  140. Added the `resilient_parsing`, `help_option_names`,
  141. `token_normalize_func` parameters.
  142. .. versionadded:: 3.0
  143. Added the `allow_extra_args` and `allow_interspersed_args`
  144. parameters.
  145. .. versionadded:: 4.0
  146. Added the `color`, `ignore_unknown_options`, and
  147. `max_content_width` parameters.
  148. .. versionadded:: 7.1
  149. Added the `show_default` parameter.
  150. :param command: the command class for this context.
  151. :param parent: the parent context.
  152. :param info_name: the info name for this invocation. Generally this
  153. is the most descriptive name for the script or
  154. command. For the toplevel script it is usually
  155. the name of the script, for commands below it it's
  156. the name of the script.
  157. :param obj: an arbitrary object of user data.
  158. :param auto_envvar_prefix: the prefix to use for automatic environment
  159. variables. If this is `None` then reading
  160. from environment variables is disabled. This
  161. does not affect manually set environment
  162. variables which are always read.
  163. :param default_map: a dictionary (like object) with default values
  164. for parameters.
  165. :param terminal_width: the width of the terminal. The default is
  166. inherit from parent context. If no context
  167. defines the terminal width then auto
  168. detection will be applied.
  169. :param max_content_width: the maximum width for content rendered by
  170. Click (this currently only affects help
  171. pages). This defaults to 80 characters if
  172. not overridden. In other words: even if the
  173. terminal is larger than that, Click will not
  174. format things wider than 80 characters by
  175. default. In addition to that, formatters might
  176. add some safety mapping on the right.
  177. :param resilient_parsing: if this flag is enabled then Click will
  178. parse without any interactivity or callback
  179. invocation. Default values will also be
  180. ignored. This is useful for implementing
  181. things such as completion support.
  182. :param allow_extra_args: if this is set to `True` then extra arguments
  183. at the end will not raise an error and will be
  184. kept on the context. The default is to inherit
  185. from the command.
  186. :param allow_interspersed_args: if this is set to `False` then options
  187. and arguments cannot be mixed. The
  188. default is to inherit from the command.
  189. :param ignore_unknown_options: instructs click to ignore options it does
  190. not know and keeps them for later
  191. processing.
  192. :param help_option_names: optionally a list of strings that define how
  193. the default help parameter is named. The
  194. default is ``['--help']``.
  195. :param token_normalize_func: an optional function that is used to
  196. normalize tokens (options, choices,
  197. etc.). This for instance can be used to
  198. implement case insensitive behavior.
  199. :param color: controls if the terminal supports ANSI colors or not. The
  200. default is autodetection. This is only needed if ANSI
  201. codes are used in texts that Click prints which is by
  202. default not the case. This for instance would affect
  203. help output.
  204. :param show_default: if True, shows defaults for all options.
  205. Even if an option is later created with show_default=False,
  206. this command-level setting overrides it.
  207. """
  208. def __init__(
  209. self,
  210. command,
  211. parent=None,
  212. info_name=None,
  213. obj=None,
  214. auto_envvar_prefix=None,
  215. default_map=None,
  216. terminal_width=None,
  217. max_content_width=None,
  218. resilient_parsing=False,
  219. allow_extra_args=None,
  220. allow_interspersed_args=None,
  221. ignore_unknown_options=None,
  222. help_option_names=None,
  223. token_normalize_func=None,
  224. color=None,
  225. show_default=None,
  226. ):
  227. #: the parent context or `None` if none exists.
  228. self.parent = parent
  229. #: the :class:`Command` for this context.
  230. self.command = command
  231. #: the descriptive information name
  232. self.info_name = info_name
  233. #: the parsed parameters except if the value is hidden in which
  234. #: case it's not remembered.
  235. self.params = {}
  236. #: the leftover arguments.
  237. self.args = []
  238. #: protected arguments. These are arguments that are prepended
  239. #: to `args` when certain parsing scenarios are encountered but
  240. #: must be never propagated to another arguments. This is used
  241. #: to implement nested parsing.
  242. self.protected_args = []
  243. if obj is None and parent is not None:
  244. obj = parent.obj
  245. #: the user object stored.
  246. self.obj = obj
  247. self._meta = getattr(parent, "meta", {})
  248. #: A dictionary (-like object) with defaults for parameters.
  249. if (
  250. default_map is None
  251. and parent is not None
  252. and parent.default_map is not None
  253. ):
  254. default_map = parent.default_map.get(info_name)
  255. self.default_map = default_map
  256. #: This flag indicates if a subcommand is going to be executed. A
  257. #: group callback can use this information to figure out if it's
  258. #: being executed directly or because the execution flow passes
  259. #: onwards to a subcommand. By default it's None, but it can be
  260. #: the name of the subcommand to execute.
  261. #:
  262. #: If chaining is enabled this will be set to ``'*'`` in case
  263. #: any commands are executed. It is however not possible to
  264. #: figure out which ones. If you require this knowledge you
  265. #: should use a :func:`resultcallback`.
  266. self.invoked_subcommand = None
  267. if terminal_width is None and parent is not None:
  268. terminal_width = parent.terminal_width
  269. #: The width of the terminal (None is autodetection).
  270. self.terminal_width = terminal_width
  271. if max_content_width is None and parent is not None:
  272. max_content_width = parent.max_content_width
  273. #: The maximum width of formatted content (None implies a sensible
  274. #: default which is 80 for most things).
  275. self.max_content_width = max_content_width
  276. if allow_extra_args is None:
  277. allow_extra_args = command.allow_extra_args
  278. #: Indicates if the context allows extra args or if it should
  279. #: fail on parsing.
  280. #:
  281. #: .. versionadded:: 3.0
  282. self.allow_extra_args = allow_extra_args
  283. if allow_interspersed_args is None:
  284. allow_interspersed_args = command.allow_interspersed_args
  285. #: Indicates if the context allows mixing of arguments and
  286. #: options or not.
  287. #:
  288. #: .. versionadded:: 3.0
  289. self.allow_interspersed_args = allow_interspersed_args
  290. if ignore_unknown_options is None:
  291. ignore_unknown_options = command.ignore_unknown_options
  292. #: Instructs click to ignore options that a command does not
  293. #: understand and will store it on the context for later
  294. #: processing. This is primarily useful for situations where you
  295. #: want to call into external programs. Generally this pattern is
  296. #: strongly discouraged because it's not possibly to losslessly
  297. #: forward all arguments.
  298. #:
  299. #: .. versionadded:: 4.0
  300. self.ignore_unknown_options = ignore_unknown_options
  301. if help_option_names is None:
  302. if parent is not None:
  303. help_option_names = parent.help_option_names
  304. else:
  305. help_option_names = ["--help"]
  306. #: The names for the help options.
  307. self.help_option_names = help_option_names
  308. if token_normalize_func is None and parent is not None:
  309. token_normalize_func = parent.token_normalize_func
  310. #: An optional normalization function for tokens. This is
  311. #: options, choices, commands etc.
  312. self.token_normalize_func = token_normalize_func
  313. #: Indicates if resilient parsing is enabled. In that case Click
  314. #: will do its best to not cause any failures and default values
  315. #: will be ignored. Useful for completion.
  316. self.resilient_parsing = resilient_parsing
  317. # If there is no envvar prefix yet, but the parent has one and
  318. # the command on this level has a name, we can expand the envvar
  319. # prefix automatically.
  320. if auto_envvar_prefix is None:
  321. if (
  322. parent is not None
  323. and parent.auto_envvar_prefix is not None
  324. and self.info_name is not None
  325. ):
  326. auto_envvar_prefix = "{}_{}".format(
  327. parent.auto_envvar_prefix, self.info_name.upper()
  328. )
  329. else:
  330. auto_envvar_prefix = auto_envvar_prefix.upper()
  331. if auto_envvar_prefix is not None:
  332. auto_envvar_prefix = auto_envvar_prefix.replace("-", "_")
  333. self.auto_envvar_prefix = auto_envvar_prefix
  334. if color is None and parent is not None:
  335. color = parent.color
  336. #: Controls if styling output is wanted or not.
  337. self.color = color
  338. self.show_default = show_default
  339. self._close_callbacks = []
  340. self._depth = 0
  341. def __enter__(self):
  342. self._depth += 1
  343. push_context(self)
  344. return self
  345. def __exit__(self, exc_type, exc_value, tb):
  346. self._depth -= 1
  347. if self._depth == 0:
  348. self.close()
  349. pop_context()
  350. @contextmanager
  351. def scope(self, cleanup=True):
  352. """This helper method can be used with the context object to promote
  353. it to the current thread local (see :func:`get_current_context`).
  354. The default behavior of this is to invoke the cleanup functions which
  355. can be disabled by setting `cleanup` to `False`. The cleanup
  356. functions are typically used for things such as closing file handles.
  357. If the cleanup is intended the context object can also be directly
  358. used as a context manager.
  359. Example usage::
  360. with ctx.scope():
  361. assert get_current_context() is ctx
  362. This is equivalent::
  363. with ctx:
  364. assert get_current_context() is ctx
  365. .. versionadded:: 5.0
  366. :param cleanup: controls if the cleanup functions should be run or
  367. not. The default is to run these functions. In
  368. some situations the context only wants to be
  369. temporarily pushed in which case this can be disabled.
  370. Nested pushes automatically defer the cleanup.
  371. """
  372. if not cleanup:
  373. self._depth += 1
  374. try:
  375. with self as rv:
  376. yield rv
  377. finally:
  378. if not cleanup:
  379. self._depth -= 1
  380. @property
  381. def meta(self):
  382. """This is a dictionary which is shared with all the contexts
  383. that are nested. It exists so that click utilities can store some
  384. state here if they need to. It is however the responsibility of
  385. that code to manage this dictionary well.
  386. The keys are supposed to be unique dotted strings. For instance
  387. module paths are a good choice for it. What is stored in there is
  388. irrelevant for the operation of click. However what is important is
  389. that code that places data here adheres to the general semantics of
  390. the system.
  391. Example usage::
  392. LANG_KEY = f'{__name__}.lang'
  393. def set_language(value):
  394. ctx = get_current_context()
  395. ctx.meta[LANG_KEY] = value
  396. def get_language():
  397. return get_current_context().meta.get(LANG_KEY, 'en_US')
  398. .. versionadded:: 5.0
  399. """
  400. return self._meta
  401. def make_formatter(self):
  402. """Creates the formatter for the help and usage output."""
  403. return HelpFormatter(
  404. width=self.terminal_width, max_width=self.max_content_width
  405. )
  406. def call_on_close(self, f):
  407. """This decorator remembers a function as callback that should be
  408. executed when the context tears down. This is most useful to bind
  409. resource handling to the script execution. For instance, file objects
  410. opened by the :class:`File` type will register their close callbacks
  411. here.
  412. :param f: the function to execute on teardown.
  413. """
  414. self._close_callbacks.append(f)
  415. return f
  416. def close(self):
  417. """Invokes all close callbacks."""
  418. for cb in self._close_callbacks:
  419. cb()
  420. self._close_callbacks = []
  421. @property
  422. def command_path(self):
  423. """The computed command path. This is used for the ``usage``
  424. information on the help page. It's automatically created by
  425. combining the info names of the chain of contexts to the root.
  426. """
  427. rv = ""
  428. if self.info_name is not None:
  429. rv = self.info_name
  430. if self.parent is not None:
  431. rv = "{} {}".format(self.parent.command_path, rv)
  432. return rv.lstrip()
  433. def find_root(self):
  434. """Finds the outermost context."""
  435. node = self
  436. while node.parent is not None:
  437. node = node.parent
  438. return node
  439. def find_object(self, object_type):
  440. """Finds the closest object of a given type."""
  441. node = self
  442. while node is not None:
  443. if isinstance(node.obj, object_type):
  444. return node.obj
  445. node = node.parent
  446. def ensure_object(self, object_type):
  447. """Like :meth:`find_object` but sets the innermost object to a
  448. new instance of `object_type` if it does not exist.
  449. """
  450. rv = self.find_object(object_type)
  451. if rv is None:
  452. self.obj = rv = object_type()
  453. return rv
  454. def lookup_default(self, name):
  455. """Looks up the default for a parameter name. This by default
  456. looks into the :attr:`default_map` if available.
  457. """
  458. if self.default_map is not None:
  459. rv = self.default_map.get(name)
  460. if callable(rv):
  461. rv = rv()
  462. return rv
  463. def fail(self, message):
  464. """Aborts the execution of the program with a specific error
  465. message.
  466. :param message: the error message to fail with.
  467. """
  468. raise UsageError(message, self)
  469. def abort(self):
  470. """Aborts the script."""
  471. raise Abort()
  472. def exit(self, code=0):
  473. """Exits the application with a given exit code."""
  474. raise Exit(code)
  475. def get_usage(self):
  476. """Helper method to get formatted usage string for the current
  477. context and command.
  478. """
  479. return self.command.get_usage(self)
  480. def get_help(self):
  481. """Helper method to get formatted help page for the current
  482. context and command.
  483. """
  484. return self.command.get_help(self)
  485. def invoke(*args, **kwargs): # noqa: B902
  486. """Invokes a command callback in exactly the way it expects. There
  487. are two ways to invoke this method:
  488. 1. the first argument can be a callback and all other arguments and
  489. keyword arguments are forwarded directly to the function.
  490. 2. the first argument is a click command object. In that case all
  491. arguments are forwarded as well but proper click parameters
  492. (options and click arguments) must be keyword arguments and Click
  493. will fill in defaults.
  494. Note that before Click 3.2 keyword arguments were not properly filled
  495. in against the intention of this code and no context was created. For
  496. more information about this change and why it was done in a bugfix
  497. release see :ref:`upgrade-to-3.2`.
  498. """
  499. self, callback = args[:2]
  500. ctx = self
  501. # It's also possible to invoke another command which might or
  502. # might not have a callback. In that case we also fill
  503. # in defaults and make a new context for this command.
  504. if isinstance(callback, Command):
  505. other_cmd = callback
  506. callback = other_cmd.callback
  507. ctx = Context(other_cmd, info_name=other_cmd.name, parent=self)
  508. if callback is None:
  509. raise TypeError(
  510. "The given command does not have a callback that can be invoked."
  511. )
  512. for param in other_cmd.params:
  513. if param.name not in kwargs and param.expose_value:
  514. kwargs[param.name] = param.get_default(ctx)
  515. args = args[2:]
  516. with augment_usage_errors(self):
  517. with ctx:
  518. return callback(*args, **kwargs)
  519. def forward(*args, **kwargs): # noqa: B902
  520. """Similar to :meth:`invoke` but fills in default keyword
  521. arguments from the current context if the other command expects
  522. it. This cannot invoke callbacks directly, only other commands.
  523. """
  524. self, cmd = args[:2]
  525. # It's also possible to invoke another command which might or
  526. # might not have a callback.
  527. if not isinstance(cmd, Command):
  528. raise TypeError("Callback is not a command.")
  529. for param in self.params:
  530. if param not in kwargs:
  531. kwargs[param] = self.params[param]
  532. return self.invoke(cmd, **kwargs)
  533. class BaseCommand(object):
  534. """The base command implements the minimal API contract of commands.
  535. Most code will never use this as it does not implement a lot of useful
  536. functionality but it can act as the direct subclass of alternative
  537. parsing methods that do not depend on the Click parser.
  538. For instance, this can be used to bridge Click and other systems like
  539. argparse or docopt.
  540. Because base commands do not implement a lot of the API that other
  541. parts of Click take for granted, they are not supported for all
  542. operations. For instance, they cannot be used with the decorators
  543. usually and they have no built-in callback system.
  544. .. versionchanged:: 2.0
  545. Added the `context_settings` parameter.
  546. :param name: the name of the command to use unless a group overrides it.
  547. :param context_settings: an optional dictionary with defaults that are
  548. passed to the context object.
  549. """
  550. #: the default for the :attr:`Context.allow_extra_args` flag.
  551. allow_extra_args = False
  552. #: the default for the :attr:`Context.allow_interspersed_args` flag.
  553. allow_interspersed_args = True
  554. #: the default for the :attr:`Context.ignore_unknown_options` flag.
  555. ignore_unknown_options = False
  556. def __init__(self, name, context_settings=None):
  557. #: the name the command thinks it has. Upon registering a command
  558. #: on a :class:`Group` the group will default the command name
  559. #: with this information. You should instead use the
  560. #: :class:`Context`\'s :attr:`~Context.info_name` attribute.
  561. self.name = name
  562. if context_settings is None:
  563. context_settings = {}
  564. #: an optional dictionary with defaults passed to the context.
  565. self.context_settings = context_settings
  566. def __repr__(self):
  567. return "<{} {}>".format(self.__class__.__name__, self.name)
  568. def get_usage(self, ctx):
  569. raise NotImplementedError("Base commands cannot get usage")
  570. def get_help(self, ctx):
  571. raise NotImplementedError("Base commands cannot get help")
  572. def make_context(self, info_name, args, parent=None, **extra):
  573. """This function when given an info name and arguments will kick
  574. off the parsing and create a new :class:`Context`. It does not
  575. invoke the actual command callback though.
  576. :param info_name: the info name for this invokation. Generally this
  577. is the most descriptive name for the script or
  578. command. For the toplevel script it's usually
  579. the name of the script, for commands below it it's
  580. the name of the script.
  581. :param args: the arguments to parse as list of strings.
  582. :param parent: the parent context if available.
  583. :param extra: extra keyword arguments forwarded to the context
  584. constructor.
  585. """
  586. for key, value in iteritems(self.context_settings):
  587. if key not in extra:
  588. extra[key] = value
  589. ctx = Context(self, info_name=info_name, parent=parent, **extra)
  590. with ctx.scope(cleanup=False):
  591. self.parse_args(ctx, args)
  592. return ctx
  593. def parse_args(self, ctx, args):
  594. """Given a context and a list of arguments this creates the parser
  595. and parses the arguments, then modifies the context as necessary.
  596. This is automatically invoked by :meth:`make_context`.
  597. """
  598. raise NotImplementedError("Base commands do not know how to parse arguments.")
  599. def invoke(self, ctx):
  600. """Given a context, this invokes the command. The default
  601. implementation is raising a not implemented error.
  602. """
  603. raise NotImplementedError("Base commands are not invokable by default")
  604. def main(
  605. self,
  606. args=None,
  607. prog_name=None,
  608. complete_var=None,
  609. standalone_mode=True,
  610. **extra
  611. ):
  612. """This is the way to invoke a script with all the bells and
  613. whistles as a command line application. This will always terminate
  614. the application after a call. If this is not wanted, ``SystemExit``
  615. needs to be caught.
  616. This method is also available by directly calling the instance of
  617. a :class:`Command`.
  618. .. versionadded:: 3.0
  619. Added the `standalone_mode` flag to control the standalone mode.
  620. :param args: the arguments that should be used for parsing. If not
  621. provided, ``sys.argv[1:]`` is used.
  622. :param prog_name: the program name that should be used. By default
  623. the program name is constructed by taking the file
  624. name from ``sys.argv[0]``.
  625. :param complete_var: the environment variable that controls the
  626. bash completion support. The default is
  627. ``"_<prog_name>_COMPLETE"`` with prog_name in
  628. uppercase.
  629. :param standalone_mode: the default behavior is to invoke the script
  630. in standalone mode. Click will then
  631. handle exceptions and convert them into
  632. error messages and the function will never
  633. return but shut down the interpreter. If
  634. this is set to `False` they will be
  635. propagated to the caller and the return
  636. value of this function is the return value
  637. of :meth:`invoke`.
  638. :param extra: extra keyword arguments are forwarded to the context
  639. constructor. See :class:`Context` for more information.
  640. """
  641. # If we are in Python 3, we will verify that the environment is
  642. # sane at this point or reject further execution to avoid a
  643. # broken script.
  644. if not PY2:
  645. _verify_python3_env()
  646. else:
  647. _check_for_unicode_literals()
  648. if args is None:
  649. args = get_os_args()
  650. else:
  651. args = list(args)
  652. if prog_name is None:
  653. prog_name = make_str(
  654. os.path.basename(sys.argv[0] if sys.argv else __file__)
  655. )
  656. # Hook for the Bash completion. This only activates if the Bash
  657. # completion is actually enabled, otherwise this is quite a fast
  658. # noop.
  659. _bashcomplete(self, prog_name, complete_var)
  660. try:
  661. try:
  662. with self.make_context(prog_name, args, **extra) as ctx:
  663. rv = self.invoke(ctx)
  664. if not standalone_mode:
  665. return rv
  666. # it's not safe to `ctx.exit(rv)` here!
  667. # note that `rv` may actually contain data like "1" which
  668. # has obvious effects
  669. # more subtle case: `rv=[None, None]` can come out of
  670. # chained commands which all returned `None` -- so it's not
  671. # even always obvious that `rv` indicates success/failure
  672. # by its truthiness/falsiness
  673. ctx.exit()
  674. except (EOFError, KeyboardInterrupt):
  675. echo(file=sys.stderr)
  676. raise Abort()
  677. except ClickException as e:
  678. if not standalone_mode:
  679. raise
  680. e.show()
  681. sys.exit(e.exit_code)
  682. except IOError as e:
  683. if e.errno == errno.EPIPE:
  684. sys.stdout = PacifyFlushWrapper(sys.stdout)
  685. sys.stderr = PacifyFlushWrapper(sys.stderr)
  686. sys.exit(1)
  687. else:
  688. raise
  689. except Exit as e:
  690. if standalone_mode:
  691. sys.exit(e.exit_code)
  692. else:
  693. # in non-standalone mode, return the exit code
  694. # note that this is only reached if `self.invoke` above raises
  695. # an Exit explicitly -- thus bypassing the check there which
  696. # would return its result
  697. # the results of non-standalone execution may therefore be
  698. # somewhat ambiguous: if there are codepaths which lead to
  699. # `ctx.exit(1)` and to `return 1`, the caller won't be able to
  700. # tell the difference between the two
  701. return e.exit_code
  702. except Abort:
  703. if not standalone_mode:
  704. raise
  705. echo("Aborted!", file=sys.stderr)
  706. sys.exit(1)
  707. def __call__(self, *args, **kwargs):
  708. """Alias for :meth:`main`."""
  709. return self.main(*args, **kwargs)
  710. class Command(BaseCommand):
  711. """Commands are the basic building block of command line interfaces in
  712. Click. A basic command handles command line parsing and might dispatch
  713. more parsing to commands nested below it.
  714. .. versionchanged:: 2.0
  715. Added the `context_settings` parameter.
  716. .. versionchanged:: 7.1
  717. Added the `no_args_is_help` parameter.
  718. :param name: the name of the command to use unless a group overrides it.
  719. :param context_settings: an optional dictionary with defaults that are
  720. passed to the context object.
  721. :param callback: the callback to invoke. This is optional.
  722. :param params: the parameters to register with this command. This can
  723. be either :class:`Option` or :class:`Argument` objects.
  724. :param help: the help string to use for this command.
  725. :param epilog: like the help string but it's printed at the end of the
  726. help page after everything else.
  727. :param short_help: the short help to use for this command. This is
  728. shown on the command listing of the parent command.
  729. :param add_help_option: by default each command registers a ``--help``
  730. option. This can be disabled by this parameter.
  731. :param no_args_is_help: this controls what happens if no arguments are
  732. provided. This option is disabled by default.
  733. If enabled this will add ``--help`` as argument
  734. if no arguments are passed
  735. :param hidden: hide this command from help outputs.
  736. :param deprecated: issues a message indicating that
  737. the command is deprecated.
  738. """
  739. def __init__(
  740. self,
  741. name,
  742. context_settings=None,
  743. callback=None,
  744. params=None,
  745. help=None,
  746. epilog=None,
  747. short_help=None,
  748. options_metavar="[OPTIONS]",
  749. add_help_option=True,
  750. no_args_is_help=False,
  751. hidden=False,
  752. deprecated=False,
  753. ):
  754. BaseCommand.__init__(self, name, context_settings)
  755. #: the callback to execute when the command fires. This might be
  756. #: `None` in which case nothing happens.
  757. self.callback = callback
  758. #: the list of parameters for this command in the order they
  759. #: should show up in the help page and execute. Eager parameters
  760. #: will automatically be handled before non eager ones.
  761. self.params = params or []
  762. # if a form feed (page break) is found in the help text, truncate help
  763. # text to the content preceding the first form feed
  764. if help and "\f" in help:
  765. help = help.split("\f", 1)[0]
  766. self.help = help
  767. self.epilog = epilog
  768. self.options_metavar = options_metavar
  769. self.short_help = short_help
  770. self.add_help_option = add_help_option
  771. self.no_args_is_help = no_args_is_help
  772. self.hidden = hidden
  773. self.deprecated = deprecated
  774. def get_usage(self, ctx):
  775. """Formats the usage line into a string and returns it.
  776. Calls :meth:`format_usage` internally.
  777. """
  778. formatter = ctx.make_formatter()
  779. self.format_usage(ctx, formatter)
  780. return formatter.getvalue().rstrip("\n")
  781. def get_params(self, ctx):
  782. rv = self.params
  783. help_option = self.get_help_option(ctx)
  784. if help_option is not None:
  785. rv = rv + [help_option]
  786. return rv
  787. def format_usage(self, ctx, formatter):
  788. """Writes the usage line into the formatter.
  789. This is a low-level method called by :meth:`get_usage`.
  790. """
  791. pieces = self.collect_usage_pieces(ctx)
  792. formatter.write_usage(ctx.command_path, " ".join(pieces))
  793. def collect_usage_pieces(self, ctx):
  794. """Returns all the pieces that go into the usage line and returns
  795. it as a list of strings.
  796. """
  797. rv = [self.options_metavar]
  798. for param in self.get_params(ctx):
  799. rv.extend(param.get_usage_pieces(ctx))
  800. return rv
  801. def get_help_option_names(self, ctx):
  802. """Returns the names for the help option."""
  803. all_names = set(ctx.help_option_names)
  804. for param in self.params:
  805. all_names.difference_update(param.opts)
  806. all_names.difference_update(param.secondary_opts)
  807. return all_names
  808. def get_help_option(self, ctx):
  809. """Returns the help option object."""
  810. help_options = self.get_help_option_names(ctx)
  811. if not help_options or not self.add_help_option:
  812. return
  813. def show_help(ctx, param, value):
  814. if value and not ctx.resilient_parsing:
  815. echo(ctx.get_help(), color=ctx.color)
  816. ctx.exit()
  817. return Option(
  818. help_options,
  819. is_flag=True,
  820. is_eager=True,
  821. expose_value=False,
  822. callback=show_help,
  823. help="Show this message and exit.",
  824. )
  825. def make_parser(self, ctx):
  826. """Creates the underlying option parser for this command."""
  827. parser = OptionParser(ctx)
  828. for param in self.get_params(ctx):
  829. param.add_to_parser(parser, ctx)
  830. return parser
  831. def get_help(self, ctx):
  832. """Formats the help into a string and returns it.
  833. Calls :meth:`format_help` internally.
  834. """
  835. formatter = ctx.make_formatter()
  836. self.format_help(ctx, formatter)
  837. return formatter.getvalue().rstrip("\n")
  838. def get_short_help_str(self, limit=45):
  839. """Gets short help for the command or makes it by shortening the
  840. long help string.
  841. """
  842. return (
  843. self.short_help
  844. or self.help
  845. and make_default_short_help(self.help, limit)
  846. or ""
  847. )
  848. def format_help(self, ctx, formatter):
  849. """Writes the help into the formatter if it exists.
  850. This is a low-level method called by :meth:`get_help`.
  851. This calls the following methods:
  852. - :meth:`format_usage`
  853. - :meth:`format_help_text`
  854. - :meth:`format_options`
  855. - :meth:`format_epilog`
  856. """
  857. self.format_usage(ctx, formatter)
  858. self.format_help_text(ctx, formatter)
  859. self.format_options(ctx, formatter)
  860. self.format_epilog(ctx, formatter)
  861. def format_help_text(self, ctx, formatter):
  862. """Writes the help text to the formatter if it exists."""
  863. if self.help:
  864. formatter.write_paragraph()
  865. with formatter.indentation():
  866. help_text = self.help
  867. if self.deprecated:
  868. help_text += DEPRECATED_HELP_NOTICE
  869. formatter.write_text(help_text)
  870. elif self.deprecated:
  871. formatter.write_paragraph()
  872. with formatter.indentation():
  873. formatter.write_text(DEPRECATED_HELP_NOTICE)
  874. def format_options(self, ctx, formatter):
  875. """Writes all the options into the formatter if they exist."""
  876. opts = []
  877. for param in self.get_params(ctx):
  878. rv = param.get_help_record(ctx)
  879. if rv is not None:
  880. opts.append(rv)
  881. if opts:
  882. with formatter.section("Options"):
  883. formatter.write_dl(opts)
  884. def format_epilog(self, ctx, formatter):
  885. """Writes the epilog into the formatter if it exists."""
  886. if self.epilog:
  887. formatter.write_paragraph()
  888. with formatter.indentation():
  889. formatter.write_text(self.epilog)
  890. def parse_args(self, ctx, args):
  891. if not args and self.no_args_is_help and not ctx.resilient_parsing:
  892. echo(ctx.get_help(), color=ctx.color)
  893. ctx.exit()
  894. parser = self.make_parser(ctx)
  895. opts, args, param_order = parser.parse_args(args=args)
  896. for param in iter_params_for_processing(param_order, self.get_params(ctx)):
  897. value, args = param.handle_parse_result(ctx, opts, args)
  898. if args and not ctx.allow_extra_args and not ctx.resilient_parsing:
  899. ctx.fail(
  900. "Got unexpected extra argument{} ({})".format(
  901. "s" if len(args) != 1 else "", " ".join(map(make_str, args))
  902. )
  903. )
  904. ctx.args = args
  905. return args
  906. def invoke(self, ctx):
  907. """Given a context, this invokes the attached callback (if it exists)
  908. in the right way.
  909. """
  910. _maybe_show_deprecated_notice(self)
  911. if self.callback is not None:
  912. return ctx.invoke(self.callback, **ctx.params)
  913. class MultiCommand(Command):
  914. """A multi command is the basic implementation of a command that
  915. dispatches to subcommands. The most common version is the
  916. :class:`Group`.
  917. :param invoke_without_command: this controls how the multi command itself
  918. is invoked. By default it's only invoked
  919. if a subcommand is provided.
  920. :param no_args_is_help: this controls what happens if no arguments are
  921. provided. This option is enabled by default if
  922. `invoke_without_command` is disabled or disabled
  923. if it's enabled. If enabled this will add
  924. ``--help`` as argument if no arguments are
  925. passed.
  926. :param subcommand_metavar: the string that is used in the documentation
  927. to indicate the subcommand place.
  928. :param chain: if this is set to `True` chaining of multiple subcommands
  929. is enabled. This restricts the form of commands in that
  930. they cannot have optional arguments but it allows
  931. multiple commands to be chained together.
  932. :param result_callback: the result callback to attach to this multi
  933. command.
  934. """
  935. allow_extra_args = True
  936. allow_interspersed_args = False
  937. def __init__(
  938. self,
  939. name=None,
  940. invoke_without_command=False,
  941. no_args_is_help=None,
  942. subcommand_metavar=None,
  943. chain=False,
  944. result_callback=None,
  945. **attrs
  946. ):
  947. Command.__init__(self, name, **attrs)
  948. if no_args_is_help is None:
  949. no_args_is_help = not invoke_without_command
  950. self.no_args_is_help = no_args_is_help
  951. self.invoke_without_command = invoke_without_command
  952. if subcommand_metavar is None:
  953. if chain:
  954. subcommand_metavar = SUBCOMMANDS_METAVAR
  955. else:
  956. subcommand_metavar = SUBCOMMAND_METAVAR
  957. self.subcommand_metavar = subcommand_metavar
  958. self.chain = chain
  959. #: The result callback that is stored. This can be set or
  960. #: overridden with the :func:`resultcallback` decorator.
  961. self.result_callback = result_callback
  962. if self.chain:
  963. for param in self.params:
  964. if isinstance(param, Argument) and not param.required:
  965. raise RuntimeError(
  966. "Multi commands in chain mode cannot have"
  967. " optional arguments."
  968. )
  969. def collect_usage_pieces(self, ctx):
  970. rv = Command.collect_usage_pieces(self, ctx)
  971. rv.append(self.subcommand_metavar)
  972. return rv
  973. def format_options(self, ctx, formatter):
  974. Command.format_options(self, ctx, formatter)
  975. self.format_commands(ctx, formatter)
  976. def resultcallback(self, replace=False):
  977. """Adds a result callback to the chain command. By default if a
  978. result callback is already registered this will chain them but
  979. this can be disabled with the `replace` parameter. The result
  980. callback is invoked with the return value of the subcommand
  981. (or the list of return values from all subcommands if chaining
  982. is enabled) as well as the parameters as they would be passed
  983. to the main callback.
  984. Example::
  985. @click.group()
  986. @click.option('-i', '--input', default=23)
  987. def cli(input):
  988. return 42
  989. @cli.resultcallback()
  990. def process_result(result, input):
  991. return result + input
  992. .. versionadded:: 3.0
  993. :param replace: if set to `True` an already existing result
  994. callback will be removed.
  995. """
  996. def decorator(f):
  997. old_callback = self.result_callback
  998. if old_callback is None or replace:
  999. self.result_callback = f
  1000. return f
  1001. def function(__value, *args, **kwargs):
  1002. return f(old_callback(__value, *args, **kwargs), *args, **kwargs)
  1003. self.result_callback = rv = update_wrapper(function, f)
  1004. return rv
  1005. return decorator
  1006. def format_commands(self, ctx, formatter):
  1007. """Extra format methods for multi methods that adds all the commands
  1008. after the options.
  1009. """
  1010. commands = []
  1011. for subcommand in self.list_commands(ctx):
  1012. cmd = self.get_command(ctx, subcommand)
  1013. # What is this, the tool lied about a command. Ignore it
  1014. if cmd is None:
  1015. continue
  1016. if cmd.hidden:
  1017. continue
  1018. commands.append((subcommand, cmd))
  1019. # allow for 3 times the default spacing
  1020. if len(commands):
  1021. limit = formatter.width - 6 - max(len(cmd[0]) for cmd in commands)
  1022. rows = []
  1023. for subcommand, cmd in commands:
  1024. help = cmd.get_short_help_str(limit)
  1025. rows.append((subcommand, help))
  1026. if rows:
  1027. with formatter.section("Commands"):
  1028. formatter.write_dl(rows)
  1029. def parse_args(self, ctx, args):
  1030. if not args and self.no_args_is_help and not ctx.resilient_parsing:
  1031. echo(ctx.get_help(), color=ctx.color)
  1032. ctx.exit()
  1033. rest = Command.parse_args(self, ctx, args)
  1034. if self.chain:
  1035. ctx.protected_args = rest
  1036. ctx.args = []
  1037. elif rest:
  1038. ctx.protected_args, ctx.args = rest[:1], rest[1:]
  1039. return ctx.args
  1040. def invoke(self, ctx):
  1041. def _process_result(value):
  1042. if self.result_callback is not None:
  1043. value = ctx.invoke(self.result_callback, value, **ctx.params)
  1044. return value
  1045. if not ctx.protected_args:
  1046. # If we are invoked without command the chain flag controls
  1047. # how this happens. If we are not in chain mode, the return
  1048. # value here is the return value of the command.
  1049. # If however we are in chain mode, the return value is the
  1050. # return value of the result processor invoked with an empty
  1051. # list (which means that no subcommand actually was executed).
  1052. if self.invoke_without_command:
  1053. if not self.chain:
  1054. return Command.invoke(self, ctx)
  1055. with ctx:
  1056. Command.invoke(self, ctx)
  1057. return _process_result([])
  1058. ctx.fail("Missing command.")
  1059. # Fetch args back out
  1060. args = ctx.protected_args + ctx.args
  1061. ctx.args = []
  1062. ctx.protected_args = []
  1063. # If we're not in chain mode, we only allow the invocation of a
  1064. # single command but we also inform the current context about the
  1065. # name of the command to invoke.
  1066. if not self.chain:
  1067. # Make sure the context is entered so we do not clean up
  1068. # resources until the result processor has worked.
  1069. with ctx:
  1070. cmd_name, cmd, args = self.resolve_command(ctx, args)
  1071. ctx.invoked_subcommand = cmd_name
  1072. Command.invoke(self, ctx)
  1073. sub_ctx = cmd.make_context(cmd_name, args, parent=ctx)
  1074. with sub_ctx:
  1075. return _process_result(sub_ctx.command.invoke(sub_ctx))
  1076. # In chain mode we create the contexts step by step, but after the
  1077. # base command has been invoked. Because at that point we do not
  1078. # know the subcommands yet, the invoked subcommand attribute is
  1079. # set to ``*`` to inform the command that subcommands are executed
  1080. # but nothing else.
  1081. with ctx:
  1082. ctx.invoked_subcommand = "*" if args else None
  1083. Command.invoke(self, ctx)
  1084. # Otherwise we make every single context and invoke them in a
  1085. # chain. In that case the return value to the result processor
  1086. # is the list of all invoked subcommand's results.
  1087. contexts = []
  1088. while args:
  1089. cmd_name, cmd, args = self.resolve_command(ctx, args)
  1090. sub_ctx = cmd.make_context(
  1091. cmd_name,
  1092. args,
  1093. parent=ctx,
  1094. allow_extra_args=True,
  1095. allow_interspersed_args=False,
  1096. )
  1097. contexts.append(sub_ctx)
  1098. args, sub_ctx.args = sub_ctx.args, []
  1099. rv = []
  1100. for sub_ctx in contexts:
  1101. with sub_ctx:
  1102. rv.append(sub_ctx.command.invoke(sub_ctx))
  1103. return _process_result(rv)
  1104. def resolve_command(self, ctx, args):
  1105. cmd_name = make_str(args[0])
  1106. original_cmd_name = cmd_name
  1107. # Get the command
  1108. cmd = self.get_command(ctx, cmd_name)
  1109. # If we can't find the command but there is a normalization
  1110. # function available, we try with that one.
  1111. if cmd is None and ctx.token_normalize_func is not None:
  1112. cmd_name = ctx.token_normalize_func(cmd_name)
  1113. cmd = self.get_command(ctx, cmd_name)
  1114. # If we don't find the command we want to show an error message
  1115. # to the user that it was not provided. However, there is
  1116. # something else we should do: if the first argument looks like
  1117. # an option we want to kick off parsing again for arguments to
  1118. # resolve things like --help which now should go to the main
  1119. # place.
  1120. if cmd is None and not ctx.resilient_parsing:
  1121. if split_opt(cmd_name)[0]:
  1122. self.parse_args(ctx, ctx.args)
  1123. ctx.fail("No such command '{}'.".format(original_cmd_name))
  1124. return cmd_name, cmd, args[1:]
  1125. def get_command(self, ctx, cmd_name):
  1126. """Given a context and a command name, this returns a
  1127. :class:`Command` object if it exists or returns `None`.
  1128. """
  1129. raise NotImplementedError()
  1130. def list_commands(self, ctx):
  1131. """Returns a list of subcommand names in the order they should
  1132. appear.
  1133. """
  1134. return []
  1135. class Group(MultiCommand):
  1136. """A group allows a command to have subcommands attached. This is the
  1137. most common way to implement nesting in Click.
  1138. :param commands: a dictionary of commands.
  1139. """
  1140. def __init__(self, name=None, commands=None, **attrs):
  1141. MultiCommand.__init__(self, name, **attrs)
  1142. #: the registered subcommands by their exported names.
  1143. self.commands = commands or {}
  1144. def add_command(self, cmd, name=None):
  1145. """Registers another :class:`Command` with this group. If the name
  1146. is not provided, the name of the command is used.
  1147. """
  1148. name = name or cmd.name
  1149. if name is None:
  1150. raise TypeError("Command has no name.")
  1151. _check_multicommand(self, name, cmd, register=True)
  1152. self.commands[name] = cmd
  1153. def command(self, *args, **kwargs):
  1154. """A shortcut decorator for declaring and attaching a command to
  1155. the group. This takes the same arguments as :func:`command` but
  1156. immediately registers the created command with this instance by
  1157. calling into :meth:`add_command`.
  1158. """
  1159. from .decorators import command
  1160. def decorator(f):
  1161. cmd = command(*args, **kwargs)(f)
  1162. self.add_command(cmd)
  1163. return cmd
  1164. return decorator
  1165. def group(self, *args, **kwargs):
  1166. """A shortcut decorator for declaring and attaching a group to
  1167. the group. This takes the same arguments as :func:`group` but
  1168. immediately registers the created command with this instance by
  1169. calling into :meth:`add_command`.
  1170. """
  1171. from .decorators import group
  1172. def decorator(f):
  1173. cmd = group(*args, **kwargs)(f)
  1174. self.add_command(cmd)
  1175. return cmd
  1176. return decorator
  1177. def get_command(self, ctx, cmd_name):
  1178. return self.commands.get(cmd_name)
  1179. def list_commands(self, ctx):
  1180. return sorted(self.commands)
  1181. class CommandCollection(MultiCommand):
  1182. """A command collection is a multi command that merges multiple multi
  1183. commands together into one. This is a straightforward implementation
  1184. that accepts a list of different multi commands as sources and
  1185. provides all the commands for each of them.
  1186. """
  1187. def __init__(self, name=None, sources=None, **attrs):
  1188. MultiCommand.__init__(self, name, **attrs)
  1189. #: The list of registered multi commands.
  1190. self.sources = sources or []
  1191. def add_source(self, multi_cmd):
  1192. """Adds a new multi command to the chain dispatcher."""
  1193. self.sources.append(multi_cmd)
  1194. def get_command(self, ctx, cmd_name):
  1195. for source in self.sources:
  1196. rv = source.get_command(ctx, cmd_name)
  1197. if rv is not None:
  1198. if self.chain:
  1199. _check_multicommand(self, cmd_name, rv)
  1200. return rv
  1201. def list_commands(self, ctx):
  1202. rv = set()
  1203. for source in self.sources:
  1204. rv.update(source.list_commands(ctx))
  1205. return sorted(rv)
  1206. class Parameter(object):
  1207. r"""A parameter to a command comes in two versions: they are either
  1208. :class:`Option`\s or :class:`Argument`\s. Other subclasses are currently
  1209. not supported by design as some of the internals for parsing are
  1210. intentionally not finalized.
  1211. Some settings are supported by both options and arguments.
  1212. :param param_decls: the parameter declarations for this option or
  1213. argument. This is a list of flags or argument
  1214. names.
  1215. :param type: the type that should be used. Either a :class:`ParamType`
  1216. or a Python type. The later is converted into the former
  1217. automatically if supported.
  1218. :param required: controls if this is optional or not.
  1219. :param default: the default value if omitted. This can also be a callable,
  1220. in which case it's invoked when the default is needed
  1221. without any arguments.
  1222. :param callback: a callback that should be executed after the parameter
  1223. was matched. This is called as ``fn(ctx, param,
  1224. value)`` and needs to return the value.
  1225. :param nargs: the number of arguments to match. If not ``1`` the return
  1226. value is a tuple instead of single value. The default for
  1227. nargs is ``1`` (except if the type is a tuple, then it's
  1228. the arity of the tuple).
  1229. :param metavar: how the value is represented in the help page.
  1230. :param expose_value: if this is `True` then the value is passed onwards
  1231. to the command callback and stored on the context,
  1232. otherwise it's skipped.
  1233. :param is_eager: eager values are processed before non eager ones. This
  1234. should not be set for arguments or it will inverse the
  1235. order of processing.
  1236. :param envvar: a string or list of strings that are environment variables
  1237. that should be checked.
  1238. .. versionchanged:: 7.1
  1239. Empty environment variables are ignored rather than taking the
  1240. empty string value. This makes it possible for scripts to clear
  1241. variables if they can't unset them.
  1242. .. versionchanged:: 2.0
  1243. Changed signature for parameter callback to also be passed the
  1244. parameter. The old callback format will still work, but it will
  1245. raise a warning to give you a chance to migrate the code easier.
  1246. """
  1247. param_type_name = "parameter"
  1248. def __init__(
  1249. self,
  1250. param_decls=None,
  1251. type=None,
  1252. required=False,
  1253. default=None,
  1254. callback=None,
  1255. nargs=None,
  1256. metavar=None,
  1257. expose_value=True,
  1258. is_eager=False,
  1259. envvar=None,
  1260. autocompletion=None,
  1261. ):
  1262. self.name, self.opts, self.secondary_opts = self._parse_decls(
  1263. param_decls or (), expose_value
  1264. )
  1265. self.type = convert_type(type, default)
  1266. # Default nargs to what the type tells us if we have that
  1267. # information available.
  1268. if nargs is None:
  1269. if self.type.is_composite:
  1270. nargs = self.type.arity
  1271. else:
  1272. nargs = 1
  1273. self.required = required
  1274. self.callback = callback
  1275. self.nargs = nargs
  1276. self.multiple = False
  1277. self.expose_value = expose_value
  1278. self.default = default
  1279. self.is_eager = is_eager
  1280. self.metavar = metavar
  1281. self.envvar = envvar
  1282. self.autocompletion = autocompletion
  1283. def __repr__(self):
  1284. return "<{} {}>".format(self.__class__.__name__, self.name)
  1285. @property
  1286. def human_readable_name(self):
  1287. """Returns the human readable name of this parameter. This is the
  1288. same as the name for options, but the metavar for arguments.
  1289. """
  1290. return self.name
  1291. def make_metavar(self):
  1292. if self.metavar is not None:
  1293. return self.metavar
  1294. metavar = self.type.get_metavar(self)
  1295. if metavar is None:
  1296. metavar = self.type.name.upper()
  1297. if self.nargs != 1:
  1298. metavar += "..."
  1299. return metavar
  1300. def get_default(self, ctx):
  1301. """Given a context variable this calculates the default value."""
  1302. # Otherwise go with the regular default.
  1303. if callable(self.default):
  1304. rv = self.default()
  1305. else:
  1306. rv = self.default
  1307. return self.type_cast_value(ctx, rv)
  1308. def add_to_parser(self, parser, ctx):
  1309. pass
  1310. def consume_value(self, ctx, opts):
  1311. value = opts.get(self.name)
  1312. if value is None:
  1313. value = self.value_from_envvar(ctx)
  1314. if value is None:
  1315. value = ctx.lookup_default(self.name)
  1316. return value
  1317. def type_cast_value(self, ctx, value):
  1318. """Given a value this runs it properly through the type system.
  1319. This automatically handles things like `nargs` and `multiple` as
  1320. well as composite types.
  1321. """
  1322. if self.type.is_composite:
  1323. if self.nargs <= 1:
  1324. raise TypeError(
  1325. "Attempted to invoke composite type but nargs has"
  1326. " been set to {}. This is not supported; nargs"
  1327. " needs to be set to a fixed value > 1.".format(self.nargs)
  1328. )
  1329. if self.multiple:
  1330. return tuple(self.type(x or (), self, ctx) for x in value or ())
  1331. return self.type(value or (), self, ctx)
  1332. def _convert(value, level):
  1333. if level == 0:
  1334. return self.type(value, self, ctx)
  1335. return tuple(_convert(x, level - 1) for x in value or ())
  1336. return _convert(value, (self.nargs != 1) + bool(self.multiple))
  1337. def process_value(self, ctx, value):
  1338. """Given a value and context this runs the logic to convert the
  1339. value as necessary.
  1340. """
  1341. # If the value we were given is None we do nothing. This way
  1342. # code that calls this can easily figure out if something was
  1343. # not provided. Otherwise it would be converted into an empty
  1344. # tuple for multiple invocations which is inconvenient.
  1345. if value is not None:
  1346. return self.type_cast_value(ctx, value)
  1347. def value_is_missing(self, value):
  1348. if value is None:
  1349. return True
  1350. if (self.nargs != 1 or self.multiple) and value == ():
  1351. return True
  1352. return False
  1353. def full_process_value(self, ctx, value):
  1354. value = self.process_value(ctx, value)
  1355. if value is None and not ctx.resilient_parsing:
  1356. value = self.get_default(ctx)
  1357. if self.required and self.value_is_missing(value):
  1358. raise MissingParameter(ctx=ctx, param=self)
  1359. return value
  1360. def resolve_envvar_value(self, ctx):
  1361. if self.envvar is None:
  1362. return
  1363. if isinstance(self.envvar, (tuple, list)):
  1364. for envvar in self.envvar:
  1365. rv = os.environ.get(envvar)
  1366. if rv is not None:
  1367. return rv
  1368. else:
  1369. rv = os.environ.get(self.envvar)
  1370. if rv != "":
  1371. return rv
  1372. def value_from_envvar(self, ctx):
  1373. rv = self.resolve_envvar_value(ctx)
  1374. if rv is not None and self.nargs != 1:
  1375. rv = self.type.split_envvar_value(rv)
  1376. return rv
  1377. def handle_parse_result(self, ctx, opts, args):
  1378. with augment_usage_errors(ctx, param=self):
  1379. value = self.consume_value(ctx, opts)
  1380. try:
  1381. value = self.full_process_value(ctx, value)
  1382. except Exception:
  1383. if not ctx.resilient_parsing:
  1384. raise
  1385. value = None
  1386. if self.callback is not None:
  1387. try:
  1388. value = invoke_param_callback(self.callback, ctx, self, value)
  1389. except Exception:
  1390. if not ctx.resilient_parsing:
  1391. raise
  1392. if self.expose_value:
  1393. ctx.params[self.name] = value
  1394. return value, args
  1395. def get_help_record(self, ctx):
  1396. pass
  1397. def get_usage_pieces(self, ctx):
  1398. return []
  1399. def get_error_hint(self, ctx):
  1400. """Get a stringified version of the param for use in error messages to
  1401. indicate which param caused the error.
  1402. """
  1403. hint_list = self.opts or [self.human_readable_name]
  1404. return " / ".join(repr(x) for x in hint_list)
  1405. class Option(Parameter):
  1406. """Options are usually optional values on the command line and
  1407. have some extra features that arguments don't have.
  1408. All other parameters are passed onwards to the parameter constructor.
  1409. :param show_default: controls if the default value should be shown on the
  1410. help page. Normally, defaults are not shown. If this
  1411. value is a string, it shows the string instead of the
  1412. value. This is particularly useful for dynamic options.
  1413. :param show_envvar: controls if an environment variable should be shown on
  1414. the help page. Normally, environment variables
  1415. are not shown.
  1416. :param prompt: if set to `True` or a non empty string then the user will be
  1417. prompted for input. If set to `True` the prompt will be the
  1418. option name capitalized.
  1419. :param confirmation_prompt: if set then the value will need to be confirmed
  1420. if it was prompted for.
  1421. :param hide_input: if this is `True` then the input on the prompt will be
  1422. hidden from the user. This is useful for password
  1423. input.
  1424. :param is_flag: forces this option to act as a flag. The default is
  1425. auto detection.
  1426. :param flag_value: which value should be used for this flag if it's
  1427. enabled. This is set to a boolean automatically if
  1428. the option string contains a slash to mark two options.
  1429. :param multiple: if this is set to `True` then the argument is accepted
  1430. multiple times and recorded. This is similar to ``nargs``
  1431. in how it works but supports arbitrary number of
  1432. arguments.
  1433. :param count: this flag makes an option increment an integer.
  1434. :param allow_from_autoenv: if this is enabled then the value of this
  1435. parameter will be pulled from an environment
  1436. variable in case a prefix is defined on the
  1437. context.
  1438. :param help: the help string.
  1439. :param hidden: hide this option from help outputs.
  1440. """
  1441. param_type_name = "option"
  1442. def __init__(
  1443. self,
  1444. param_decls=None,
  1445. show_default=False,
  1446. prompt=False,
  1447. confirmation_prompt=False,
  1448. hide_input=False,
  1449. is_flag=None,
  1450. flag_value=None,
  1451. multiple=False,
  1452. count=False,
  1453. allow_from_autoenv=True,
  1454. type=None,
  1455. help=None,
  1456. hidden=False,
  1457. show_choices=True,
  1458. show_envvar=False,
  1459. **attrs
  1460. ):
  1461. default_is_missing = attrs.get("default", _missing) is _missing
  1462. Parameter.__init__(self, param_decls, type=type, **attrs)
  1463. if prompt is True:
  1464. prompt_text = self.name.replace("_", " ").capitalize()
  1465. elif prompt is False:
  1466. prompt_text = None
  1467. else:
  1468. prompt_text = prompt
  1469. self.prompt = prompt_text
  1470. self.confirmation_prompt = confirmation_prompt
  1471. self.hide_input = hide_input
  1472. self.hidden = hidden
  1473. # Flags
  1474. if is_flag is None:
  1475. if flag_value is not None:
  1476. is_flag = True
  1477. else:
  1478. is_flag = bool(self.secondary_opts)
  1479. if is_flag and default_is_missing:
  1480. self.default = False
  1481. if flag_value is None:
  1482. flag_value = not self.default
  1483. self.is_flag = is_flag
  1484. self.flag_value = flag_value
  1485. if self.is_flag and isinstance(self.flag_value, bool) and type in [None, bool]:
  1486. self.type = BOOL
  1487. self.is_bool_flag = True
  1488. else:
  1489. self.is_bool_flag = False
  1490. # Counting
  1491. self.count = count
  1492. if count:
  1493. if type is None:
  1494. self.type = IntRange(min=0)
  1495. if default_is_missing:
  1496. self.default = 0
  1497. self.multiple = multiple
  1498. self.allow_from_autoenv = allow_from_autoenv
  1499. self.help = help
  1500. self.show_default = show_default
  1501. self.show_choices = show_choices
  1502. self.show_envvar = show_envvar
  1503. # Sanity check for stuff we don't support
  1504. if __debug__:
  1505. if self.nargs < 0:
  1506. raise TypeError("Options cannot have nargs < 0")
  1507. if self.prompt and self.is_flag and not self.is_bool_flag:
  1508. raise TypeError("Cannot prompt for flags that are not bools.")
  1509. if not self.is_bool_flag and self.secondary_opts:
  1510. raise TypeError("Got secondary option for non boolean flag.")
  1511. if self.is_bool_flag and self.hide_input and self.prompt is not None:
  1512. raise TypeError("Hidden input does not work with boolean flag prompts.")
  1513. if self.count:
  1514. if self.multiple:
  1515. raise TypeError(
  1516. "Options cannot be multiple and count at the same time."
  1517. )
  1518. elif self.is_flag:
  1519. raise TypeError(
  1520. "Options cannot be count and flags at the same time."
  1521. )
  1522. def _parse_decls(self, decls, expose_value):
  1523. opts = []
  1524. secondary_opts = []
  1525. name = None
  1526. possible_names = []
  1527. for decl in decls:
  1528. if isidentifier(decl):
  1529. if name is not None:
  1530. raise TypeError("Name defined twice")
  1531. name = decl
  1532. else:
  1533. split_char = ";" if decl[:1] == "/" else "/"
  1534. if split_char in decl:
  1535. first, second = decl.split(split_char, 1)
  1536. first = first.rstrip()
  1537. if first:
  1538. possible_names.append(split_opt(first))
  1539. opts.append(first)
  1540. second = second.lstrip()
  1541. if second:
  1542. secondary_opts.append(second.lstrip())
  1543. else:
  1544. possible_names.append(split_opt(decl))
  1545. opts.append(decl)
  1546. if name is None and possible_names:
  1547. possible_names.sort(key=lambda x: -len(x[0])) # group long options first
  1548. name = possible_names[0][1].replace("-", "_").lower()
  1549. if not isidentifier(name):
  1550. name = None
  1551. if name is None:
  1552. if not expose_value:
  1553. return None, opts, secondary_opts
  1554. raise TypeError("Could not determine name for option")
  1555. if not opts and not secondary_opts:
  1556. raise TypeError(
  1557. "No options defined but a name was passed ({}). Did you"
  1558. " mean to declare an argument instead of an option?".format(name)
  1559. )
  1560. return name, opts, secondary_opts
  1561. def add_to_parser(self, parser, ctx):
  1562. kwargs = {
  1563. "dest": self.name,
  1564. "nargs": self.nargs,
  1565. "obj": self,
  1566. }
  1567. if self.multiple:
  1568. action = "append"
  1569. elif self.count:
  1570. action = "count"
  1571. else:
  1572. action = "store"
  1573. if self.is_flag:
  1574. kwargs.pop("nargs", None)
  1575. action_const = "{}_const".format(action)
  1576. if self.is_bool_flag and self.secondary_opts:
  1577. parser.add_option(self.opts, action=action_const, const=True, **kwargs)
  1578. parser.add_option(
  1579. self.secondary_opts, action=action_const, const=False, **kwargs
  1580. )
  1581. else:
  1582. parser.add_option(
  1583. self.opts, action=action_const, const=self.flag_value, **kwargs
  1584. )
  1585. else:
  1586. kwargs["action"] = action
  1587. parser.add_option(self.opts, **kwargs)
  1588. def get_help_record(self, ctx):
  1589. if self.hidden:
  1590. return
  1591. any_prefix_is_slash = []
  1592. def _write_opts(opts):
  1593. rv, any_slashes = join_options(opts)
  1594. if any_slashes:
  1595. any_prefix_is_slash[:] = [True]
  1596. if not self.is_flag and not self.count:
  1597. rv += " {}".format(self.make_metavar())
  1598. return rv
  1599. rv = [_write_opts(self.opts)]
  1600. if self.secondary_opts:
  1601. rv.append(_write_opts(self.secondary_opts))
  1602. help = self.help or ""
  1603. extra = []
  1604. if self.show_envvar:
  1605. envvar = self.envvar
  1606. if envvar is None:
  1607. if self.allow_from_autoenv and ctx.auto_envvar_prefix is not None:
  1608. envvar = "{}_{}".format(ctx.auto_envvar_prefix, self.name.upper())
  1609. if envvar is not None:
  1610. extra.append(
  1611. "env var: {}".format(
  1612. ", ".join(str(d) for d in envvar)
  1613. if isinstance(envvar, (list, tuple))
  1614. else envvar
  1615. )
  1616. )
  1617. if self.default is not None and (self.show_default or ctx.show_default):
  1618. if isinstance(self.show_default, string_types):
  1619. default_string = "({})".format(self.show_default)
  1620. elif isinstance(self.default, (list, tuple)):
  1621. default_string = ", ".join(str(d) for d in self.default)
  1622. elif inspect.isfunction(self.default):
  1623. default_string = "(dynamic)"
  1624. else:
  1625. default_string = self.default
  1626. extra.append("default: {}".format(default_string))
  1627. if self.required:
  1628. extra.append("required")
  1629. if extra:
  1630. help = "{}[{}]".format(
  1631. "{} ".format(help) if help else "", "; ".join(extra)
  1632. )
  1633. return ("; " if any_prefix_is_slash else " / ").join(rv), help
  1634. def get_default(self, ctx):
  1635. # If we're a non boolean flag our default is more complex because
  1636. # we need to look at all flags in the same group to figure out
  1637. # if we're the the default one in which case we return the flag
  1638. # value as default.
  1639. if self.is_flag and not self.is_bool_flag:
  1640. for param in ctx.command.params:
  1641. if param.name == self.name and param.default:
  1642. return param.flag_value
  1643. return None
  1644. return Parameter.get_default(self, ctx)
  1645. def prompt_for_value(self, ctx):
  1646. """This is an alternative flow that can be activated in the full
  1647. value processing if a value does not exist. It will prompt the
  1648. user until a valid value exists and then returns the processed
  1649. value as result.
  1650. """
  1651. # Calculate the default before prompting anything to be stable.
  1652. default = self.get_default(ctx)
  1653. # If this is a prompt for a flag we need to handle this
  1654. # differently.
  1655. if self.is_bool_flag:
  1656. return confirm(self.prompt, default)
  1657. return prompt(
  1658. self.prompt,
  1659. default=default,
  1660. type=self.type,
  1661. hide_input=self.hide_input,
  1662. show_choices=self.show_choices,
  1663. confirmation_prompt=self.confirmation_prompt,
  1664. value_proc=lambda x: self.process_value(ctx, x),
  1665. )
  1666. def resolve_envvar_value(self, ctx):
  1667. rv = Parameter.resolve_envvar_value(self, ctx)
  1668. if rv is not None:
  1669. return rv
  1670. if self.allow_from_autoenv and ctx.auto_envvar_prefix is not None:
  1671. envvar = "{}_{}".format(ctx.auto_envvar_prefix, self.name.upper())
  1672. return os.environ.get(envvar)
  1673. def value_from_envvar(self, ctx):
  1674. rv = self.resolve_envvar_value(ctx)
  1675. if rv is None:
  1676. return None
  1677. value_depth = (self.nargs != 1) + bool(self.multiple)
  1678. if value_depth > 0 and rv is not None:
  1679. rv = self.type.split_envvar_value(rv)
  1680. if self.multiple and self.nargs != 1:
  1681. rv = batch(rv, self.nargs)
  1682. return rv
  1683. def full_process_value(self, ctx, value):
  1684. if value is None and self.prompt is not None and not ctx.resilient_parsing:
  1685. return self.prompt_for_value(ctx)
  1686. return Parameter.full_process_value(self, ctx, value)
  1687. class Argument(Parameter):
  1688. """Arguments are positional parameters to a command. They generally
  1689. provide fewer features than options but can have infinite ``nargs``
  1690. and are required by default.
  1691. All parameters are passed onwards to the parameter constructor.
  1692. """
  1693. param_type_name = "argument"
  1694. def __init__(self, param_decls, required=None, **attrs):
  1695. if required is None:
  1696. if attrs.get("default") is not None:
  1697. required = False
  1698. else:
  1699. required = attrs.get("nargs", 1) > 0
  1700. Parameter.__init__(self, param_decls, required=required, **attrs)
  1701. if self.default is not None and self.nargs < 0:
  1702. raise TypeError(
  1703. "nargs=-1 in combination with a default value is not supported."
  1704. )
  1705. @property
  1706. def human_readable_name(self):
  1707. if self.metavar is not None:
  1708. return self.metavar
  1709. return self.name.upper()
  1710. def make_metavar(self):
  1711. if self.metavar is not None:
  1712. return self.metavar
  1713. var = self.type.get_metavar(self)
  1714. if not var:
  1715. var = self.name.upper()
  1716. if not self.required:
  1717. var = "[{}]".format(var)
  1718. if self.nargs != 1:
  1719. var += "..."
  1720. return var
  1721. def _parse_decls(self, decls, expose_value):
  1722. if not decls:
  1723. if not expose_value:
  1724. return None, [], []
  1725. raise TypeError("Could not determine name for argument")
  1726. if len(decls) == 1:
  1727. name = arg = decls[0]
  1728. name = name.replace("-", "_").lower()
  1729. else:
  1730. raise TypeError(
  1731. "Arguments take exactly one parameter declaration, got"
  1732. " {}".format(len(decls))
  1733. )
  1734. return name, [arg], []
  1735. def get_usage_pieces(self, ctx):
  1736. return [self.make_metavar()]
  1737. def get_error_hint(self, ctx):
  1738. return repr(self.make_metavar())
  1739. def add_to_parser(self, parser, ctx):
  1740. parser.add_argument(dest=self.name, nargs=self.nargs, obj=self)