core.py 110 KB

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