core.py 144 KB

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