core.py 112 KB

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