core.py 126 KB

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