core.py 111 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042
  1. import enum
  2. import errno
  3. import inspect
  4. import os
  5. import sys
  6. import typing as t
  7. from collections import abc
  8. from contextlib import contextmanager
  9. from contextlib import ExitStack
  10. from functools import update_wrapper
  11. from gettext import gettext as _
  12. from gettext import ngettext
  13. from itertools import repeat
  14. from types import TracebackType
  15. from . import types
  16. from .exceptions import Abort
  17. from .exceptions import BadParameter
  18. from .exceptions import ClickException
  19. from .exceptions import Exit
  20. from .exceptions import MissingParameter
  21. from .exceptions import UsageError
  22. from .formatting import HelpFormatter
  23. from .formatting import join_options
  24. from .globals import pop_context
  25. from .globals import push_context
  26. from .parser import _flag_needs_value
  27. from .parser import OptionParser
  28. from .parser import split_opt
  29. from .termui import confirm
  30. from .termui import prompt
  31. from .termui import style
  32. from .utils import _detect_program_name
  33. from .utils import _expand_args
  34. from .utils import echo
  35. from .utils import make_default_short_help
  36. from .utils import make_str
  37. from .utils import PacifyFlushWrapper
  38. if t.TYPE_CHECKING:
  39. import typing_extensions as te
  40. from .shell_completion import CompletionItem
  41. F = t.TypeVar("F", bound=t.Callable[..., t.Any])
  42. V = t.TypeVar("V")
  43. def _complete_visible_commands(
  44. ctx: "Context", incomplete: str
  45. ) -> t.Iterator[t.Tuple[str, "Command"]]:
  46. """List all the subcommands of a group that start with the
  47. incomplete value and aren't hidden.
  48. :param ctx: Invocation context for the group.
  49. :param incomplete: Value being completed. May be empty.
  50. """
  51. multi = t.cast(MultiCommand, ctx.command)
  52. for name in multi.list_commands(ctx):
  53. if name.startswith(incomplete):
  54. command = multi.get_command(ctx, name)
  55. if command is not None and not command.hidden:
  56. yield name, command
  57. def _check_multicommand(
  58. base_command: "MultiCommand", cmd_name: str, cmd: "Command", register: bool = False
  59. ) -> None:
  60. if not base_command.chain or not isinstance(cmd, MultiCommand):
  61. return
  62. if register:
  63. hint = (
  64. "It is not possible to add multi commands as children to"
  65. " another multi command that is in chain mode."
  66. )
  67. else:
  68. hint = (
  69. "Found a multi command as subcommand to a multi command"
  70. " that is in chain mode. This is not supported."
  71. )
  72. raise RuntimeError(
  73. f"{hint}. Command {base_command.name!r} is set to chain and"
  74. f" {cmd_name!r} was added as a subcommand but it in itself is a"
  75. f" multi command. ({cmd_name!r} is a {type(cmd).__name__}"
  76. f" within a chained {type(base_command).__name__} named"
  77. f" {base_command.name!r})."
  78. )
  79. def batch(iterable: t.Iterable[V], batch_size: int) -> t.List[t.Tuple[V, ...]]:
  80. return list(zip(*repeat(iter(iterable), batch_size)))
  81. @contextmanager
  82. def augment_usage_errors(
  83. ctx: "Context", param: t.Optional["Parameter"] = None
  84. ) -> t.Iterator[None]:
  85. """Context manager that attaches extra information to exceptions."""
  86. try:
  87. yield
  88. except BadParameter as e:
  89. if e.ctx is None:
  90. e.ctx = ctx
  91. if param is not None and e.param is None:
  92. e.param = param
  93. raise
  94. except UsageError as e:
  95. if e.ctx is None:
  96. e.ctx = ctx
  97. raise
  98. def iter_params_for_processing(
  99. invocation_order: t.Sequence["Parameter"],
  100. declaration_order: t.Sequence["Parameter"],
  101. ) -> t.List["Parameter"]:
  102. """Given a sequence of parameters in the order as should be considered
  103. for processing and an iterable of parameters that exist, this returns
  104. a list in the correct order as they should be processed.
  105. """
  106. def sort_key(item: "Parameter") -> t.Tuple[bool, float]:
  107. try:
  108. idx: float = invocation_order.index(item)
  109. except ValueError:
  110. idx = float("inf")
  111. return not item.is_eager, idx
  112. return sorted(declaration_order, key=sort_key)
  113. class ParameterSource(enum.Enum):
  114. """This is an :class:`~enum.Enum` that indicates the source of a
  115. parameter's value.
  116. Use :meth:`click.Context.get_parameter_source` to get the
  117. source for a parameter by name.
  118. .. versionchanged:: 8.0
  119. Use :class:`~enum.Enum` and drop the ``validate`` method.
  120. .. versionchanged:: 8.0
  121. Added the ``PROMPT`` value.
  122. """
  123. COMMANDLINE = enum.auto()
  124. """The value was provided by the command line args."""
  125. ENVIRONMENT = enum.auto()
  126. """The value was provided with an environment variable."""
  127. DEFAULT = enum.auto()
  128. """Used the default specified by the parameter."""
  129. DEFAULT_MAP = enum.auto()
  130. """Used a default provided by :attr:`Context.default_map`."""
  131. PROMPT = enum.auto()
  132. """Used a prompt to confirm a default or provide a value."""
  133. class Context:
  134. """The context is a special internal object that holds state relevant
  135. for the script execution at every single level. It's normally invisible
  136. to commands unless they opt-in to getting access to it.
  137. The context is useful as it can pass internal objects around and can
  138. control special execution features such as reading data from
  139. environment variables.
  140. A context can be used as context manager in which case it will call
  141. :meth:`close` on teardown.
  142. :param command: the command class for this context.
  143. :param parent: the parent context.
  144. :param info_name: the info name for this invocation. Generally this
  145. is the most descriptive name for the script or
  146. command. For the toplevel script it is usually
  147. the name of the script, for commands below it it's
  148. the name of the script.
  149. :param obj: an arbitrary object of user data.
  150. :param auto_envvar_prefix: the prefix to use for automatic environment
  151. variables. If this is `None` then reading
  152. from environment variables is disabled. This
  153. does not affect manually set environment
  154. variables which are always read.
  155. :param default_map: a dictionary (like object) with default values
  156. for parameters.
  157. :param terminal_width: the width of the terminal. The default is
  158. inherit from parent context. If no context
  159. defines the terminal width then auto
  160. detection will be applied.
  161. :param max_content_width: the maximum width for content rendered by
  162. Click (this currently only affects help
  163. pages). This defaults to 80 characters if
  164. not overridden. In other words: even if the
  165. terminal is larger than that, Click will not
  166. format things wider than 80 characters by
  167. default. In addition to that, formatters might
  168. add some safety mapping on the right.
  169. :param resilient_parsing: if this flag is enabled then Click will
  170. parse without any interactivity or callback
  171. invocation. Default values will also be
  172. ignored. This is useful for implementing
  173. things such as completion support.
  174. :param allow_extra_args: if this is set to `True` then extra arguments
  175. at the end will not raise an error and will be
  176. kept on the context. The default is to inherit
  177. from the command.
  178. :param allow_interspersed_args: if this is set to `False` then options
  179. and arguments cannot be mixed. The
  180. default is to inherit from the command.
  181. :param ignore_unknown_options: instructs click to ignore options it does
  182. not know and keeps them for later
  183. processing.
  184. :param help_option_names: optionally a list of strings that define how
  185. the default help parameter is named. The
  186. default is ``['--help']``.
  187. :param token_normalize_func: an optional function that is used to
  188. normalize tokens (options, choices,
  189. etc.). This for instance can be used to
  190. implement case insensitive behavior.
  191. :param color: controls if the terminal supports ANSI colors or not. The
  192. default is autodetection. This is only needed if ANSI
  193. codes are used in texts that Click prints which is by
  194. default not the case. This for instance would affect
  195. help output.
  196. :param show_default: Show the default value for commands. If this
  197. value is not set, it defaults to the value from the parent
  198. context. ``Command.show_default`` overrides this default for the
  199. specific command.
  200. .. versionchanged:: 8.1
  201. The ``show_default`` parameter is overridden by
  202. ``Command.show_default``, instead of the other way around.
  203. .. versionchanged:: 8.0
  204. The ``show_default`` parameter defaults to the value from the
  205. parent context.
  206. .. versionchanged:: 7.1
  207. Added the ``show_default`` parameter.
  208. .. versionchanged:: 4.0
  209. Added the ``color``, ``ignore_unknown_options``, and
  210. ``max_content_width`` parameters.
  211. .. versionchanged:: 3.0
  212. Added the ``allow_extra_args`` and ``allow_interspersed_args``
  213. parameters.
  214. .. versionchanged:: 2.0
  215. Added the ``resilient_parsing``, ``help_option_names``, and
  216. ``token_normalize_func`` parameters.
  217. """
  218. #: The formatter class to create with :meth:`make_formatter`.
  219. #:
  220. #: .. versionadded:: 8.0
  221. formatter_class: t.Type["HelpFormatter"] = HelpFormatter
  222. def __init__(
  223. self,
  224. command: "Command",
  225. parent: t.Optional["Context"] = None,
  226. info_name: t.Optional[str] = None,
  227. obj: t.Optional[t.Any] = None,
  228. auto_envvar_prefix: t.Optional[str] = None,
  229. default_map: t.Optional[t.MutableMapping[str, t.Any]] = None,
  230. terminal_width: t.Optional[int] = None,
  231. max_content_width: t.Optional[int] = None,
  232. resilient_parsing: bool = False,
  233. allow_extra_args: t.Optional[bool] = None,
  234. allow_interspersed_args: t.Optional[bool] = None,
  235. ignore_unknown_options: t.Optional[bool] = None,
  236. help_option_names: t.Optional[t.List[str]] = None,
  237. token_normalize_func: t.Optional[t.Callable[[str], str]] = None,
  238. color: t.Optional[bool] = None,
  239. show_default: t.Optional[bool] = None,
  240. ) -> None:
  241. #: the parent context or `None` if none exists.
  242. self.parent = parent
  243. #: the :class:`Command` for this context.
  244. self.command = command
  245. #: the descriptive information name
  246. self.info_name = info_name
  247. #: Map of parameter names to their parsed values. Parameters
  248. #: with ``expose_value=False`` are not stored.
  249. self.params: t.Dict[str, t.Any] = {}
  250. #: the leftover arguments.
  251. self.args: t.List[str] = []
  252. #: protected arguments. These are arguments that are prepended
  253. #: to `args` when certain parsing scenarios are encountered but
  254. #: must be never propagated to another arguments. This is used
  255. #: to implement nested parsing.
  256. self.protected_args: t.List[str] = []
  257. #: the collected prefixes of the command's options.
  258. self._opt_prefixes: t.Set[str] = set(parent._opt_prefixes) if parent else set()
  259. if obj is None and parent is not None:
  260. obj = parent.obj
  261. #: the user object stored.
  262. self.obj: t.Any = obj
  263. self._meta: t.Dict[str, t.Any] = getattr(parent, "meta", {})
  264. #: A dictionary (-like object) with defaults for parameters.
  265. if (
  266. default_map is None
  267. and info_name is not None
  268. and parent is not None
  269. and parent.default_map is not None
  270. ):
  271. default_map = parent.default_map.get(info_name)
  272. self.default_map: t.Optional[t.MutableMapping[str, t.Any]] = default_map
  273. #: This flag indicates if a subcommand is going to be executed. A
  274. #: group callback can use this information to figure out if it's
  275. #: being executed directly or because the execution flow passes
  276. #: onwards to a subcommand. By default it's None, but it can be
  277. #: the name of the subcommand to execute.
  278. #:
  279. #: If chaining is enabled this will be set to ``'*'`` in case
  280. #: any commands are executed. It is however not possible to
  281. #: figure out which ones. If you require this knowledge you
  282. #: should use a :func:`result_callback`.
  283. self.invoked_subcommand: t.Optional[str] = None
  284. if terminal_width is None and parent is not None:
  285. terminal_width = parent.terminal_width
  286. #: The width of the terminal (None is autodetection).
  287. self.terminal_width: t.Optional[int] = terminal_width
  288. if max_content_width is None and parent is not None:
  289. max_content_width = parent.max_content_width
  290. #: The maximum width of formatted content (None implies a sensible
  291. #: default which is 80 for most things).
  292. self.max_content_width: t.Optional[int] = max_content_width
  293. if allow_extra_args is None:
  294. allow_extra_args = command.allow_extra_args
  295. #: Indicates if the context allows extra args or if it should
  296. #: fail on parsing.
  297. #:
  298. #: .. versionadded:: 3.0
  299. self.allow_extra_args = allow_extra_args
  300. if allow_interspersed_args is None:
  301. allow_interspersed_args = command.allow_interspersed_args
  302. #: Indicates if the context allows mixing of arguments and
  303. #: options or not.
  304. #:
  305. #: .. versionadded:: 3.0
  306. self.allow_interspersed_args: bool = allow_interspersed_args
  307. if ignore_unknown_options is None:
  308. ignore_unknown_options = command.ignore_unknown_options
  309. #: Instructs click to ignore options that a command does not
  310. #: understand and will store it on the context for later
  311. #: processing. This is primarily useful for situations where you
  312. #: want to call into external programs. Generally this pattern is
  313. #: strongly discouraged because it's not possibly to losslessly
  314. #: forward all arguments.
  315. #:
  316. #: .. versionadded:: 4.0
  317. self.ignore_unknown_options: bool = ignore_unknown_options
  318. if help_option_names is None:
  319. if parent is not None:
  320. help_option_names = parent.help_option_names
  321. else:
  322. help_option_names = ["--help"]
  323. #: The names for the help options.
  324. self.help_option_names: t.List[str] = help_option_names
  325. if token_normalize_func is None and parent is not None:
  326. token_normalize_func = parent.token_normalize_func
  327. #: An optional normalization function for tokens. This is
  328. #: options, choices, commands etc.
  329. self.token_normalize_func: t.Optional[
  330. t.Callable[[str], str]
  331. ] = token_normalize_func
  332. #: Indicates if resilient parsing is enabled. In that case Click
  333. #: will do its best to not cause any failures and default values
  334. #: will be ignored. Useful for completion.
  335. self.resilient_parsing: bool = resilient_parsing
  336. # If there is no envvar prefix yet, but the parent has one and
  337. # the command on this level has a name, we can expand the envvar
  338. # prefix automatically.
  339. if auto_envvar_prefix is None:
  340. if (
  341. parent is not None
  342. and parent.auto_envvar_prefix is not None
  343. and self.info_name is not None
  344. ):
  345. auto_envvar_prefix = (
  346. f"{parent.auto_envvar_prefix}_{self.info_name.upper()}"
  347. )
  348. else:
  349. auto_envvar_prefix = auto_envvar_prefix.upper()
  350. if auto_envvar_prefix is not None:
  351. auto_envvar_prefix = auto_envvar_prefix.replace("-", "_")
  352. self.auto_envvar_prefix: t.Optional[str] = auto_envvar_prefix
  353. if color is None and parent is not None:
  354. color = parent.color
  355. #: Controls if styling output is wanted or not.
  356. self.color: t.Optional[bool] = color
  357. if show_default is None and parent is not None:
  358. show_default = parent.show_default
  359. #: Show option default values when formatting help text.
  360. self.show_default: t.Optional[bool] = show_default
  361. self._close_callbacks: t.List[t.Callable[[], t.Any]] = []
  362. self._depth = 0
  363. self._parameter_source: t.Dict[str, ParameterSource] = {}
  364. self._exit_stack = ExitStack()
  365. def to_info_dict(self) -> t.Dict[str, t.Any]:
  366. """Gather information that could be useful for a tool generating
  367. user-facing documentation. This traverses the entire CLI
  368. structure.
  369. .. code-block:: python
  370. with Context(cli) as ctx:
  371. info = ctx.to_info_dict()
  372. .. versionadded:: 8.0
  373. """
  374. return {
  375. "command": self.command.to_info_dict(self),
  376. "info_name": self.info_name,
  377. "allow_extra_args": self.allow_extra_args,
  378. "allow_interspersed_args": self.allow_interspersed_args,
  379. "ignore_unknown_options": self.ignore_unknown_options,
  380. "auto_envvar_prefix": self.auto_envvar_prefix,
  381. }
  382. def __enter__(self) -> "Context":
  383. self._depth += 1
  384. push_context(self)
  385. return self
  386. def __exit__(
  387. self,
  388. exc_type: t.Optional[t.Type[BaseException]],
  389. exc_value: t.Optional[BaseException],
  390. tb: t.Optional[TracebackType],
  391. ) -> None:
  392. self._depth -= 1
  393. if self._depth == 0:
  394. self.close()
  395. pop_context()
  396. @contextmanager
  397. def scope(self, cleanup: bool = True) -> t.Iterator["Context"]:
  398. """This helper method can be used with the context object to promote
  399. it to the current thread local (see :func:`get_current_context`).
  400. The default behavior of this is to invoke the cleanup functions which
  401. can be disabled by setting `cleanup` to `False`. The cleanup
  402. functions are typically used for things such as closing file handles.
  403. If the cleanup is intended the context object can also be directly
  404. used as a context manager.
  405. Example usage::
  406. with ctx.scope():
  407. assert get_current_context() is ctx
  408. This is equivalent::
  409. with ctx:
  410. assert get_current_context() is ctx
  411. .. versionadded:: 5.0
  412. :param cleanup: controls if the cleanup functions should be run or
  413. not. The default is to run these functions. In
  414. some situations the context only wants to be
  415. temporarily pushed in which case this can be disabled.
  416. Nested pushes automatically defer the cleanup.
  417. """
  418. if not cleanup:
  419. self._depth += 1
  420. try:
  421. with self as rv:
  422. yield rv
  423. finally:
  424. if not cleanup:
  425. self._depth -= 1
  426. @property
  427. def meta(self) -> t.Dict[str, t.Any]:
  428. """This is a dictionary which is shared with all the contexts
  429. that are nested. It exists so that click utilities can store some
  430. state here if they need to. It is however the responsibility of
  431. that code to manage this dictionary well.
  432. The keys are supposed to be unique dotted strings. For instance
  433. module paths are a good choice for it. What is stored in there is
  434. irrelevant for the operation of click. However what is important is
  435. that code that places data here adheres to the general semantics of
  436. the system.
  437. Example usage::
  438. LANG_KEY = f'{__name__}.lang'
  439. def set_language(value):
  440. ctx = get_current_context()
  441. ctx.meta[LANG_KEY] = value
  442. def get_language():
  443. return get_current_context().meta.get(LANG_KEY, 'en_US')
  444. .. versionadded:: 5.0
  445. """
  446. return self._meta
  447. def make_formatter(self) -> HelpFormatter:
  448. """Creates the :class:`~click.HelpFormatter` for the help and
  449. usage output.
  450. To quickly customize the formatter class used without overriding
  451. this method, set the :attr:`formatter_class` attribute.
  452. .. versionchanged:: 8.0
  453. Added the :attr:`formatter_class` attribute.
  454. """
  455. return self.formatter_class(
  456. width=self.terminal_width, max_width=self.max_content_width
  457. )
  458. def with_resource(self, context_manager: t.ContextManager[V]) -> V:
  459. """Register a resource as if it were used in a ``with``
  460. statement. The resource will be cleaned up when the context is
  461. popped.
  462. Uses :meth:`contextlib.ExitStack.enter_context`. It calls the
  463. resource's ``__enter__()`` method and returns the result. When
  464. the context is popped, it closes the stack, which calls the
  465. resource's ``__exit__()`` method.
  466. To register a cleanup function for something that isn't a
  467. context manager, use :meth:`call_on_close`. Or use something
  468. from :mod:`contextlib` to turn it into a context manager first.
  469. .. code-block:: python
  470. @click.group()
  471. @click.option("--name")
  472. @click.pass_context
  473. def cli(ctx):
  474. ctx.obj = ctx.with_resource(connect_db(name))
  475. :param context_manager: The context manager to enter.
  476. :return: Whatever ``context_manager.__enter__()`` returns.
  477. .. versionadded:: 8.0
  478. """
  479. return self._exit_stack.enter_context(context_manager)
  480. def call_on_close(self, f: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]:
  481. """Register a function to be called when the context tears down.
  482. This can be used to close resources opened during the script
  483. execution. Resources that support Python's context manager
  484. protocol which would be used in a ``with`` statement should be
  485. registered with :meth:`with_resource` instead.
  486. :param f: The function to execute on teardown.
  487. """
  488. return self._exit_stack.callback(f)
  489. def close(self) -> None:
  490. """Invoke all close callbacks registered with
  491. :meth:`call_on_close`, and exit all context managers entered
  492. with :meth:`with_resource`.
  493. """
  494. self._exit_stack.close()
  495. # In case the context is reused, create a new exit stack.
  496. self._exit_stack = ExitStack()
  497. @property
  498. def command_path(self) -> str:
  499. """The computed command path. This is used for the ``usage``
  500. information on the help page. It's automatically created by
  501. combining the info names of the chain of contexts to the root.
  502. """
  503. rv = ""
  504. if self.info_name is not None:
  505. rv = self.info_name
  506. if self.parent is not None:
  507. parent_command_path = [self.parent.command_path]
  508. if isinstance(self.parent.command, Command):
  509. for param in self.parent.command.get_params(self):
  510. parent_command_path.extend(param.get_usage_pieces(self))
  511. rv = f"{' '.join(parent_command_path)} {rv}"
  512. return rv.lstrip()
  513. def find_root(self) -> "Context":
  514. """Finds the outermost context."""
  515. node = self
  516. while node.parent is not None:
  517. node = node.parent
  518. return node
  519. def find_object(self, object_type: t.Type[V]) -> t.Optional[V]:
  520. """Finds the closest object of a given type."""
  521. node: t.Optional["Context"] = self
  522. while node is not None:
  523. if isinstance(node.obj, object_type):
  524. return node.obj
  525. node = node.parent
  526. return None
  527. def ensure_object(self, object_type: t.Type[V]) -> V:
  528. """Like :meth:`find_object` but sets the innermost object to a
  529. new instance of `object_type` if it does not exist.
  530. """
  531. rv = self.find_object(object_type)
  532. if rv is None:
  533. self.obj = rv = object_type()
  534. return rv
  535. @t.overload
  536. def lookup_default(
  537. self, name: str, call: "te.Literal[True]" = True
  538. ) -> t.Optional[t.Any]:
  539. ...
  540. @t.overload
  541. def lookup_default(
  542. self, name: str, call: "te.Literal[False]" = ...
  543. ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]:
  544. ...
  545. def lookup_default(self, name: str, call: bool = True) -> t.Optional[t.Any]:
  546. """Get the default for a parameter from :attr:`default_map`.
  547. :param name: Name of the parameter.
  548. :param call: If the default is a callable, call it. Disable to
  549. return the callable instead.
  550. .. versionchanged:: 8.0
  551. Added the ``call`` parameter.
  552. """
  553. if self.default_map is not None:
  554. value = self.default_map.get(name)
  555. if call and callable(value):
  556. return value()
  557. return value
  558. return None
  559. def fail(self, message: str) -> "te.NoReturn":
  560. """Aborts the execution of the program with a specific error
  561. message.
  562. :param message: the error message to fail with.
  563. """
  564. raise UsageError(message, self)
  565. def abort(self) -> "te.NoReturn":
  566. """Aborts the script."""
  567. raise Abort()
  568. def exit(self, code: int = 0) -> "te.NoReturn":
  569. """Exits the application with a given exit code."""
  570. raise Exit(code)
  571. def get_usage(self) -> str:
  572. """Helper method to get formatted usage string for the current
  573. context and command.
  574. """
  575. return self.command.get_usage(self)
  576. def get_help(self) -> str:
  577. """Helper method to get formatted help page for the current
  578. context and command.
  579. """
  580. return self.command.get_help(self)
  581. def _make_sub_context(self, command: "Command") -> "Context":
  582. """Create a new context of the same type as this context, but
  583. for a new command.
  584. :meta private:
  585. """
  586. return type(self)(command, info_name=command.name, parent=self)
  587. @t.overload
  588. def invoke(
  589. __self, # noqa: B902
  590. __callback: "t.Callable[..., V]",
  591. *args: t.Any,
  592. **kwargs: t.Any,
  593. ) -> V:
  594. ...
  595. @t.overload
  596. def invoke(
  597. __self, # noqa: B902
  598. __callback: "Command",
  599. *args: t.Any,
  600. **kwargs: t.Any,
  601. ) -> t.Any:
  602. ...
  603. def invoke(
  604. __self, # noqa: B902
  605. __callback: t.Union["Command", "t.Callable[..., V]"],
  606. *args: t.Any,
  607. **kwargs: t.Any,
  608. ) -> t.Union[t.Any, V]:
  609. """Invokes a command callback in exactly the way it expects. There
  610. are two ways to invoke this method:
  611. 1. the first argument can be a callback and all other arguments and
  612. keyword arguments are forwarded directly to the function.
  613. 2. the first argument is a click command object. In that case all
  614. arguments are forwarded as well but proper click parameters
  615. (options and click arguments) must be keyword arguments and Click
  616. will fill in defaults.
  617. Note that before Click 3.2 keyword arguments were not properly filled
  618. in against the intention of this code and no context was created. For
  619. more information about this change and why it was done in a bugfix
  620. release see :ref:`upgrade-to-3.2`.
  621. .. versionchanged:: 8.0
  622. All ``kwargs`` are tracked in :attr:`params` so they will be
  623. passed if :meth:`forward` is called at multiple levels.
  624. """
  625. if isinstance(__callback, Command):
  626. other_cmd = __callback
  627. if other_cmd.callback is None:
  628. raise TypeError(
  629. "The given command does not have a callback that can be invoked."
  630. )
  631. else:
  632. __callback = t.cast("t.Callable[..., V]", other_cmd.callback)
  633. ctx = __self._make_sub_context(other_cmd)
  634. for param in other_cmd.params:
  635. if param.name not in kwargs and param.expose_value:
  636. kwargs[param.name] = param.type_cast_value( # type: ignore
  637. ctx, param.get_default(ctx)
  638. )
  639. # Track all kwargs as params, so that forward() will pass
  640. # them on in subsequent calls.
  641. ctx.params.update(kwargs)
  642. else:
  643. ctx = __self
  644. with augment_usage_errors(__self):
  645. with ctx:
  646. return __callback(*args, **kwargs)
  647. def forward(
  648. __self, __cmd: "Command", *args: t.Any, **kwargs: t.Any # noqa: B902
  649. ) -> t.Any:
  650. """Similar to :meth:`invoke` but fills in default keyword
  651. arguments from the current context if the other command expects
  652. it. This cannot invoke callbacks directly, only other commands.
  653. .. versionchanged:: 8.0
  654. All ``kwargs`` are tracked in :attr:`params` so they will be
  655. passed if ``forward`` is called at multiple levels.
  656. """
  657. # Can only forward to other commands, not direct callbacks.
  658. if not isinstance(__cmd, Command):
  659. raise TypeError("Callback is not a command.")
  660. for param in __self.params:
  661. if param not in kwargs:
  662. kwargs[param] = __self.params[param]
  663. return __self.invoke(__cmd, *args, **kwargs)
  664. def set_parameter_source(self, name: str, source: ParameterSource) -> None:
  665. """Set the source of a parameter. This indicates the location
  666. from which the value of the parameter was obtained.
  667. :param name: The name of the parameter.
  668. :param source: A member of :class:`~click.core.ParameterSource`.
  669. """
  670. self._parameter_source[name] = source
  671. def get_parameter_source(self, name: str) -> t.Optional[ParameterSource]:
  672. """Get the source of a parameter. This indicates the location
  673. from which the value of the parameter was obtained.
  674. This can be useful for determining when a user specified a value
  675. on the command line that is the same as the default value. It
  676. will be :attr:`~click.core.ParameterSource.DEFAULT` only if the
  677. value was actually taken from the default.
  678. :param name: The name of the parameter.
  679. :rtype: ParameterSource
  680. .. versionchanged:: 8.0
  681. Returns ``None`` if the parameter was not provided from any
  682. source.
  683. """
  684. return self._parameter_source.get(name)
  685. class BaseCommand:
  686. """The base command implements the minimal API contract of commands.
  687. Most code will never use this as it does not implement a lot of useful
  688. functionality but it can act as the direct subclass of alternative
  689. parsing methods that do not depend on the Click parser.
  690. For instance, this can be used to bridge Click and other systems like
  691. argparse or docopt.
  692. Because base commands do not implement a lot of the API that other
  693. parts of Click take for granted, they are not supported for all
  694. operations. For instance, they cannot be used with the decorators
  695. usually and they have no built-in callback system.
  696. .. versionchanged:: 2.0
  697. Added the `context_settings` parameter.
  698. :param name: the name of the command to use unless a group overrides it.
  699. :param context_settings: an optional dictionary with defaults that are
  700. passed to the context object.
  701. """
  702. #: The context class to create with :meth:`make_context`.
  703. #:
  704. #: .. versionadded:: 8.0
  705. context_class: t.Type[Context] = Context
  706. #: the default for the :attr:`Context.allow_extra_args` flag.
  707. allow_extra_args = False
  708. #: the default for the :attr:`Context.allow_interspersed_args` flag.
  709. allow_interspersed_args = True
  710. #: the default for the :attr:`Context.ignore_unknown_options` flag.
  711. ignore_unknown_options = False
  712. def __init__(
  713. self,
  714. name: t.Optional[str],
  715. context_settings: t.Optional[t.MutableMapping[str, t.Any]] = None,
  716. ) -> None:
  717. #: the name the command thinks it has. Upon registering a command
  718. #: on a :class:`Group` the group will default the command name
  719. #: with this information. You should instead use the
  720. #: :class:`Context`\'s :attr:`~Context.info_name` attribute.
  721. self.name = name
  722. if context_settings is None:
  723. context_settings = {}
  724. #: an optional dictionary with defaults passed to the context.
  725. self.context_settings: t.MutableMapping[str, t.Any] = context_settings
  726. def to_info_dict(self, ctx: Context) -> t.Dict[str, t.Any]:
  727. """Gather information that could be useful for a tool generating
  728. user-facing documentation. This traverses the entire structure
  729. below this command.
  730. Use :meth:`click.Context.to_info_dict` to traverse the entire
  731. CLI structure.
  732. :param ctx: A :class:`Context` representing this command.
  733. .. versionadded:: 8.0
  734. """
  735. return {"name": self.name}
  736. def __repr__(self) -> str:
  737. return f"<{self.__class__.__name__} {self.name}>"
  738. def get_usage(self, ctx: Context) -> str:
  739. raise NotImplementedError("Base commands cannot get usage")
  740. def get_help(self, ctx: Context) -> str:
  741. raise NotImplementedError("Base commands cannot get help")
  742. def make_context(
  743. self,
  744. info_name: t.Optional[str],
  745. args: t.List[str],
  746. parent: t.Optional[Context] = None,
  747. **extra: t.Any,
  748. ) -> Context:
  749. """This function when given an info name and arguments will kick
  750. off the parsing and create a new :class:`Context`. It does not
  751. invoke the actual command callback though.
  752. To quickly customize the context class used without overriding
  753. this method, set the :attr:`context_class` attribute.
  754. :param info_name: the info name for this invocation. Generally this
  755. is the most descriptive name for the script or
  756. command. For the toplevel script it's usually
  757. the name of the script, for commands below it's
  758. the name of the command.
  759. :param args: the arguments to parse as list of strings.
  760. :param parent: the parent context if available.
  761. :param extra: extra keyword arguments forwarded to the context
  762. constructor.
  763. .. versionchanged:: 8.0
  764. Added the :attr:`context_class` attribute.
  765. """
  766. for key, value in self.context_settings.items():
  767. if key not in extra:
  768. extra[key] = value
  769. ctx = self.context_class(
  770. self, info_name=info_name, parent=parent, **extra # type: ignore
  771. )
  772. with ctx.scope(cleanup=False):
  773. self.parse_args(ctx, args)
  774. return ctx
  775. def parse_args(self, ctx: Context, args: t.List[str]) -> t.List[str]:
  776. """Given a context and a list of arguments this creates the parser
  777. and parses the arguments, then modifies the context as necessary.
  778. This is automatically invoked by :meth:`make_context`.
  779. """
  780. raise NotImplementedError("Base commands do not know how to parse arguments.")
  781. def invoke(self, ctx: Context) -> t.Any:
  782. """Given a context, this invokes the command. The default
  783. implementation is raising a not implemented error.
  784. """
  785. raise NotImplementedError("Base commands are not invocable by default")
  786. def shell_complete(self, ctx: Context, incomplete: str) -> t.List["CompletionItem"]:
  787. """Return a list of completions for the incomplete value. Looks
  788. at the names of chained multi-commands.
  789. Any command could be part of a chained multi-command, so sibling
  790. commands are valid at any point during command completion. Other
  791. command classes will return more completions.
  792. :param ctx: Invocation context for this command.
  793. :param incomplete: Value being completed. May be empty.
  794. .. versionadded:: 8.0
  795. """
  796. from click.shell_completion import CompletionItem
  797. results: t.List["CompletionItem"] = []
  798. while ctx.parent is not None:
  799. ctx = ctx.parent
  800. if isinstance(ctx.command, MultiCommand) and ctx.command.chain:
  801. results.extend(
  802. CompletionItem(name, help=command.get_short_help_str())
  803. for name, command in _complete_visible_commands(ctx, incomplete)
  804. if name not in ctx.protected_args
  805. )
  806. return results
  807. @t.overload
  808. def main(
  809. self,
  810. args: t.Optional[t.Sequence[str]] = None,
  811. prog_name: t.Optional[str] = None,
  812. complete_var: t.Optional[str] = None,
  813. standalone_mode: "te.Literal[True]" = True,
  814. **extra: t.Any,
  815. ) -> "te.NoReturn":
  816. ...
  817. @t.overload
  818. def main(
  819. self,
  820. args: t.Optional[t.Sequence[str]] = None,
  821. prog_name: t.Optional[str] = None,
  822. complete_var: t.Optional[str] = None,
  823. standalone_mode: bool = ...,
  824. **extra: t.Any,
  825. ) -> t.Any:
  826. ...
  827. def main(
  828. self,
  829. args: t.Optional[t.Sequence[str]] = None,
  830. prog_name: t.Optional[str] = None,
  831. complete_var: t.Optional[str] = None,
  832. standalone_mode: bool = True,
  833. windows_expand_args: bool = True,
  834. **extra: t.Any,
  835. ) -> t.Any:
  836. """This is the way to invoke a script with all the bells and
  837. whistles as a command line application. This will always terminate
  838. the application after a call. If this is not wanted, ``SystemExit``
  839. needs to be caught.
  840. This method is also available by directly calling the instance of
  841. a :class:`Command`.
  842. :param args: the arguments that should be used for parsing. If not
  843. provided, ``sys.argv[1:]`` is used.
  844. :param prog_name: the program name that should be used. By default
  845. the program name is constructed by taking the file
  846. name from ``sys.argv[0]``.
  847. :param complete_var: the environment variable that controls the
  848. bash completion support. The default is
  849. ``"_<prog_name>_COMPLETE"`` with prog_name in
  850. uppercase.
  851. :param standalone_mode: the default behavior is to invoke the script
  852. in standalone mode. Click will then
  853. handle exceptions and convert them into
  854. error messages and the function will never
  855. return but shut down the interpreter. If
  856. this is set to `False` they will be
  857. propagated to the caller and the return
  858. value of this function is the return value
  859. of :meth:`invoke`.
  860. :param windows_expand_args: Expand glob patterns, user dir, and
  861. env vars in command line args on Windows.
  862. :param extra: extra keyword arguments are forwarded to the context
  863. constructor. See :class:`Context` for more information.
  864. .. versionchanged:: 8.0.1
  865. Added the ``windows_expand_args`` parameter to allow
  866. disabling command line arg expansion on Windows.
  867. .. versionchanged:: 8.0
  868. When taking arguments from ``sys.argv`` on Windows, glob
  869. patterns, user dir, and env vars are expanded.
  870. .. versionchanged:: 3.0
  871. Added the ``standalone_mode`` parameter.
  872. """
  873. if args is None:
  874. args = sys.argv[1:]
  875. if os.name == "nt" and windows_expand_args:
  876. args = _expand_args(args)
  877. else:
  878. args = list(args)
  879. if prog_name is None:
  880. prog_name = _detect_program_name()
  881. # Process shell completion requests and exit early.
  882. self._main_shell_completion(extra, prog_name, complete_var)
  883. try:
  884. try:
  885. with self.make_context(prog_name, args, **extra) as ctx:
  886. rv = self.invoke(ctx)
  887. if not standalone_mode:
  888. return rv
  889. # it's not safe to `ctx.exit(rv)` here!
  890. # note that `rv` may actually contain data like "1" which
  891. # has obvious effects
  892. # more subtle case: `rv=[None, None]` can come out of
  893. # chained commands which all returned `None` -- so it's not
  894. # even always obvious that `rv` indicates success/failure
  895. # by its truthiness/falsiness
  896. ctx.exit()
  897. except (EOFError, KeyboardInterrupt) as e:
  898. echo(file=sys.stderr)
  899. raise Abort() from e
  900. except ClickException as e:
  901. if not standalone_mode:
  902. raise
  903. e.show()
  904. sys.exit(e.exit_code)
  905. except OSError as e:
  906. if e.errno == errno.EPIPE:
  907. sys.stdout = t.cast(t.TextIO, PacifyFlushWrapper(sys.stdout))
  908. sys.stderr = t.cast(t.TextIO, PacifyFlushWrapper(sys.stderr))
  909. sys.exit(1)
  910. else:
  911. raise
  912. except Exit as e:
  913. if standalone_mode:
  914. sys.exit(e.exit_code)
  915. else:
  916. # in non-standalone mode, return the exit code
  917. # note that this is only reached if `self.invoke` above raises
  918. # an Exit explicitly -- thus bypassing the check there which
  919. # would return its result
  920. # the results of non-standalone execution may therefore be
  921. # somewhat ambiguous: if there are codepaths which lead to
  922. # `ctx.exit(1)` and to `return 1`, the caller won't be able to
  923. # tell the difference between the two
  924. return e.exit_code
  925. except Abort:
  926. if not standalone_mode:
  927. raise
  928. echo(_("Aborted!"), file=sys.stderr)
  929. sys.exit(1)
  930. def _main_shell_completion(
  931. self,
  932. ctx_args: t.MutableMapping[str, t.Any],
  933. prog_name: str,
  934. complete_var: t.Optional[str] = None,
  935. ) -> None:
  936. """Check if the shell is asking for tab completion, process
  937. that, then exit early. Called from :meth:`main` before the
  938. program is invoked.
  939. :param prog_name: Name of the executable in the shell.
  940. :param complete_var: Name of the environment variable that holds
  941. the completion instruction. Defaults to
  942. ``_{PROG_NAME}_COMPLETE``.
  943. .. versionchanged:: 8.2.0
  944. Dots (``.``) in ``prog_name`` are replaced with underscores (``_``).
  945. """
  946. if complete_var is None:
  947. complete_name = prog_name.replace("-", "_").replace(".", "_")
  948. complete_var = f"_{complete_name}_COMPLETE".upper()
  949. instruction = os.environ.get(complete_var)
  950. if not instruction:
  951. return
  952. from .shell_completion import shell_complete
  953. rv = shell_complete(self, ctx_args, prog_name, complete_var, instruction)
  954. sys.exit(rv)
  955. def __call__(self, *args: t.Any, **kwargs: t.Any) -> t.Any:
  956. """Alias for :meth:`main`."""
  957. return self.main(*args, **kwargs)
  958. class Command(BaseCommand):
  959. """Commands are the basic building block of command line interfaces in
  960. Click. A basic command handles command line parsing and might dispatch
  961. more parsing to commands nested below it.
  962. :param name: the name of the command to use unless a group overrides it.
  963. :param context_settings: an optional dictionary with defaults that are
  964. passed to the context object.
  965. :param callback: the callback to invoke. This is optional.
  966. :param params: the parameters to register with this command. This can
  967. be either :class:`Option` or :class:`Argument` objects.
  968. :param help: the help string to use for this command.
  969. :param epilog: like the help string but it's printed at the end of the
  970. help page after everything else.
  971. :param short_help: the short help to use for this command. This is
  972. shown on the command listing of the parent command.
  973. :param add_help_option: by default each command registers a ``--help``
  974. option. This can be disabled by this parameter.
  975. :param no_args_is_help: this controls what happens if no arguments are
  976. provided. This option is disabled by default.
  977. If enabled this will add ``--help`` as argument
  978. if no arguments are passed
  979. :param hidden: hide this command from help outputs.
  980. :param deprecated: issues a message indicating that
  981. the command is deprecated.
  982. .. versionchanged:: 8.1
  983. ``help``, ``epilog``, and ``short_help`` are stored unprocessed,
  984. all formatting is done when outputting help text, not at init,
  985. and is done even if not using the ``@command`` decorator.
  986. .. versionchanged:: 8.0
  987. Added a ``repr`` showing the command name.
  988. .. versionchanged:: 7.1
  989. Added the ``no_args_is_help`` parameter.
  990. .. versionchanged:: 2.0
  991. Added the ``context_settings`` parameter.
  992. """
  993. def __init__(
  994. self,
  995. name: t.Optional[str],
  996. context_settings: t.Optional[t.MutableMapping[str, t.Any]] = None,
  997. callback: t.Optional[t.Callable[..., t.Any]] = None,
  998. params: t.Optional[t.List["Parameter"]] = None,
  999. help: t.Optional[str] = None,
  1000. epilog: t.Optional[str] = None,
  1001. short_help: t.Optional[str] = None,
  1002. options_metavar: t.Optional[str] = "[OPTIONS]",
  1003. add_help_option: bool = True,
  1004. no_args_is_help: bool = False,
  1005. hidden: bool = False,
  1006. deprecated: bool = False,
  1007. ) -> None:
  1008. super().__init__(name, context_settings)
  1009. #: the callback to execute when the command fires. This might be
  1010. #: `None` in which case nothing happens.
  1011. self.callback = callback
  1012. #: the list of parameters for this command in the order they
  1013. #: should show up in the help page and execute. Eager parameters
  1014. #: will automatically be handled before non eager ones.
  1015. self.params: t.List["Parameter"] = params or []
  1016. self.help = help
  1017. self.epilog = epilog
  1018. self.options_metavar = options_metavar
  1019. self.short_help = short_help
  1020. self.add_help_option = add_help_option
  1021. self.no_args_is_help = no_args_is_help
  1022. self.hidden = hidden
  1023. self.deprecated = deprecated
  1024. def to_info_dict(self, ctx: Context) -> t.Dict[str, t.Any]:
  1025. info_dict = super().to_info_dict(ctx)
  1026. info_dict.update(
  1027. params=[param.to_info_dict() for param in self.get_params(ctx)],
  1028. help=self.help,
  1029. epilog=self.epilog,
  1030. short_help=self.short_help,
  1031. hidden=self.hidden,
  1032. deprecated=self.deprecated,
  1033. )
  1034. return info_dict
  1035. def get_usage(self, ctx: Context) -> str:
  1036. """Formats the usage line into a string and returns it.
  1037. Calls :meth:`format_usage` internally.
  1038. """
  1039. formatter = ctx.make_formatter()
  1040. self.format_usage(ctx, formatter)
  1041. return formatter.getvalue().rstrip("\n")
  1042. def get_params(self, ctx: Context) -> t.List["Parameter"]:
  1043. rv = self.params
  1044. help_option = self.get_help_option(ctx)
  1045. if help_option is not None:
  1046. rv = [*rv, help_option]
  1047. return rv
  1048. def format_usage(self, ctx: Context, formatter: HelpFormatter) -> None:
  1049. """Writes the usage line into the formatter.
  1050. This is a low-level method called by :meth:`get_usage`.
  1051. """
  1052. pieces = self.collect_usage_pieces(ctx)
  1053. formatter.write_usage(ctx.command_path, " ".join(pieces))
  1054. def collect_usage_pieces(self, ctx: Context) -> t.List[str]:
  1055. """Returns all the pieces that go into the usage line and returns
  1056. it as a list of strings.
  1057. """
  1058. rv = [self.options_metavar] if self.options_metavar else []
  1059. for param in self.get_params(ctx):
  1060. rv.extend(param.get_usage_pieces(ctx))
  1061. return rv
  1062. def get_help_option_names(self, ctx: Context) -> t.List[str]:
  1063. """Returns the names for the help option."""
  1064. all_names = set(ctx.help_option_names)
  1065. for param in self.params:
  1066. all_names.difference_update(param.opts)
  1067. all_names.difference_update(param.secondary_opts)
  1068. return list(all_names)
  1069. def get_help_option(self, ctx: Context) -> t.Optional["Option"]:
  1070. """Returns the help option object."""
  1071. help_options = self.get_help_option_names(ctx)
  1072. if not help_options or not self.add_help_option:
  1073. return None
  1074. def show_help(ctx: Context, param: "Parameter", value: str) -> None:
  1075. if value and not ctx.resilient_parsing:
  1076. echo(ctx.get_help(), color=ctx.color)
  1077. ctx.exit()
  1078. return Option(
  1079. help_options,
  1080. is_flag=True,
  1081. is_eager=True,
  1082. expose_value=False,
  1083. callback=show_help,
  1084. help=_("Show this message and exit."),
  1085. )
  1086. def make_parser(self, ctx: Context) -> OptionParser:
  1087. """Creates the underlying option parser for this command."""
  1088. parser = OptionParser(ctx)
  1089. for param in self.get_params(ctx):
  1090. param.add_to_parser(parser, ctx)
  1091. return parser
  1092. def get_help(self, ctx: Context) -> str:
  1093. """Formats the help into a string and returns it.
  1094. Calls :meth:`format_help` internally.
  1095. """
  1096. formatter = ctx.make_formatter()
  1097. self.format_help(ctx, formatter)
  1098. return formatter.getvalue().rstrip("\n")
  1099. def get_short_help_str(self, limit: int = 45) -> str:
  1100. """Gets short help for the command or makes it by shortening the
  1101. long help string.
  1102. """
  1103. if self.short_help:
  1104. text = inspect.cleandoc(self.short_help)
  1105. elif self.help:
  1106. text = make_default_short_help(self.help, limit)
  1107. else:
  1108. text = ""
  1109. if self.deprecated:
  1110. text = _("(Deprecated) {text}").format(text=text)
  1111. return text.strip()
  1112. def format_help(self, ctx: Context, formatter: HelpFormatter) -> None:
  1113. """Writes the help into the formatter if it exists.
  1114. This is a low-level method called by :meth:`get_help`.
  1115. This calls the following methods:
  1116. - :meth:`format_usage`
  1117. - :meth:`format_help_text`
  1118. - :meth:`format_options`
  1119. - :meth:`format_epilog`
  1120. """
  1121. self.format_usage(ctx, formatter)
  1122. self.format_help_text(ctx, formatter)
  1123. self.format_options(ctx, formatter)
  1124. self.format_epilog(ctx, formatter)
  1125. def format_help_text(self, ctx: Context, formatter: HelpFormatter) -> None:
  1126. """Writes the help text to the formatter if it exists."""
  1127. if self.help is not None:
  1128. # truncate the help text to the first form feed
  1129. text = inspect.cleandoc(self.help).partition("\f")[0]
  1130. else:
  1131. text = ""
  1132. if self.deprecated:
  1133. text = _("(Deprecated) {text}").format(text=text)
  1134. if text:
  1135. formatter.write_paragraph()
  1136. with formatter.indentation():
  1137. formatter.write_text(text)
  1138. def format_options(self, ctx: Context, formatter: HelpFormatter) -> None:
  1139. """Writes all the options into the formatter if they exist."""
  1140. opts = []
  1141. for param in self.get_params(ctx):
  1142. rv = param.get_help_record(ctx)
  1143. if rv is not None:
  1144. opts.append(rv)
  1145. if opts:
  1146. with formatter.section(_("Options")):
  1147. formatter.write_dl(opts)
  1148. def format_epilog(self, ctx: Context, formatter: HelpFormatter) -> None:
  1149. """Writes the epilog into the formatter if it exists."""
  1150. if self.epilog:
  1151. epilog = inspect.cleandoc(self.epilog)
  1152. formatter.write_paragraph()
  1153. with formatter.indentation():
  1154. formatter.write_text(epilog)
  1155. def parse_args(self, ctx: Context, args: t.List[str]) -> t.List[str]:
  1156. if not args and self.no_args_is_help and not ctx.resilient_parsing:
  1157. echo(ctx.get_help(), color=ctx.color)
  1158. ctx.exit()
  1159. parser = self.make_parser(ctx)
  1160. opts, args, param_order = parser.parse_args(args=args)
  1161. for param in iter_params_for_processing(param_order, self.get_params(ctx)):
  1162. value, args = param.handle_parse_result(ctx, opts, args)
  1163. if args and not ctx.allow_extra_args and not ctx.resilient_parsing:
  1164. ctx.fail(
  1165. ngettext(
  1166. "Got unexpected extra argument ({args})",
  1167. "Got unexpected extra arguments ({args})",
  1168. len(args),
  1169. ).format(args=" ".join(map(str, args)))
  1170. )
  1171. ctx.args = args
  1172. ctx._opt_prefixes.update(parser._opt_prefixes)
  1173. return args
  1174. def invoke(self, ctx: Context) -> t.Any:
  1175. """Given a context, this invokes the attached callback (if it exists)
  1176. in the right way.
  1177. """
  1178. if self.deprecated:
  1179. message = _(
  1180. "DeprecationWarning: The command {name!r} is deprecated."
  1181. ).format(name=self.name)
  1182. echo(style(message, fg="red"), err=True)
  1183. if self.callback is not None:
  1184. return ctx.invoke(self.callback, **ctx.params)
  1185. def shell_complete(self, ctx: Context, incomplete: str) -> t.List["CompletionItem"]:
  1186. """Return a list of completions for the incomplete value. Looks
  1187. at the names of options and chained multi-commands.
  1188. :param ctx: Invocation context for this command.
  1189. :param incomplete: Value being completed. May be empty.
  1190. .. versionadded:: 8.0
  1191. """
  1192. from click.shell_completion import CompletionItem
  1193. results: t.List["CompletionItem"] = []
  1194. if incomplete and not incomplete[0].isalnum():
  1195. for param in self.get_params(ctx):
  1196. if (
  1197. not isinstance(param, Option)
  1198. or param.hidden
  1199. or (
  1200. not param.multiple
  1201. and ctx.get_parameter_source(param.name) # type: ignore
  1202. is ParameterSource.COMMANDLINE
  1203. )
  1204. ):
  1205. continue
  1206. results.extend(
  1207. CompletionItem(name, help=param.help)
  1208. for name in [*param.opts, *param.secondary_opts]
  1209. if name.startswith(incomplete)
  1210. )
  1211. results.extend(super().shell_complete(ctx, incomplete))
  1212. return results
  1213. class MultiCommand(Command):
  1214. """A multi command is the basic implementation of a command that
  1215. dispatches to subcommands. The most common version is the
  1216. :class:`Group`.
  1217. :param invoke_without_command: this controls how the multi command itself
  1218. is invoked. By default it's only invoked
  1219. if a subcommand is provided.
  1220. :param no_args_is_help: this controls what happens if no arguments are
  1221. provided. This option is enabled by default if
  1222. `invoke_without_command` is disabled or disabled
  1223. if it's enabled. If enabled this will add
  1224. ``--help`` as argument if no arguments are
  1225. passed.
  1226. :param subcommand_metavar: the string that is used in the documentation
  1227. to indicate the subcommand place.
  1228. :param chain: if this is set to `True` chaining of multiple subcommands
  1229. is enabled. This restricts the form of commands in that
  1230. they cannot have optional arguments but it allows
  1231. multiple commands to be chained together.
  1232. :param result_callback: The result callback to attach to this multi
  1233. command. This can be set or changed later with the
  1234. :meth:`result_callback` decorator.
  1235. :param attrs: Other command arguments described in :class:`Command`.
  1236. """
  1237. allow_extra_args = True
  1238. allow_interspersed_args = False
  1239. def __init__(
  1240. self,
  1241. name: t.Optional[str] = None,
  1242. invoke_without_command: bool = False,
  1243. no_args_is_help: t.Optional[bool] = None,
  1244. subcommand_metavar: t.Optional[str] = None,
  1245. chain: bool = False,
  1246. result_callback: t.Optional[t.Callable[..., t.Any]] = None,
  1247. **attrs: t.Any,
  1248. ) -> None:
  1249. super().__init__(name, **attrs)
  1250. if no_args_is_help is None:
  1251. no_args_is_help = not invoke_without_command
  1252. self.no_args_is_help = no_args_is_help
  1253. self.invoke_without_command = invoke_without_command
  1254. if subcommand_metavar is None:
  1255. if chain:
  1256. subcommand_metavar = "COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]..."
  1257. else:
  1258. subcommand_metavar = "COMMAND [ARGS]..."
  1259. self.subcommand_metavar = subcommand_metavar
  1260. self.chain = chain
  1261. # The result callback that is stored. This can be set or
  1262. # overridden with the :func:`result_callback` decorator.
  1263. self._result_callback = result_callback
  1264. if self.chain:
  1265. for param in self.params:
  1266. if isinstance(param, Argument) and not param.required:
  1267. raise RuntimeError(
  1268. "Multi commands in chain mode cannot have"
  1269. " optional arguments."
  1270. )
  1271. def to_info_dict(self, ctx: Context) -> t.Dict[str, t.Any]:
  1272. info_dict = super().to_info_dict(ctx)
  1273. commands = {}
  1274. for name in self.list_commands(ctx):
  1275. command = self.get_command(ctx, name)
  1276. if command is None:
  1277. continue
  1278. sub_ctx = ctx._make_sub_context(command)
  1279. with sub_ctx.scope(cleanup=False):
  1280. commands[name] = command.to_info_dict(sub_ctx)
  1281. info_dict.update(commands=commands, chain=self.chain)
  1282. return info_dict
  1283. def collect_usage_pieces(self, ctx: Context) -> t.List[str]:
  1284. rv = super().collect_usage_pieces(ctx)
  1285. rv.append(self.subcommand_metavar)
  1286. return rv
  1287. def format_options(self, ctx: Context, formatter: HelpFormatter) -> None:
  1288. super().format_options(ctx, formatter)
  1289. self.format_commands(ctx, formatter)
  1290. def result_callback(self, replace: bool = False) -> t.Callable[[F], F]:
  1291. """Adds a result callback to the command. By default if a
  1292. result callback is already registered this will chain them but
  1293. this can be disabled with the `replace` parameter. The result
  1294. callback is invoked with the return value of the subcommand
  1295. (or the list of return values from all subcommands if chaining
  1296. is enabled) as well as the parameters as they would be passed
  1297. to the main callback.
  1298. Example::
  1299. @click.group()
  1300. @click.option('-i', '--input', default=23)
  1301. def cli(input):
  1302. return 42
  1303. @cli.result_callback()
  1304. def process_result(result, input):
  1305. return result + input
  1306. :param replace: if set to `True` an already existing result
  1307. callback will be removed.
  1308. .. versionchanged:: 8.0
  1309. Renamed from ``resultcallback``.
  1310. .. versionadded:: 3.0
  1311. """
  1312. def decorator(f: F) -> F:
  1313. old_callback = self._result_callback
  1314. if old_callback is None or replace:
  1315. self._result_callback = f
  1316. return f
  1317. def function(__value, *args, **kwargs): # type: ignore
  1318. inner = old_callback(__value, *args, **kwargs)
  1319. return f(inner, *args, **kwargs)
  1320. self._result_callback = rv = update_wrapper(t.cast(F, function), f)
  1321. return rv
  1322. return decorator
  1323. def format_commands(self, ctx: Context, formatter: HelpFormatter) -> None:
  1324. """Extra format methods for multi methods that adds all the commands
  1325. after the options.
  1326. """
  1327. commands = []
  1328. for subcommand in self.list_commands(ctx):
  1329. cmd = self.get_command(ctx, subcommand)
  1330. # What is this, the tool lied about a command. Ignore it
  1331. if cmd is None:
  1332. continue
  1333. if cmd.hidden:
  1334. continue
  1335. commands.append((subcommand, cmd))
  1336. # allow for 3 times the default spacing
  1337. if len(commands):
  1338. limit = formatter.width - 6 - max(len(cmd[0]) for cmd in commands)
  1339. rows = []
  1340. for subcommand, cmd in commands:
  1341. help = cmd.get_short_help_str(limit)
  1342. rows.append((subcommand, help))
  1343. if rows:
  1344. with formatter.section(_("Commands")):
  1345. formatter.write_dl(rows)
  1346. def parse_args(self, ctx: Context, args: t.List[str]) -> t.List[str]:
  1347. if not args and self.no_args_is_help and not ctx.resilient_parsing:
  1348. echo(ctx.get_help(), color=ctx.color)
  1349. ctx.exit()
  1350. rest = super().parse_args(ctx, args)
  1351. if self.chain:
  1352. ctx.protected_args = rest
  1353. ctx.args = []
  1354. elif rest:
  1355. ctx.protected_args, ctx.args = rest[:1], rest[1:]
  1356. return ctx.args
  1357. def invoke(self, ctx: Context) -> t.Any:
  1358. def _process_result(value: t.Any) -> t.Any:
  1359. if self._result_callback is not None:
  1360. value = ctx.invoke(self._result_callback, value, **ctx.params)
  1361. return value
  1362. if not ctx.protected_args:
  1363. if self.invoke_without_command:
  1364. # No subcommand was invoked, so the result callback is
  1365. # invoked with the group return value for regular
  1366. # groups, or an empty list for chained groups.
  1367. with ctx:
  1368. rv = super().invoke(ctx)
  1369. return _process_result([] if self.chain else rv)
  1370. ctx.fail(_("Missing command."))
  1371. # Fetch args back out
  1372. args = [*ctx.protected_args, *ctx.args]
  1373. ctx.args = []
  1374. ctx.protected_args = []
  1375. # If we're not in chain mode, we only allow the invocation of a
  1376. # single command but we also inform the current context about the
  1377. # name of the command to invoke.
  1378. if not self.chain:
  1379. # Make sure the context is entered so we do not clean up
  1380. # resources until the result processor has worked.
  1381. with ctx:
  1382. cmd_name, cmd, args = self.resolve_command(ctx, args)
  1383. assert cmd is not None
  1384. ctx.invoked_subcommand = cmd_name
  1385. super().invoke(ctx)
  1386. sub_ctx = cmd.make_context(cmd_name, args, parent=ctx)
  1387. with sub_ctx:
  1388. return _process_result(sub_ctx.command.invoke(sub_ctx))
  1389. # In chain mode we create the contexts step by step, but after the
  1390. # base command has been invoked. Because at that point we do not
  1391. # know the subcommands yet, the invoked subcommand attribute is
  1392. # set to ``*`` to inform the command that subcommands are executed
  1393. # but nothing else.
  1394. with ctx:
  1395. ctx.invoked_subcommand = "*" if args else None
  1396. super().invoke(ctx)
  1397. # Otherwise we make every single context and invoke them in a
  1398. # chain. In that case the return value to the result processor
  1399. # is the list of all invoked subcommand's results.
  1400. contexts = []
  1401. while args:
  1402. cmd_name, cmd, args = self.resolve_command(ctx, args)
  1403. assert cmd is not None
  1404. sub_ctx = cmd.make_context(
  1405. cmd_name,
  1406. args,
  1407. parent=ctx,
  1408. allow_extra_args=True,
  1409. allow_interspersed_args=False,
  1410. )
  1411. contexts.append(sub_ctx)
  1412. args, sub_ctx.args = sub_ctx.args, []
  1413. rv = []
  1414. for sub_ctx in contexts:
  1415. with sub_ctx:
  1416. rv.append(sub_ctx.command.invoke(sub_ctx))
  1417. return _process_result(rv)
  1418. def resolve_command(
  1419. self, ctx: Context, args: t.List[str]
  1420. ) -> t.Tuple[t.Optional[str], t.Optional[Command], t.List[str]]:
  1421. cmd_name = make_str(args[0])
  1422. original_cmd_name = cmd_name
  1423. # Get the command
  1424. cmd = self.get_command(ctx, cmd_name)
  1425. # If we can't find the command but there is a normalization
  1426. # function available, we try with that one.
  1427. if cmd is None and ctx.token_normalize_func is not None:
  1428. cmd_name = ctx.token_normalize_func(cmd_name)
  1429. cmd = self.get_command(ctx, cmd_name)
  1430. # If we don't find the command we want to show an error message
  1431. # to the user that it was not provided. However, there is
  1432. # something else we should do: if the first argument looks like
  1433. # an option we want to kick off parsing again for arguments to
  1434. # resolve things like --help which now should go to the main
  1435. # place.
  1436. if cmd is None and not ctx.resilient_parsing:
  1437. if split_opt(cmd_name)[0]:
  1438. self.parse_args(ctx, ctx.args)
  1439. ctx.fail(_("No such command {name!r}.").format(name=original_cmd_name))
  1440. return cmd_name if cmd else None, cmd, args[1:]
  1441. def get_command(self, ctx: Context, cmd_name: str) -> t.Optional[Command]:
  1442. """Given a context and a command name, this returns a
  1443. :class:`Command` object if it exists or returns `None`.
  1444. """
  1445. raise NotImplementedError
  1446. def list_commands(self, ctx: Context) -> t.List[str]:
  1447. """Returns a list of subcommand names in the order they should
  1448. appear.
  1449. """
  1450. return []
  1451. def shell_complete(self, ctx: Context, incomplete: str) -> t.List["CompletionItem"]:
  1452. """Return a list of completions for the incomplete value. Looks
  1453. at the names of options, subcommands, and chained
  1454. multi-commands.
  1455. :param ctx: Invocation context for this command.
  1456. :param incomplete: Value being completed. May be empty.
  1457. .. versionadded:: 8.0
  1458. """
  1459. from click.shell_completion import CompletionItem
  1460. results = [
  1461. CompletionItem(name, help=command.get_short_help_str())
  1462. for name, command in _complete_visible_commands(ctx, incomplete)
  1463. ]
  1464. results.extend(super().shell_complete(ctx, incomplete))
  1465. return results
  1466. class Group(MultiCommand):
  1467. """A group allows a command to have subcommands attached. This is
  1468. the most common way to implement nesting in Click.
  1469. :param name: The name of the group command.
  1470. :param commands: A dict mapping names to :class:`Command` objects.
  1471. Can also be a list of :class:`Command`, which will use
  1472. :attr:`Command.name` to create the dict.
  1473. :param attrs: Other command arguments described in
  1474. :class:`MultiCommand`, :class:`Command`, and
  1475. :class:`BaseCommand`.
  1476. .. versionchanged:: 8.0
  1477. The ``commands`` argument can be a list of command objects.
  1478. """
  1479. #: If set, this is used by the group's :meth:`command` decorator
  1480. #: as the default :class:`Command` class. This is useful to make all
  1481. #: subcommands use a custom command class.
  1482. #:
  1483. #: .. versionadded:: 8.0
  1484. command_class: t.Optional[t.Type[Command]] = None
  1485. #: If set, this is used by the group's :meth:`group` decorator
  1486. #: as the default :class:`Group` class. This is useful to make all
  1487. #: subgroups use a custom group class.
  1488. #:
  1489. #: If set to the special value :class:`type` (literally
  1490. #: ``group_class = type``), this group's class will be used as the
  1491. #: default class. This makes a custom group class continue to make
  1492. #: custom groups.
  1493. #:
  1494. #: .. versionadded:: 8.0
  1495. group_class: t.Optional[t.Union[t.Type["Group"], t.Type[type]]] = None
  1496. # Literal[type] isn't valid, so use Type[type]
  1497. def __init__(
  1498. self,
  1499. name: t.Optional[str] = None,
  1500. commands: t.Optional[
  1501. t.Union[t.MutableMapping[str, Command], t.Sequence[Command]]
  1502. ] = None,
  1503. **attrs: t.Any,
  1504. ) -> None:
  1505. super().__init__(name, **attrs)
  1506. if commands is None:
  1507. commands = {}
  1508. elif isinstance(commands, abc.Sequence):
  1509. commands = {c.name: c for c in commands if c.name is not None}
  1510. #: The registered subcommands by their exported names.
  1511. self.commands: t.MutableMapping[str, Command] = commands
  1512. def add_command(self, cmd: Command, name: t.Optional[str] = None) -> None:
  1513. """Registers another :class:`Command` with this group. If the name
  1514. is not provided, the name of the command is used.
  1515. """
  1516. name = name or cmd.name
  1517. if name is None:
  1518. raise TypeError("Command has no name.")
  1519. _check_multicommand(self, name, cmd, register=True)
  1520. self.commands[name] = cmd
  1521. @t.overload
  1522. def command(self, __func: t.Callable[..., t.Any]) -> Command:
  1523. ...
  1524. @t.overload
  1525. def command(
  1526. self, *args: t.Any, **kwargs: t.Any
  1527. ) -> t.Callable[[t.Callable[..., t.Any]], Command]:
  1528. ...
  1529. def command(
  1530. self, *args: t.Any, **kwargs: t.Any
  1531. ) -> t.Union[t.Callable[[t.Callable[..., t.Any]], Command], Command]:
  1532. """A shortcut decorator for declaring and attaching a command to
  1533. the group. This takes the same arguments as :func:`command` and
  1534. immediately registers the created command with this group by
  1535. calling :meth:`add_command`.
  1536. To customize the command class used, set the
  1537. :attr:`command_class` attribute.
  1538. .. versionchanged:: 8.1
  1539. This decorator can be applied without parentheses.
  1540. .. versionchanged:: 8.0
  1541. Added the :attr:`command_class` attribute.
  1542. """
  1543. from .decorators import command
  1544. func: t.Optional[t.Callable[..., t.Any]] = None
  1545. if args and callable(args[0]):
  1546. assert (
  1547. len(args) == 1 and not kwargs
  1548. ), "Use 'command(**kwargs)(callable)' to provide arguments."
  1549. (func,) = args
  1550. args = ()
  1551. if self.command_class and kwargs.get("cls") is None:
  1552. kwargs["cls"] = self.command_class
  1553. def decorator(f: t.Callable[..., t.Any]) -> Command:
  1554. cmd: Command = command(*args, **kwargs)(f)
  1555. self.add_command(cmd)
  1556. return cmd
  1557. if func is not None:
  1558. return decorator(func)
  1559. return decorator
  1560. @t.overload
  1561. def group(self, __func: t.Callable[..., t.Any]) -> "Group":
  1562. ...
  1563. @t.overload
  1564. def group(
  1565. self, *args: t.Any, **kwargs: t.Any
  1566. ) -> t.Callable[[t.Callable[..., t.Any]], "Group"]:
  1567. ...
  1568. def group(
  1569. self, *args: t.Any, **kwargs: t.Any
  1570. ) -> t.Union[t.Callable[[t.Callable[..., t.Any]], "Group"], "Group"]:
  1571. """A shortcut decorator for declaring and attaching a group to
  1572. the group. This takes the same arguments as :func:`group` and
  1573. immediately registers the created group with this group by
  1574. calling :meth:`add_command`.
  1575. To customize the group class used, set the :attr:`group_class`
  1576. attribute.
  1577. .. versionchanged:: 8.1
  1578. This decorator can be applied without parentheses.
  1579. .. versionchanged:: 8.0
  1580. Added the :attr:`group_class` attribute.
  1581. """
  1582. from .decorators import group
  1583. func: t.Optional[t.Callable[..., t.Any]] = None
  1584. if args and callable(args[0]):
  1585. assert (
  1586. len(args) == 1 and not kwargs
  1587. ), "Use 'group(**kwargs)(callable)' to provide arguments."
  1588. (func,) = args
  1589. args = ()
  1590. if self.group_class is not None and kwargs.get("cls") is None:
  1591. if self.group_class is type:
  1592. kwargs["cls"] = type(self)
  1593. else:
  1594. kwargs["cls"] = self.group_class
  1595. def decorator(f: t.Callable[..., t.Any]) -> "Group":
  1596. cmd: Group = group(*args, **kwargs)(f)
  1597. self.add_command(cmd)
  1598. return cmd
  1599. if func is not None:
  1600. return decorator(func)
  1601. return decorator
  1602. def get_command(self, ctx: Context, cmd_name: str) -> t.Optional[Command]:
  1603. return self.commands.get(cmd_name)
  1604. def list_commands(self, ctx: Context) -> t.List[str]:
  1605. return sorted(self.commands)
  1606. class CommandCollection(MultiCommand):
  1607. """A command collection is a multi command that merges multiple multi
  1608. commands together into one. This is a straightforward implementation
  1609. that accepts a list of different multi commands as sources and
  1610. provides all the commands for each of them.
  1611. See :class:`MultiCommand` and :class:`Command` for the description of
  1612. ``name`` and ``attrs``.
  1613. """
  1614. def __init__(
  1615. self,
  1616. name: t.Optional[str] = None,
  1617. sources: t.Optional[t.List[MultiCommand]] = None,
  1618. **attrs: t.Any,
  1619. ) -> None:
  1620. super().__init__(name, **attrs)
  1621. #: The list of registered multi commands.
  1622. self.sources: t.List[MultiCommand] = sources or []
  1623. def add_source(self, multi_cmd: MultiCommand) -> None:
  1624. """Adds a new multi command to the chain dispatcher."""
  1625. self.sources.append(multi_cmd)
  1626. def get_command(self, ctx: Context, cmd_name: str) -> t.Optional[Command]:
  1627. for source in self.sources:
  1628. rv = source.get_command(ctx, cmd_name)
  1629. if rv is not None:
  1630. if self.chain:
  1631. _check_multicommand(self, cmd_name, rv)
  1632. return rv
  1633. return None
  1634. def list_commands(self, ctx: Context) -> t.List[str]:
  1635. rv: t.Set[str] = set()
  1636. for source in self.sources:
  1637. rv.update(source.list_commands(ctx))
  1638. return sorted(rv)
  1639. def _check_iter(value: t.Any) -> t.Iterator[t.Any]:
  1640. """Check if the value is iterable but not a string. Raises a type
  1641. error, or return an iterator over the value.
  1642. """
  1643. if isinstance(value, str):
  1644. raise TypeError
  1645. return iter(value)
  1646. class Parameter:
  1647. r"""A parameter to a command comes in two versions: they are either
  1648. :class:`Option`\s or :class:`Argument`\s. Other subclasses are currently
  1649. not supported by design as some of the internals for parsing are
  1650. intentionally not finalized.
  1651. Some settings are supported by both options and arguments.
  1652. :param param_decls: the parameter declarations for this option or
  1653. argument. This is a list of flags or argument
  1654. names.
  1655. :param type: the type that should be used. Either a :class:`ParamType`
  1656. or a Python type. The latter is converted into the former
  1657. automatically if supported.
  1658. :param required: controls if this is optional or not.
  1659. :param default: the default value if omitted. This can also be a callable,
  1660. in which case it's invoked when the default is needed
  1661. without any arguments.
  1662. :param callback: A function to further process or validate the value
  1663. after type conversion. It is called as ``f(ctx, param, value)``
  1664. and must return the value. It is called for all sources,
  1665. including prompts.
  1666. :param nargs: the number of arguments to match. If not ``1`` the return
  1667. value is a tuple instead of single value. The default for
  1668. nargs is ``1`` (except if the type is a tuple, then it's
  1669. the arity of the tuple). If ``nargs=-1``, all remaining
  1670. parameters are collected.
  1671. :param metavar: how the value is represented in the help page.
  1672. :param expose_value: if this is `True` then the value is passed onwards
  1673. to the command callback and stored on the context,
  1674. otherwise it's skipped.
  1675. :param is_eager: eager values are processed before non eager ones. This
  1676. should not be set for arguments or it will inverse the
  1677. order of processing.
  1678. :param envvar: a string or list of strings that are environment variables
  1679. that should be checked.
  1680. :param shell_complete: A function that returns custom shell
  1681. completions. Used instead of the param's type completion if
  1682. given. Takes ``ctx, param, incomplete`` and must return a list
  1683. of :class:`~click.shell_completion.CompletionItem` or a list of
  1684. strings.
  1685. .. versionchanged:: 8.0
  1686. ``process_value`` validates required parameters and bounded
  1687. ``nargs``, and invokes the parameter callback before returning
  1688. the value. This allows the callback to validate prompts.
  1689. ``full_process_value`` is removed.
  1690. .. versionchanged:: 8.0
  1691. ``autocompletion`` is renamed to ``shell_complete`` and has new
  1692. semantics described above. The old name is deprecated and will
  1693. be removed in 8.1, until then it will be wrapped to match the
  1694. new requirements.
  1695. .. versionchanged:: 8.0
  1696. For ``multiple=True, nargs>1``, the default must be a list of
  1697. tuples.
  1698. .. versionchanged:: 8.0
  1699. Setting a default is no longer required for ``nargs>1``, it will
  1700. default to ``None``. ``multiple=True`` or ``nargs=-1`` will
  1701. default to ``()``.
  1702. .. versionchanged:: 7.1
  1703. Empty environment variables are ignored rather than taking the
  1704. empty string value. This makes it possible for scripts to clear
  1705. variables if they can't unset them.
  1706. .. versionchanged:: 2.0
  1707. Changed signature for parameter callback to also be passed the
  1708. parameter. The old callback format will still work, but it will
  1709. raise a warning to give you a chance to migrate the code easier.
  1710. """
  1711. param_type_name = "parameter"
  1712. def __init__(
  1713. self,
  1714. param_decls: t.Optional[t.Sequence[str]] = None,
  1715. type: t.Optional[t.Union[types.ParamType, t.Any]] = None,
  1716. required: bool = False,
  1717. default: t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]] = None,
  1718. callback: t.Optional[t.Callable[[Context, "Parameter", t.Any], t.Any]] = None,
  1719. nargs: t.Optional[int] = None,
  1720. multiple: bool = False,
  1721. metavar: t.Optional[str] = None,
  1722. expose_value: bool = True,
  1723. is_eager: bool = False,
  1724. envvar: t.Optional[t.Union[str, t.Sequence[str]]] = None,
  1725. shell_complete: t.Optional[
  1726. t.Callable[
  1727. [Context, "Parameter", str],
  1728. t.Union[t.List["CompletionItem"], t.List[str]],
  1729. ]
  1730. ] = None,
  1731. ) -> None:
  1732. self.name: t.Optional[str]
  1733. self.opts: t.List[str]
  1734. self.secondary_opts: t.List[str]
  1735. self.name, self.opts, self.secondary_opts = self._parse_decls(
  1736. param_decls or (), expose_value
  1737. )
  1738. self.type: types.ParamType = types.convert_type(type, default)
  1739. # Default nargs to what the type tells us if we have that
  1740. # information available.
  1741. if nargs is None:
  1742. if self.type.is_composite:
  1743. nargs = self.type.arity
  1744. else:
  1745. nargs = 1
  1746. self.required = required
  1747. self.callback = callback
  1748. self.nargs = nargs
  1749. self.multiple = multiple
  1750. self.expose_value = expose_value
  1751. self.default = default
  1752. self.is_eager = is_eager
  1753. self.metavar = metavar
  1754. self.envvar = envvar
  1755. self._custom_shell_complete = shell_complete
  1756. if __debug__:
  1757. if self.type.is_composite and nargs != self.type.arity:
  1758. raise ValueError(
  1759. f"'nargs' must be {self.type.arity} (or None) for"
  1760. f" type {self.type!r}, but it was {nargs}."
  1761. )
  1762. # Skip no default or callable default.
  1763. check_default = default if not callable(default) else None
  1764. if check_default is not None:
  1765. if multiple:
  1766. try:
  1767. # Only check the first value against nargs.
  1768. check_default = next(_check_iter(check_default), None)
  1769. except TypeError:
  1770. raise ValueError(
  1771. "'default' must be a list when 'multiple' is true."
  1772. ) from None
  1773. # Can be None for multiple with empty default.
  1774. if nargs != 1 and check_default is not None:
  1775. try:
  1776. _check_iter(check_default)
  1777. except TypeError:
  1778. if multiple:
  1779. message = (
  1780. "'default' must be a list of lists when 'multiple' is"
  1781. " true and 'nargs' != 1."
  1782. )
  1783. else:
  1784. message = "'default' must be a list when 'nargs' != 1."
  1785. raise ValueError(message) from None
  1786. if nargs > 1 and len(check_default) != nargs:
  1787. subject = "item length" if multiple else "length"
  1788. raise ValueError(
  1789. f"'default' {subject} must match nargs={nargs}."
  1790. )
  1791. def to_info_dict(self) -> t.Dict[str, t.Any]:
  1792. """Gather information that could be useful for a tool generating
  1793. user-facing documentation.
  1794. Use :meth:`click.Context.to_info_dict` to traverse the entire
  1795. CLI structure.
  1796. .. versionadded:: 8.0
  1797. """
  1798. return {
  1799. "name": self.name,
  1800. "param_type_name": self.param_type_name,
  1801. "opts": self.opts,
  1802. "secondary_opts": self.secondary_opts,
  1803. "type": self.type.to_info_dict(),
  1804. "required": self.required,
  1805. "nargs": self.nargs,
  1806. "multiple": self.multiple,
  1807. "default": self.default,
  1808. "envvar": self.envvar,
  1809. }
  1810. def __repr__(self) -> str:
  1811. return f"<{self.__class__.__name__} {self.name}>"
  1812. def _parse_decls(
  1813. self, decls: t.Sequence[str], expose_value: bool
  1814. ) -> t.Tuple[t.Optional[str], t.List[str], t.List[str]]:
  1815. raise NotImplementedError()
  1816. @property
  1817. def human_readable_name(self) -> str:
  1818. """Returns the human readable name of this parameter. This is the
  1819. same as the name for options, but the metavar for arguments.
  1820. """
  1821. return self.name # type: ignore
  1822. def make_metavar(self) -> str:
  1823. if self.metavar is not None:
  1824. return self.metavar
  1825. metavar = self.type.get_metavar(self)
  1826. if metavar is None:
  1827. metavar = self.type.name.upper()
  1828. if self.nargs != 1:
  1829. metavar += "..."
  1830. return metavar
  1831. @t.overload
  1832. def get_default(
  1833. self, ctx: Context, call: "te.Literal[True]" = True
  1834. ) -> t.Optional[t.Any]:
  1835. ...
  1836. @t.overload
  1837. def get_default(
  1838. self, ctx: Context, call: bool = ...
  1839. ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]:
  1840. ...
  1841. def get_default(
  1842. self, ctx: Context, call: bool = True
  1843. ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]:
  1844. """Get the default for the parameter. Tries
  1845. :meth:`Context.lookup_default` first, then the local default.
  1846. :param ctx: Current context.
  1847. :param call: If the default is a callable, call it. Disable to
  1848. return the callable instead.
  1849. .. versionchanged:: 8.0.2
  1850. Type casting is no longer performed when getting a default.
  1851. .. versionchanged:: 8.0.1
  1852. Type casting can fail in resilient parsing mode. Invalid
  1853. defaults will not prevent showing help text.
  1854. .. versionchanged:: 8.0
  1855. Looks at ``ctx.default_map`` first.
  1856. .. versionchanged:: 8.0
  1857. Added the ``call`` parameter.
  1858. """
  1859. value = ctx.lookup_default(self.name, call=False) # type: ignore
  1860. if value is None:
  1861. value = self.default
  1862. if call and callable(value):
  1863. value = value()
  1864. return value
  1865. def add_to_parser(self, parser: OptionParser, ctx: Context) -> None:
  1866. raise NotImplementedError()
  1867. def consume_value(
  1868. self, ctx: Context, opts: t.Mapping[str, t.Any]
  1869. ) -> t.Tuple[t.Any, ParameterSource]:
  1870. value = opts.get(self.name) # type: ignore
  1871. source = ParameterSource.COMMANDLINE
  1872. if value is None:
  1873. value = self.value_from_envvar(ctx)
  1874. source = ParameterSource.ENVIRONMENT
  1875. if value is None:
  1876. value = ctx.lookup_default(self.name) # type: ignore
  1877. source = ParameterSource.DEFAULT_MAP
  1878. if value is None:
  1879. value = self.get_default(ctx)
  1880. source = ParameterSource.DEFAULT
  1881. return value, source
  1882. def type_cast_value(self, ctx: Context, value: t.Any) -> t.Any:
  1883. """Convert and validate a value against the option's
  1884. :attr:`type`, :attr:`multiple`, and :attr:`nargs`.
  1885. """
  1886. if value is None:
  1887. return () if self.multiple or self.nargs == -1 else None
  1888. def check_iter(value: t.Any) -> t.Iterator[t.Any]:
  1889. try:
  1890. return _check_iter(value)
  1891. except TypeError:
  1892. # This should only happen when passing in args manually,
  1893. # the parser should construct an iterable when parsing
  1894. # the command line.
  1895. raise BadParameter(
  1896. _("Value must be an iterable."), ctx=ctx, param=self
  1897. ) from None
  1898. if self.nargs == 1 or self.type.is_composite:
  1899. def convert(value: t.Any) -> t.Any:
  1900. return self.type(value, param=self, ctx=ctx)
  1901. elif self.nargs == -1:
  1902. def convert(value: t.Any) -> t.Any: # t.Tuple[t.Any, ...]
  1903. return tuple(self.type(x, self, ctx) for x in check_iter(value))
  1904. else: # nargs > 1
  1905. def convert(value: t.Any) -> t.Any: # t.Tuple[t.Any, ...]
  1906. value = tuple(check_iter(value))
  1907. if len(value) != self.nargs:
  1908. raise BadParameter(
  1909. ngettext(
  1910. "Takes {nargs} values but 1 was given.",
  1911. "Takes {nargs} values but {len} were given.",
  1912. len(value),
  1913. ).format(nargs=self.nargs, len=len(value)),
  1914. ctx=ctx,
  1915. param=self,
  1916. )
  1917. return tuple(self.type(x, self, ctx) for x in value)
  1918. if self.multiple:
  1919. return tuple(convert(x) for x in check_iter(value))
  1920. return convert(value)
  1921. def value_is_missing(self, value: t.Any) -> bool:
  1922. if value is None:
  1923. return True
  1924. if (self.nargs != 1 or self.multiple) and value == ():
  1925. return True
  1926. return False
  1927. def process_value(self, ctx: Context, value: t.Any) -> t.Any:
  1928. value = self.type_cast_value(ctx, value)
  1929. if self.required and self.value_is_missing(value):
  1930. raise MissingParameter(ctx=ctx, param=self)
  1931. if self.callback is not None:
  1932. value = self.callback(ctx, self, value)
  1933. return value
  1934. def resolve_envvar_value(self, ctx: Context) -> t.Optional[str]:
  1935. if self.envvar is None:
  1936. return None
  1937. if isinstance(self.envvar, str):
  1938. rv = os.environ.get(self.envvar)
  1939. if rv:
  1940. return rv
  1941. else:
  1942. for envvar in self.envvar:
  1943. rv = os.environ.get(envvar)
  1944. if rv:
  1945. return rv
  1946. return None
  1947. def value_from_envvar(self, ctx: Context) -> t.Optional[t.Any]:
  1948. rv: t.Optional[t.Any] = self.resolve_envvar_value(ctx)
  1949. if rv is not None and self.nargs != 1:
  1950. rv = self.type.split_envvar_value(rv)
  1951. return rv
  1952. def handle_parse_result(
  1953. self, ctx: Context, opts: t.Mapping[str, t.Any], args: t.List[str]
  1954. ) -> t.Tuple[t.Any, t.List[str]]:
  1955. with augment_usage_errors(ctx, param=self):
  1956. value, source = self.consume_value(ctx, opts)
  1957. ctx.set_parameter_source(self.name, source) # type: ignore
  1958. try:
  1959. value = self.process_value(ctx, value)
  1960. except Exception:
  1961. if not ctx.resilient_parsing:
  1962. raise
  1963. value = None
  1964. if self.expose_value:
  1965. ctx.params[self.name] = value # type: ignore
  1966. return value, args
  1967. def get_help_record(self, ctx: Context) -> t.Optional[t.Tuple[str, str]]:
  1968. pass
  1969. def get_usage_pieces(self, ctx: Context) -> t.List[str]:
  1970. return []
  1971. def get_error_hint(self, ctx: Context) -> str:
  1972. """Get a stringified version of the param for use in error messages to
  1973. indicate which param caused the error.
  1974. """
  1975. hint_list = self.opts or [self.human_readable_name]
  1976. return " / ".join(f"'{x}'" for x in hint_list)
  1977. def shell_complete(self, ctx: Context, incomplete: str) -> t.List["CompletionItem"]:
  1978. """Return a list of completions for the incomplete value. If a
  1979. ``shell_complete`` function was given during init, it is used.
  1980. Otherwise, the :attr:`type`
  1981. :meth:`~click.types.ParamType.shell_complete` function is used.
  1982. :param ctx: Invocation context for this command.
  1983. :param incomplete: Value being completed. May be empty.
  1984. .. versionadded:: 8.0
  1985. """
  1986. if self._custom_shell_complete is not None:
  1987. results = self._custom_shell_complete(ctx, self, incomplete)
  1988. if results and isinstance(results[0], str):
  1989. from click.shell_completion import CompletionItem
  1990. results = [CompletionItem(c) for c in results]
  1991. return t.cast(t.List["CompletionItem"], results)
  1992. return self.type.shell_complete(ctx, self, incomplete)
  1993. class Option(Parameter):
  1994. """Options are usually optional values on the command line and
  1995. have some extra features that arguments don't have.
  1996. All other parameters are passed onwards to the parameter constructor.
  1997. :param show_default: Show the default value for this option in its
  1998. help text. Values are not shown by default, unless
  1999. :attr:`Context.show_default` is ``True``. If this value is a
  2000. string, it shows that string in parentheses instead of the
  2001. actual value. This is particularly useful for dynamic options.
  2002. For single option boolean flags, the default remains hidden if
  2003. its value is ``False``.
  2004. :param show_envvar: Controls if an environment variable should be
  2005. shown on the help page. Normally, environment variables are not
  2006. shown.
  2007. :param prompt: If set to ``True`` or a non empty string then the
  2008. user will be prompted for input. If set to ``True`` the prompt
  2009. will be the option name capitalized.
  2010. :param confirmation_prompt: Prompt a second time to confirm the
  2011. value if it was prompted for. Can be set to a string instead of
  2012. ``True`` to customize the message.
  2013. :param prompt_required: If set to ``False``, the user will be
  2014. prompted for input only when the option was specified as a flag
  2015. without a value.
  2016. :param hide_input: If this is ``True`` then the input on the prompt
  2017. will be hidden from the user. This is useful for password input.
  2018. :param is_flag: forces this option to act as a flag. The default is
  2019. auto detection.
  2020. :param flag_value: which value should be used for this flag if it's
  2021. enabled. This is set to a boolean automatically if
  2022. the option string contains a slash to mark two options.
  2023. :param multiple: if this is set to `True` then the argument is accepted
  2024. multiple times and recorded. This is similar to ``nargs``
  2025. in how it works but supports arbitrary number of
  2026. arguments.
  2027. :param count: this flag makes an option increment an integer.
  2028. :param allow_from_autoenv: if this is enabled then the value of this
  2029. parameter will be pulled from an environment
  2030. variable in case a prefix is defined on the
  2031. context.
  2032. :param help: the help string.
  2033. :param hidden: hide this option from help outputs.
  2034. :param attrs: Other command arguments described in :class:`Parameter`.
  2035. .. versionchanged:: 8.1.0
  2036. Help text indentation is cleaned here instead of only in the
  2037. ``@option`` decorator.
  2038. .. versionchanged:: 8.1.0
  2039. The ``show_default`` parameter overrides
  2040. ``Context.show_default``.
  2041. .. versionchanged:: 8.1.0
  2042. The default of a single option boolean flag is not shown if the
  2043. default value is ``False``.
  2044. .. versionchanged:: 8.0.1
  2045. ``type`` is detected from ``flag_value`` if given.
  2046. """
  2047. param_type_name = "option"
  2048. def __init__(
  2049. self,
  2050. param_decls: t.Optional[t.Sequence[str]] = None,
  2051. show_default: t.Union[bool, str, None] = None,
  2052. prompt: t.Union[bool, str] = False,
  2053. confirmation_prompt: t.Union[bool, str] = False,
  2054. prompt_required: bool = True,
  2055. hide_input: bool = False,
  2056. is_flag: t.Optional[bool] = None,
  2057. flag_value: t.Optional[t.Any] = None,
  2058. multiple: bool = False,
  2059. count: bool = False,
  2060. allow_from_autoenv: bool = True,
  2061. type: t.Optional[t.Union[types.ParamType, t.Any]] = None,
  2062. help: t.Optional[str] = None,
  2063. hidden: bool = False,
  2064. show_choices: bool = True,
  2065. show_envvar: bool = False,
  2066. **attrs: t.Any,
  2067. ) -> None:
  2068. if help:
  2069. help = inspect.cleandoc(help)
  2070. default_is_missing = "default" not in attrs
  2071. super().__init__(param_decls, type=type, multiple=multiple, **attrs)
  2072. if prompt is True:
  2073. if self.name is None:
  2074. raise TypeError("'name' is required with 'prompt=True'.")
  2075. prompt_text: t.Optional[str] = self.name.replace("_", " ").capitalize()
  2076. elif prompt is False:
  2077. prompt_text = None
  2078. else:
  2079. prompt_text = prompt
  2080. self.prompt = prompt_text
  2081. self.confirmation_prompt = confirmation_prompt
  2082. self.prompt_required = prompt_required
  2083. self.hide_input = hide_input
  2084. self.hidden = hidden
  2085. # If prompt is enabled but not required, then the option can be
  2086. # used as a flag to indicate using prompt or flag_value.
  2087. self._flag_needs_value = self.prompt is not None and not self.prompt_required
  2088. if is_flag is None:
  2089. if flag_value is not None:
  2090. # Implicitly a flag because flag_value was set.
  2091. is_flag = True
  2092. elif self._flag_needs_value:
  2093. # Not a flag, but when used as a flag it shows a prompt.
  2094. is_flag = False
  2095. else:
  2096. # Implicitly a flag because flag options were given.
  2097. is_flag = bool(self.secondary_opts)
  2098. elif is_flag is False and not self._flag_needs_value:
  2099. # Not a flag, and prompt is not enabled, can be used as a
  2100. # flag if flag_value is set.
  2101. self._flag_needs_value = flag_value is not None
  2102. self.default: t.Union[t.Any, t.Callable[[], t.Any]]
  2103. if is_flag and default_is_missing and not self.required:
  2104. if multiple:
  2105. self.default = ()
  2106. else:
  2107. self.default = False
  2108. if flag_value is None:
  2109. flag_value = not self.default
  2110. self.type: types.ParamType
  2111. if is_flag and type is None:
  2112. # Re-guess the type from the flag value instead of the
  2113. # default.
  2114. self.type = types.convert_type(None, flag_value)
  2115. self.is_flag: bool = is_flag
  2116. self.is_bool_flag: bool = is_flag and isinstance(self.type, types.BoolParamType)
  2117. self.flag_value: t.Any = flag_value
  2118. # Counting
  2119. self.count = count
  2120. if count:
  2121. if type is None:
  2122. self.type = types.IntRange(min=0)
  2123. if default_is_missing:
  2124. self.default = 0
  2125. self.allow_from_autoenv = allow_from_autoenv
  2126. self.help = help
  2127. self.show_default = show_default
  2128. self.show_choices = show_choices
  2129. self.show_envvar = show_envvar
  2130. if __debug__:
  2131. if self.nargs == -1:
  2132. raise TypeError("nargs=-1 is not supported for options.")
  2133. if self.prompt and self.is_flag and not self.is_bool_flag:
  2134. raise TypeError("'prompt' is not valid for non-boolean flag.")
  2135. if not self.is_bool_flag and self.secondary_opts:
  2136. raise TypeError("Secondary flag is not valid for non-boolean flag.")
  2137. if self.is_bool_flag and self.hide_input and self.prompt is not None:
  2138. raise TypeError(
  2139. "'prompt' with 'hide_input' is not valid for boolean flag."
  2140. )
  2141. if self.count:
  2142. if self.multiple:
  2143. raise TypeError("'count' is not valid with 'multiple'.")
  2144. if self.is_flag:
  2145. raise TypeError("'count' is not valid with 'is_flag'.")
  2146. def to_info_dict(self) -> t.Dict[str, t.Any]:
  2147. info_dict = super().to_info_dict()
  2148. info_dict.update(
  2149. help=self.help,
  2150. prompt=self.prompt,
  2151. is_flag=self.is_flag,
  2152. flag_value=self.flag_value,
  2153. count=self.count,
  2154. hidden=self.hidden,
  2155. )
  2156. return info_dict
  2157. def _parse_decls(
  2158. self, decls: t.Sequence[str], expose_value: bool
  2159. ) -> t.Tuple[t.Optional[str], t.List[str], t.List[str]]:
  2160. opts = []
  2161. secondary_opts = []
  2162. name = None
  2163. possible_names = []
  2164. for decl in decls:
  2165. if decl.isidentifier():
  2166. if name is not None:
  2167. raise TypeError(f"Name '{name}' defined twice")
  2168. name = decl
  2169. else:
  2170. split_char = ";" if decl[:1] == "/" else "/"
  2171. if split_char in decl:
  2172. first, second = decl.split(split_char, 1)
  2173. first = first.rstrip()
  2174. if first:
  2175. possible_names.append(split_opt(first))
  2176. opts.append(first)
  2177. second = second.lstrip()
  2178. if second:
  2179. secondary_opts.append(second.lstrip())
  2180. if first == second:
  2181. raise ValueError(
  2182. f"Boolean option {decl!r} cannot use the"
  2183. " same flag for true/false."
  2184. )
  2185. else:
  2186. possible_names.append(split_opt(decl))
  2187. opts.append(decl)
  2188. if name is None and possible_names:
  2189. possible_names.sort(key=lambda x: -len(x[0])) # group long options first
  2190. name = possible_names[0][1].replace("-", "_").lower()
  2191. if not name.isidentifier():
  2192. name = None
  2193. if name is None:
  2194. if not expose_value:
  2195. return None, opts, secondary_opts
  2196. raise TypeError("Could not determine name for option")
  2197. if not opts and not secondary_opts:
  2198. raise TypeError(
  2199. f"No options defined but a name was passed ({name})."
  2200. " Did you mean to declare an argument instead? Did"
  2201. f" you mean to pass '--{name}'?"
  2202. )
  2203. return name, opts, secondary_opts
  2204. def add_to_parser(self, parser: OptionParser, ctx: Context) -> None:
  2205. if self.multiple:
  2206. action = "append"
  2207. elif self.count:
  2208. action = "count"
  2209. else:
  2210. action = "store"
  2211. if self.is_flag:
  2212. action = f"{action}_const"
  2213. if self.is_bool_flag and self.secondary_opts:
  2214. parser.add_option(
  2215. obj=self, opts=self.opts, dest=self.name, action=action, const=True
  2216. )
  2217. parser.add_option(
  2218. obj=self,
  2219. opts=self.secondary_opts,
  2220. dest=self.name,
  2221. action=action,
  2222. const=False,
  2223. )
  2224. else:
  2225. parser.add_option(
  2226. obj=self,
  2227. opts=self.opts,
  2228. dest=self.name,
  2229. action=action,
  2230. const=self.flag_value,
  2231. )
  2232. else:
  2233. parser.add_option(
  2234. obj=self,
  2235. opts=self.opts,
  2236. dest=self.name,
  2237. action=action,
  2238. nargs=self.nargs,
  2239. )
  2240. def get_help_record(self, ctx: Context) -> t.Optional[t.Tuple[str, str]]:
  2241. if self.hidden:
  2242. return None
  2243. any_prefix_is_slash = False
  2244. def _write_opts(opts: t.Sequence[str]) -> str:
  2245. nonlocal any_prefix_is_slash
  2246. rv, any_slashes = join_options(opts)
  2247. if any_slashes:
  2248. any_prefix_is_slash = True
  2249. if not self.is_flag and not self.count:
  2250. rv += f" {self.make_metavar()}"
  2251. return rv
  2252. rv = [_write_opts(self.opts)]
  2253. if self.secondary_opts:
  2254. rv.append(_write_opts(self.secondary_opts))
  2255. help = self.help or ""
  2256. extra = []
  2257. if self.show_envvar:
  2258. envvar = self.envvar
  2259. if envvar is None:
  2260. if (
  2261. self.allow_from_autoenv
  2262. and ctx.auto_envvar_prefix is not None
  2263. and self.name is not None
  2264. ):
  2265. envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}"
  2266. if envvar is not None:
  2267. var_str = (
  2268. envvar
  2269. if isinstance(envvar, str)
  2270. else ", ".join(str(d) for d in envvar)
  2271. )
  2272. extra.append(_("env var: {var}").format(var=var_str))
  2273. # Temporarily enable resilient parsing to avoid type casting
  2274. # failing for the default. Might be possible to extend this to
  2275. # help formatting in general.
  2276. resilient = ctx.resilient_parsing
  2277. ctx.resilient_parsing = True
  2278. try:
  2279. default_value = self.get_default(ctx, call=False)
  2280. finally:
  2281. ctx.resilient_parsing = resilient
  2282. show_default = False
  2283. show_default_is_str = False
  2284. if self.show_default is not None:
  2285. if isinstance(self.show_default, str):
  2286. show_default_is_str = show_default = True
  2287. else:
  2288. show_default = self.show_default
  2289. elif ctx.show_default is not None:
  2290. show_default = ctx.show_default
  2291. if show_default_is_str or (show_default and (default_value is not None)):
  2292. if show_default_is_str:
  2293. default_string = f"({self.show_default})"
  2294. elif isinstance(default_value, (list, tuple)):
  2295. default_string = ", ".join(str(d) for d in default_value)
  2296. elif inspect.isfunction(default_value):
  2297. default_string = _("(dynamic)")
  2298. elif self.is_bool_flag and self.secondary_opts:
  2299. # For boolean flags that have distinct True/False opts,
  2300. # use the opt without prefix instead of the value.
  2301. default_string = split_opt(
  2302. (self.opts if self.default else self.secondary_opts)[0]
  2303. )[1]
  2304. elif self.is_bool_flag and not self.secondary_opts and not default_value:
  2305. default_string = ""
  2306. else:
  2307. default_string = str(default_value)
  2308. if default_string:
  2309. extra.append(_("default: {default}").format(default=default_string))
  2310. if (
  2311. isinstance(self.type, types._NumberRangeBase)
  2312. # skip count with default range type
  2313. and not (self.count and self.type.min == 0 and self.type.max is None)
  2314. ):
  2315. range_str = self.type._describe_range()
  2316. if range_str:
  2317. extra.append(range_str)
  2318. if self.required:
  2319. extra.append(_("required"))
  2320. if extra:
  2321. extra_str = "; ".join(extra)
  2322. help = f"{help} [{extra_str}]" if help else f"[{extra_str}]"
  2323. return ("; " if any_prefix_is_slash else " / ").join(rv), help
  2324. @t.overload
  2325. def get_default(
  2326. self, ctx: Context, call: "te.Literal[True]" = True
  2327. ) -> t.Optional[t.Any]:
  2328. ...
  2329. @t.overload
  2330. def get_default(
  2331. self, ctx: Context, call: bool = ...
  2332. ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]:
  2333. ...
  2334. def get_default(
  2335. self, ctx: Context, call: bool = True
  2336. ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]:
  2337. # If we're a non boolean flag our default is more complex because
  2338. # we need to look at all flags in the same group to figure out
  2339. # if we're the default one in which case we return the flag
  2340. # value as default.
  2341. if self.is_flag and not self.is_bool_flag:
  2342. for param in ctx.command.params:
  2343. if param.name == self.name and param.default:
  2344. return t.cast(Option, param).flag_value
  2345. return None
  2346. return super().get_default(ctx, call=call)
  2347. def prompt_for_value(self, ctx: Context) -> t.Any:
  2348. """This is an alternative flow that can be activated in the full
  2349. value processing if a value does not exist. It will prompt the
  2350. user until a valid value exists and then returns the processed
  2351. value as result.
  2352. """
  2353. assert self.prompt is not None
  2354. # Calculate the default before prompting anything to be stable.
  2355. default = self.get_default(ctx)
  2356. # If this is a prompt for a flag we need to handle this
  2357. # differently.
  2358. if self.is_bool_flag:
  2359. return confirm(self.prompt, default)
  2360. return prompt(
  2361. self.prompt,
  2362. default=default,
  2363. type=self.type,
  2364. hide_input=self.hide_input,
  2365. show_choices=self.show_choices,
  2366. confirmation_prompt=self.confirmation_prompt,
  2367. value_proc=lambda x: self.process_value(ctx, x),
  2368. )
  2369. def resolve_envvar_value(self, ctx: Context) -> t.Optional[str]:
  2370. rv = super().resolve_envvar_value(ctx)
  2371. if rv is not None:
  2372. return rv
  2373. if (
  2374. self.allow_from_autoenv
  2375. and ctx.auto_envvar_prefix is not None
  2376. and self.name is not None
  2377. ):
  2378. envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}"
  2379. rv = os.environ.get(envvar)
  2380. if rv:
  2381. return rv
  2382. return None
  2383. def value_from_envvar(self, ctx: Context) -> t.Optional[t.Any]:
  2384. rv: t.Optional[t.Any] = self.resolve_envvar_value(ctx)
  2385. if rv is None:
  2386. return None
  2387. value_depth = (self.nargs != 1) + bool(self.multiple)
  2388. if value_depth > 0:
  2389. rv = self.type.split_envvar_value(rv)
  2390. if self.multiple and self.nargs != 1:
  2391. rv = batch(rv, self.nargs)
  2392. return rv
  2393. def consume_value(
  2394. self, ctx: Context, opts: t.Mapping[str, "Parameter"]
  2395. ) -> t.Tuple[t.Any, ParameterSource]:
  2396. value, source = super().consume_value(ctx, opts)
  2397. # The parser will emit a sentinel value if the option can be
  2398. # given as a flag without a value. This is different from None
  2399. # to distinguish from the flag not being given at all.
  2400. if value is _flag_needs_value:
  2401. if self.prompt is not None and not ctx.resilient_parsing:
  2402. value = self.prompt_for_value(ctx)
  2403. source = ParameterSource.PROMPT
  2404. else:
  2405. value = self.flag_value
  2406. source = ParameterSource.COMMANDLINE
  2407. elif (
  2408. self.multiple
  2409. and value is not None
  2410. and any(v is _flag_needs_value for v in value)
  2411. ):
  2412. value = [self.flag_value if v is _flag_needs_value else v for v in value]
  2413. source = ParameterSource.COMMANDLINE
  2414. # The value wasn't set, or used the param's default, prompt if
  2415. # prompting is enabled.
  2416. elif (
  2417. source in {None, ParameterSource.DEFAULT}
  2418. and self.prompt is not None
  2419. and (self.required or self.prompt_required)
  2420. and not ctx.resilient_parsing
  2421. ):
  2422. value = self.prompt_for_value(ctx)
  2423. source = ParameterSource.PROMPT
  2424. return value, source
  2425. class Argument(Parameter):
  2426. """Arguments are positional parameters to a command. They generally
  2427. provide fewer features than options but can have infinite ``nargs``
  2428. and are required by default.
  2429. All parameters are passed onwards to the constructor of :class:`Parameter`.
  2430. """
  2431. param_type_name = "argument"
  2432. def __init__(
  2433. self,
  2434. param_decls: t.Sequence[str],
  2435. required: t.Optional[bool] = None,
  2436. **attrs: t.Any,
  2437. ) -> None:
  2438. if required is None:
  2439. if attrs.get("default") is not None:
  2440. required = False
  2441. else:
  2442. required = attrs.get("nargs", 1) > 0
  2443. if "multiple" in attrs:
  2444. raise TypeError("__init__() got an unexpected keyword argument 'multiple'.")
  2445. super().__init__(param_decls, required=required, **attrs)
  2446. if __debug__:
  2447. if self.default is not None and self.nargs == -1:
  2448. raise TypeError("'default' is not supported for nargs=-1.")
  2449. @property
  2450. def human_readable_name(self) -> str:
  2451. if self.metavar is not None:
  2452. return self.metavar
  2453. return self.name.upper() # type: ignore
  2454. def make_metavar(self) -> str:
  2455. if self.metavar is not None:
  2456. return self.metavar
  2457. var = self.type.get_metavar(self)
  2458. if not var:
  2459. var = self.name.upper() # type: ignore
  2460. if not self.required:
  2461. var = f"[{var}]"
  2462. if self.nargs != 1:
  2463. var += "..."
  2464. return var
  2465. def _parse_decls(
  2466. self, decls: t.Sequence[str], expose_value: bool
  2467. ) -> t.Tuple[t.Optional[str], t.List[str], t.List[str]]:
  2468. if not decls:
  2469. if not expose_value:
  2470. return None, [], []
  2471. raise TypeError("Could not determine name for argument")
  2472. if len(decls) == 1:
  2473. name = arg = decls[0]
  2474. name = name.replace("-", "_").lower()
  2475. else:
  2476. raise TypeError(
  2477. "Arguments take exactly one parameter declaration, got"
  2478. f" {len(decls)}."
  2479. )
  2480. return name, [arg], []
  2481. def get_usage_pieces(self, ctx: Context) -> t.List[str]:
  2482. return [self.make_metavar()]
  2483. def get_error_hint(self, ctx: Context) -> str:
  2484. return f"'{self.make_metavar()}'"
  2485. def add_to_parser(self, parser: OptionParser, ctx: Context) -> None:
  2486. parser.add_argument(dest=self.name, nargs=self.nargs, obj=self)