core.py 109 KB

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