core.py 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744
  1. import errno
  2. import os
  3. import sys
  4. from contextlib import contextmanager
  5. from itertools import repeat
  6. from functools import update_wrapper
  7. from .types import convert_type, IntRange, BOOL
  8. from .utils import make_str, make_default_short_help, echo, get_os_args
  9. from .exceptions import ClickException, UsageError, BadParameter, Abort, \
  10. MissingParameter
  11. from .termui import prompt, confirm
  12. from .formatting import HelpFormatter, join_options
  13. from .parser import OptionParser, split_opt
  14. from .globals import push_context, pop_context
  15. from ._compat import PY2, isidentifier, iteritems
  16. from ._unicodefun import _check_for_unicode_literals, _verify_python3_env
  17. _missing = object()
  18. SUBCOMMAND_METAVAR = 'COMMAND [ARGS]...'
  19. SUBCOMMANDS_METAVAR = 'COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]...'
  20. def _bashcomplete(cmd, prog_name, complete_var=None):
  21. """Internal handler for the bash completion support."""
  22. if complete_var is None:
  23. complete_var = '_%s_COMPLETE' % (prog_name.replace('-', '_')).upper()
  24. complete_instr = os.environ.get(complete_var)
  25. if not complete_instr:
  26. return
  27. from ._bashcomplete import bashcomplete
  28. if bashcomplete(cmd, prog_name, complete_var, complete_instr):
  29. sys.exit(1)
  30. def _check_multicommand(base_command, cmd_name, cmd, register=False):
  31. if not base_command.chain or not isinstance(cmd, MultiCommand):
  32. return
  33. if register:
  34. hint = 'It is not possible to add multi commands as children to ' \
  35. 'another multi command that is in chain mode'
  36. else:
  37. hint = 'Found a multi command as subcommand to a multi command ' \
  38. 'that is in chain mode. This is not supported'
  39. raise RuntimeError('%s. Command "%s" is set to chain and "%s" was '
  40. 'added as subcommand but it in itself is a '
  41. 'multi command. ("%s" is a %s within a chained '
  42. '%s named "%s"). This restriction was supposed to '
  43. 'be lifted in 6.0 but the fix was flawed. This '
  44. 'will be fixed in Click 7.0' % (
  45. hint, base_command.name, cmd_name,
  46. cmd_name, cmd.__class__.__name__,
  47. base_command.__class__.__name__,
  48. base_command.name))
  49. def batch(iterable, batch_size):
  50. return list(zip(*repeat(iter(iterable), batch_size)))
  51. def invoke_param_callback(callback, ctx, param, value):
  52. code = getattr(callback, '__code__', None)
  53. args = getattr(code, 'co_argcount', 3)
  54. if args < 3:
  55. # This will become a warning in Click 3.0:
  56. from warnings import warn
  57. warn(Warning('Invoked legacy parameter callback "%s". The new '
  58. 'signature for such callbacks starting with '
  59. 'click 2.0 is (ctx, param, value).'
  60. % callback), stacklevel=3)
  61. return callback(ctx, value)
  62. return callback(ctx, param, value)
  63. @contextmanager
  64. def augment_usage_errors(ctx, param=None):
  65. """Context manager that attaches extra information to exceptions that
  66. fly.
  67. """
  68. try:
  69. yield
  70. except BadParameter as e:
  71. if e.ctx is None:
  72. e.ctx = ctx
  73. if param is not None and e.param is None:
  74. e.param = param
  75. raise
  76. except UsageError as e:
  77. if e.ctx is None:
  78. e.ctx = ctx
  79. raise
  80. def iter_params_for_processing(invocation_order, declaration_order):
  81. """Given a sequence of parameters in the order as should be considered
  82. for processing and an iterable of parameters that exist, this returns
  83. a list in the correct order as they should be processed.
  84. """
  85. def sort_key(item):
  86. try:
  87. idx = invocation_order.index(item)
  88. except ValueError:
  89. idx = float('inf')
  90. return (not item.is_eager, idx)
  91. return sorted(declaration_order, key=sort_key)
  92. class Context(object):
  93. """The context is a special internal object that holds state relevant
  94. for the script execution at every single level. It's normally invisible
  95. to commands unless they opt-in to getting access to it.
  96. The context is useful as it can pass internal objects around and can
  97. control special execution features such as reading data from
  98. environment variables.
  99. A context can be used as context manager in which case it will call
  100. :meth:`close` on teardown.
  101. .. versionadded:: 2.0
  102. Added the `resilient_parsing`, `help_option_names`,
  103. `token_normalize_func` parameters.
  104. .. versionadded:: 3.0
  105. Added the `allow_extra_args` and `allow_interspersed_args`
  106. parameters.
  107. .. versionadded:: 4.0
  108. Added the `color`, `ignore_unknown_options`, and
  109. `max_content_width` parameters.
  110. :param command: the command class for this context.
  111. :param parent: the parent context.
  112. :param info_name: the info name for this invocation. Generally this
  113. is the most descriptive name for the script or
  114. command. For the toplevel script it is usually
  115. the name of the script, for commands below it it's
  116. the name of the script.
  117. :param obj: an arbitrary object of user data.
  118. :param auto_envvar_prefix: the prefix to use for automatic environment
  119. variables. If this is `None` then reading
  120. from environment variables is disabled. This
  121. does not affect manually set environment
  122. variables which are always read.
  123. :param default_map: a dictionary (like object) with default values
  124. for parameters.
  125. :param terminal_width: the width of the terminal. The default is
  126. inherit from parent context. If no context
  127. defines the terminal width then auto
  128. detection will be applied.
  129. :param max_content_width: the maximum width for content rendered by
  130. Click (this currently only affects help
  131. pages). This defaults to 80 characters if
  132. not overridden. In other words: even if the
  133. terminal is larger than that, Click will not
  134. format things wider than 80 characters by
  135. default. In addition to that, formatters might
  136. add some safety mapping on the right.
  137. :param resilient_parsing: if this flag is enabled then Click will
  138. parse without any interactivity or callback
  139. invocation. This is useful for implementing
  140. things such as completion support.
  141. :param allow_extra_args: if this is set to `True` then extra arguments
  142. at the end will not raise an error and will be
  143. kept on the context. The default is to inherit
  144. from the command.
  145. :param allow_interspersed_args: if this is set to `False` then options
  146. and arguments cannot be mixed. The
  147. default is to inherit from the command.
  148. :param ignore_unknown_options: instructs click to ignore options it does
  149. not know and keeps them for later
  150. processing.
  151. :param help_option_names: optionally a list of strings that define how
  152. the default help parameter is named. The
  153. default is ``['--help']``.
  154. :param token_normalize_func: an optional function that is used to
  155. normalize tokens (options, choices,
  156. etc.). This for instance can be used to
  157. implement case insensitive behavior.
  158. :param color: controls if the terminal supports ANSI colors or not. The
  159. default is autodetection. This is only needed if ANSI
  160. codes are used in texts that Click prints which is by
  161. default not the case. This for instance would affect
  162. help output.
  163. """
  164. def __init__(self, command, parent=None, info_name=None, obj=None,
  165. auto_envvar_prefix=None, default_map=None,
  166. terminal_width=None, max_content_width=None,
  167. resilient_parsing=False, allow_extra_args=None,
  168. allow_interspersed_args=None,
  169. ignore_unknown_options=None, help_option_names=None,
  170. token_normalize_func=None, color=None):
  171. #: the parent context or `None` if none exists.
  172. self.parent = parent
  173. #: the :class:`Command` for this context.
  174. self.command = command
  175. #: the descriptive information name
  176. self.info_name = info_name
  177. #: the parsed parameters except if the value is hidden in which
  178. #: case it's not remembered.
  179. self.params = {}
  180. #: the leftover arguments.
  181. self.args = []
  182. #: protected arguments. These are arguments that are prepended
  183. #: to `args` when certain parsing scenarios are encountered but
  184. #: must be never propagated to another arguments. This is used
  185. #: to implement nested parsing.
  186. self.protected_args = []
  187. if obj is None and parent is not None:
  188. obj = parent.obj
  189. #: the user object stored.
  190. self.obj = obj
  191. self._meta = getattr(parent, 'meta', {})
  192. #: A dictionary (-like object) with defaults for parameters.
  193. if default_map is None \
  194. and parent is not None \
  195. and parent.default_map is not None:
  196. default_map = parent.default_map.get(info_name)
  197. self.default_map = default_map
  198. #: This flag indicates if a subcommand is going to be executed. A
  199. #: group callback can use this information to figure out if it's
  200. #: being executed directly or because the execution flow passes
  201. #: onwards to a subcommand. By default it's None, but it can be
  202. #: the name of the subcommand to execute.
  203. #:
  204. #: If chaining is enabled this will be set to ``'*'`` in case
  205. #: any commands are executed. It is however not possible to
  206. #: figure out which ones. If you require this knowledge you
  207. #: should use a :func:`resultcallback`.
  208. self.invoked_subcommand = None
  209. if terminal_width is None and parent is not None:
  210. terminal_width = parent.terminal_width
  211. #: The width of the terminal (None is autodetection).
  212. self.terminal_width = terminal_width
  213. if max_content_width is None and parent is not None:
  214. max_content_width = parent.max_content_width
  215. #: The maximum width of formatted content (None implies a sensible
  216. #: default which is 80 for most things).
  217. self.max_content_width = max_content_width
  218. if allow_extra_args is None:
  219. allow_extra_args = command.allow_extra_args
  220. #: Indicates if the context allows extra args or if it should
  221. #: fail on parsing.
  222. #:
  223. #: .. versionadded:: 3.0
  224. self.allow_extra_args = allow_extra_args
  225. if allow_interspersed_args is None:
  226. allow_interspersed_args = command.allow_interspersed_args
  227. #: Indicates if the context allows mixing of arguments and
  228. #: options or not.
  229. #:
  230. #: .. versionadded:: 3.0
  231. self.allow_interspersed_args = allow_interspersed_args
  232. if ignore_unknown_options is None:
  233. ignore_unknown_options = command.ignore_unknown_options
  234. #: Instructs click to ignore options that a command does not
  235. #: understand and will store it on the context for later
  236. #: processing. This is primarily useful for situations where you
  237. #: want to call into external programs. Generally this pattern is
  238. #: strongly discouraged because it's not possibly to losslessly
  239. #: forward all arguments.
  240. #:
  241. #: .. versionadded:: 4.0
  242. self.ignore_unknown_options = ignore_unknown_options
  243. if help_option_names is None:
  244. if parent is not None:
  245. help_option_names = parent.help_option_names
  246. else:
  247. help_option_names = ['--help']
  248. #: The names for the help options.
  249. self.help_option_names = help_option_names
  250. if token_normalize_func is None and parent is not None:
  251. token_normalize_func = parent.token_normalize_func
  252. #: An optional normalization function for tokens. This is
  253. #: options, choices, commands etc.
  254. self.token_normalize_func = token_normalize_func
  255. #: Indicates if resilient parsing is enabled. In that case Click
  256. #: will do its best to not cause any failures.
  257. self.resilient_parsing = resilient_parsing
  258. # If there is no envvar prefix yet, but the parent has one and
  259. # the command on this level has a name, we can expand the envvar
  260. # prefix automatically.
  261. if auto_envvar_prefix is None:
  262. if parent is not None \
  263. and parent.auto_envvar_prefix is not None and \
  264. self.info_name is not None:
  265. auto_envvar_prefix = '%s_%s' % (parent.auto_envvar_prefix,
  266. self.info_name.upper())
  267. else:
  268. self.auto_envvar_prefix = auto_envvar_prefix.upper()
  269. self.auto_envvar_prefix = auto_envvar_prefix
  270. if color is None and parent is not None:
  271. color = parent.color
  272. #: Controls if styling output is wanted or not.
  273. self.color = color
  274. self._close_callbacks = []
  275. self._depth = 0
  276. def __enter__(self):
  277. self._depth += 1
  278. push_context(self)
  279. return self
  280. def __exit__(self, exc_type, exc_value, tb):
  281. self._depth -= 1
  282. if self._depth == 0:
  283. self.close()
  284. pop_context()
  285. @contextmanager
  286. def scope(self, cleanup=True):
  287. """This helper method can be used with the context object to promote
  288. it to the current thread local (see :func:`get_current_context`).
  289. The default behavior of this is to invoke the cleanup functions which
  290. can be disabled by setting `cleanup` to `False`. The cleanup
  291. functions are typically used for things such as closing file handles.
  292. If the cleanup is intended the context object can also be directly
  293. used as a context manager.
  294. Example usage::
  295. with ctx.scope():
  296. assert get_current_context() is ctx
  297. This is equivalent::
  298. with ctx:
  299. assert get_current_context() is ctx
  300. .. versionadded:: 5.0
  301. :param cleanup: controls if the cleanup functions should be run or
  302. not. The default is to run these functions. In
  303. some situations the context only wants to be
  304. temporarily pushed in which case this can be disabled.
  305. Nested pushes automatically defer the cleanup.
  306. """
  307. if not cleanup:
  308. self._depth += 1
  309. try:
  310. with self as rv:
  311. yield rv
  312. finally:
  313. if not cleanup:
  314. self._depth -= 1
  315. @property
  316. def meta(self):
  317. """This is a dictionary which is shared with all the contexts
  318. that are nested. It exists so that click utiltiies can store some
  319. state here if they need to. It is however the responsibility of
  320. that code to manage this dictionary well.
  321. The keys are supposed to be unique dotted strings. For instance
  322. module paths are a good choice for it. What is stored in there is
  323. irrelevant for the operation of click. However what is important is
  324. that code that places data here adheres to the general semantics of
  325. the system.
  326. Example usage::
  327. LANG_KEY = __name__ + '.lang'
  328. def set_language(value):
  329. ctx = get_current_context()
  330. ctx.meta[LANG_KEY] = value
  331. def get_language():
  332. return get_current_context().meta.get(LANG_KEY, 'en_US')
  333. .. versionadded:: 5.0
  334. """
  335. return self._meta
  336. def make_formatter(self):
  337. """Creates the formatter for the help and usage output."""
  338. return HelpFormatter(width=self.terminal_width,
  339. max_width=self.max_content_width)
  340. def call_on_close(self, f):
  341. """This decorator remembers a function as callback that should be
  342. executed when the context tears down. This is most useful to bind
  343. resource handling to the script execution. For instance, file objects
  344. opened by the :class:`File` type will register their close callbacks
  345. here.
  346. :param f: the function to execute on teardown.
  347. """
  348. self._close_callbacks.append(f)
  349. return f
  350. def close(self):
  351. """Invokes all close callbacks."""
  352. for cb in self._close_callbacks:
  353. cb()
  354. self._close_callbacks = []
  355. @property
  356. def command_path(self):
  357. """The computed command path. This is used for the ``usage``
  358. information on the help page. It's automatically created by
  359. combining the info names of the chain of contexts to the root.
  360. """
  361. rv = ''
  362. if self.info_name is not None:
  363. rv = self.info_name
  364. if self.parent is not None:
  365. rv = self.parent.command_path + ' ' + rv
  366. return rv.lstrip()
  367. def find_root(self):
  368. """Finds the outermost context."""
  369. node = self
  370. while node.parent is not None:
  371. node = node.parent
  372. return node
  373. def find_object(self, object_type):
  374. """Finds the closest object of a given type."""
  375. node = self
  376. while node is not None:
  377. if isinstance(node.obj, object_type):
  378. return node.obj
  379. node = node.parent
  380. def ensure_object(self, object_type):
  381. """Like :meth:`find_object` but sets the innermost object to a
  382. new instance of `object_type` if it does not exist.
  383. """
  384. rv = self.find_object(object_type)
  385. if rv is None:
  386. self.obj = rv = object_type()
  387. return rv
  388. def lookup_default(self, name):
  389. """Looks up the default for a parameter name. This by default
  390. looks into the :attr:`default_map` if available.
  391. """
  392. if self.default_map is not None:
  393. rv = self.default_map.get(name)
  394. if callable(rv):
  395. rv = rv()
  396. return rv
  397. def fail(self, message):
  398. """Aborts the execution of the program with a specific error
  399. message.
  400. :param message: the error message to fail with.
  401. """
  402. raise UsageError(message, self)
  403. def abort(self):
  404. """Aborts the script."""
  405. raise Abort()
  406. def exit(self, code=0):
  407. """Exits the application with a given exit code."""
  408. sys.exit(code)
  409. def get_usage(self):
  410. """Helper method to get formatted usage string for the current
  411. context and command.
  412. """
  413. return self.command.get_usage(self)
  414. def get_help(self):
  415. """Helper method to get formatted help page for the current
  416. context and command.
  417. """
  418. return self.command.get_help(self)
  419. def invoke(*args, **kwargs):
  420. """Invokes a command callback in exactly the way it expects. There
  421. are two ways to invoke this method:
  422. 1. the first argument can be a callback and all other arguments and
  423. keyword arguments are forwarded directly to the function.
  424. 2. the first argument is a click command object. In that case all
  425. arguments are forwarded as well but proper click parameters
  426. (options and click arguments) must be keyword arguments and Click
  427. will fill in defaults.
  428. Note that before Click 3.2 keyword arguments were not properly filled
  429. in against the intention of this code and no context was created. For
  430. more information about this change and why it was done in a bugfix
  431. release see :ref:`upgrade-to-3.2`.
  432. """
  433. self, callback = args[:2]
  434. ctx = self
  435. # It's also possible to invoke another command which might or
  436. # might not have a callback. In that case we also fill
  437. # in defaults and make a new context for this command.
  438. if isinstance(callback, Command):
  439. other_cmd = callback
  440. callback = other_cmd.callback
  441. ctx = Context(other_cmd, info_name=other_cmd.name, parent=self)
  442. if callback is None:
  443. raise TypeError('The given command does not have a '
  444. 'callback that can be invoked.')
  445. for param in other_cmd.params:
  446. if param.name not in kwargs and param.expose_value:
  447. kwargs[param.name] = param.get_default(ctx)
  448. args = args[2:]
  449. with augment_usage_errors(self):
  450. with ctx:
  451. return callback(*args, **kwargs)
  452. def forward(*args, **kwargs):
  453. """Similar to :meth:`invoke` but fills in default keyword
  454. arguments from the current context if the other command expects
  455. it. This cannot invoke callbacks directly, only other commands.
  456. """
  457. self, cmd = args[:2]
  458. # It's also possible to invoke another command which might or
  459. # might not have a callback.
  460. if not isinstance(cmd, Command):
  461. raise TypeError('Callback is not a command.')
  462. for param in self.params:
  463. if param not in kwargs:
  464. kwargs[param] = self.params[param]
  465. return self.invoke(cmd, **kwargs)
  466. class BaseCommand(object):
  467. """The base command implements the minimal API contract of commands.
  468. Most code will never use this as it does not implement a lot of useful
  469. functionality but it can act as the direct subclass of alternative
  470. parsing methods that do not depend on the Click parser.
  471. For instance, this can be used to bridge Click and other systems like
  472. argparse or docopt.
  473. Because base commands do not implement a lot of the API that other
  474. parts of Click take for granted, they are not supported for all
  475. operations. For instance, they cannot be used with the decorators
  476. usually and they have no built-in callback system.
  477. .. versionchanged:: 2.0
  478. Added the `context_settings` parameter.
  479. :param name: the name of the command to use unless a group overrides it.
  480. :param context_settings: an optional dictionary with defaults that are
  481. passed to the context object.
  482. """
  483. #: the default for the :attr:`Context.allow_extra_args` flag.
  484. allow_extra_args = False
  485. #: the default for the :attr:`Context.allow_interspersed_args` flag.
  486. allow_interspersed_args = True
  487. #: the default for the :attr:`Context.ignore_unknown_options` flag.
  488. ignore_unknown_options = False
  489. def __init__(self, name, context_settings=None):
  490. #: the name the command thinks it has. Upon registering a command
  491. #: on a :class:`Group` the group will default the command name
  492. #: with this information. You should instead use the
  493. #: :class:`Context`\'s :attr:`~Context.info_name` attribute.
  494. self.name = name
  495. if context_settings is None:
  496. context_settings = {}
  497. #: an optional dictionary with defaults passed to the context.
  498. self.context_settings = context_settings
  499. def get_usage(self, ctx):
  500. raise NotImplementedError('Base commands cannot get usage')
  501. def get_help(self, ctx):
  502. raise NotImplementedError('Base commands cannot get help')
  503. def make_context(self, info_name, args, parent=None, **extra):
  504. """This function when given an info name and arguments will kick
  505. off the parsing and create a new :class:`Context`. It does not
  506. invoke the actual command callback though.
  507. :param info_name: the info name for this invokation. Generally this
  508. is the most descriptive name for the script or
  509. command. For the toplevel script it's usually
  510. the name of the script, for commands below it it's
  511. the name of the script.
  512. :param args: the arguments to parse as list of strings.
  513. :param parent: the parent context if available.
  514. :param extra: extra keyword arguments forwarded to the context
  515. constructor.
  516. """
  517. for key, value in iteritems(self.context_settings):
  518. if key not in extra:
  519. extra[key] = value
  520. ctx = Context(self, info_name=info_name, parent=parent, **extra)
  521. with ctx.scope(cleanup=False):
  522. self.parse_args(ctx, args)
  523. return ctx
  524. def parse_args(self, ctx, args):
  525. """Given a context and a list of arguments this creates the parser
  526. and parses the arguments, then modifies the context as necessary.
  527. This is automatically invoked by :meth:`make_context`.
  528. """
  529. raise NotImplementedError('Base commands do not know how to parse '
  530. 'arguments.')
  531. def invoke(self, ctx):
  532. """Given a context, this invokes the command. The default
  533. implementation is raising a not implemented error.
  534. """
  535. raise NotImplementedError('Base commands are not invokable by default')
  536. def main(self, args=None, prog_name=None, complete_var=None,
  537. standalone_mode=True, **extra):
  538. """This is the way to invoke a script with all the bells and
  539. whistles as a command line application. This will always terminate
  540. the application after a call. If this is not wanted, ``SystemExit``
  541. needs to be caught.
  542. This method is also available by directly calling the instance of
  543. a :class:`Command`.
  544. .. versionadded:: 3.0
  545. Added the `standalone_mode` flag to control the standalone mode.
  546. :param args: the arguments that should be used for parsing. If not
  547. provided, ``sys.argv[1:]`` is used.
  548. :param prog_name: the program name that should be used. By default
  549. the program name is constructed by taking the file
  550. name from ``sys.argv[0]``.
  551. :param complete_var: the environment variable that controls the
  552. bash completion support. The default is
  553. ``"_<prog_name>_COMPLETE"`` with prog name in
  554. uppercase.
  555. :param standalone_mode: the default behavior is to invoke the script
  556. in standalone mode. Click will then
  557. handle exceptions and convert them into
  558. error messages and the function will never
  559. return but shut down the interpreter. If
  560. this is set to `False` they will be
  561. propagated to the caller and the return
  562. value of this function is the return value
  563. of :meth:`invoke`.
  564. :param extra: extra keyword arguments are forwarded to the context
  565. constructor. See :class:`Context` for more information.
  566. """
  567. # If we are in Python 3, we will verify that the environment is
  568. # sane at this point of reject further execution to avoid a
  569. # broken script.
  570. if not PY2:
  571. _verify_python3_env()
  572. else:
  573. _check_for_unicode_literals()
  574. if args is None:
  575. args = get_os_args()
  576. else:
  577. args = list(args)
  578. if prog_name is None:
  579. prog_name = make_str(os.path.basename(
  580. sys.argv and sys.argv[0] or __file__))
  581. # Hook for the Bash completion. This only activates if the Bash
  582. # completion is actually enabled, otherwise this is quite a fast
  583. # noop.
  584. _bashcomplete(self, prog_name, complete_var)
  585. try:
  586. try:
  587. with self.make_context(prog_name, args, **extra) as ctx:
  588. rv = self.invoke(ctx)
  589. if not standalone_mode:
  590. return rv
  591. ctx.exit()
  592. except (EOFError, KeyboardInterrupt):
  593. echo(file=sys.stderr)
  594. raise Abort()
  595. except ClickException as e:
  596. if not standalone_mode:
  597. raise
  598. e.show()
  599. sys.exit(e.exit_code)
  600. except IOError as e:
  601. if e.errno == errno.EPIPE:
  602. sys.exit(1)
  603. else:
  604. raise
  605. except Abort:
  606. if not standalone_mode:
  607. raise
  608. echo('Aborted!', file=sys.stderr)
  609. sys.exit(1)
  610. def __call__(self, *args, **kwargs):
  611. """Alias for :meth:`main`."""
  612. return self.main(*args, **kwargs)
  613. class Command(BaseCommand):
  614. """Commands are the basic building block of command line interfaces in
  615. Click. A basic command handles command line parsing and might dispatch
  616. more parsing to commands nested below it.
  617. .. versionchanged:: 2.0
  618. Added the `context_settings` parameter.
  619. :param name: the name of the command to use unless a group overrides it.
  620. :param context_settings: an optional dictionary with defaults that are
  621. passed to the context object.
  622. :param callback: the callback to invoke. This is optional.
  623. :param params: the parameters to register with this command. This can
  624. be either :class:`Option` or :class:`Argument` objects.
  625. :param help: the help string to use for this command.
  626. :param epilog: like the help string but it's printed at the end of the
  627. help page after everything else.
  628. :param short_help: the short help to use for this command. This is
  629. shown on the command listing of the parent command.
  630. :param add_help_option: by default each command registers a ``--help``
  631. option. This can be disabled by this parameter.
  632. """
  633. def __init__(self, name, context_settings=None, callback=None,
  634. params=None, help=None, epilog=None, short_help=None,
  635. options_metavar='[OPTIONS]', add_help_option=True):
  636. BaseCommand.__init__(self, name, context_settings)
  637. #: the callback to execute when the command fires. This might be
  638. #: `None` in which case nothing happens.
  639. self.callback = callback
  640. #: the list of parameters for this command in the order they
  641. #: should show up in the help page and execute. Eager parameters
  642. #: will automatically be handled before non eager ones.
  643. self.params = params or []
  644. self.help = help
  645. self.epilog = epilog
  646. self.options_metavar = options_metavar
  647. if short_help is None and help:
  648. short_help = make_default_short_help(help)
  649. self.short_help = short_help
  650. self.add_help_option = add_help_option
  651. def get_usage(self, ctx):
  652. formatter = ctx.make_formatter()
  653. self.format_usage(ctx, formatter)
  654. return formatter.getvalue().rstrip('\n')
  655. def get_params(self, ctx):
  656. rv = self.params
  657. help_option = self.get_help_option(ctx)
  658. if help_option is not None:
  659. rv = rv + [help_option]
  660. return rv
  661. def format_usage(self, ctx, formatter):
  662. """Writes the usage line into the formatter."""
  663. pieces = self.collect_usage_pieces(ctx)
  664. formatter.write_usage(ctx.command_path, ' '.join(pieces))
  665. def collect_usage_pieces(self, ctx):
  666. """Returns all the pieces that go into the usage line and returns
  667. it as a list of strings.
  668. """
  669. rv = [self.options_metavar]
  670. for param in self.get_params(ctx):
  671. rv.extend(param.get_usage_pieces(ctx))
  672. return rv
  673. def get_help_option_names(self, ctx):
  674. """Returns the names for the help option."""
  675. all_names = set(ctx.help_option_names)
  676. for param in self.params:
  677. all_names.difference_update(param.opts)
  678. all_names.difference_update(param.secondary_opts)
  679. return all_names
  680. def get_help_option(self, ctx):
  681. """Returns the help option object."""
  682. help_options = self.get_help_option_names(ctx)
  683. if not help_options or not self.add_help_option:
  684. return
  685. def show_help(ctx, param, value):
  686. if value and not ctx.resilient_parsing:
  687. echo(ctx.get_help(), color=ctx.color)
  688. ctx.exit()
  689. return Option(help_options, is_flag=True,
  690. is_eager=True, expose_value=False,
  691. callback=show_help,
  692. help='Show this message and exit.')
  693. def make_parser(self, ctx):
  694. """Creates the underlying option parser for this command."""
  695. parser = OptionParser(ctx)
  696. parser.allow_interspersed_args = ctx.allow_interspersed_args
  697. parser.ignore_unknown_options = ctx.ignore_unknown_options
  698. for param in self.get_params(ctx):
  699. param.add_to_parser(parser, ctx)
  700. return parser
  701. def get_help(self, ctx):
  702. """Formats the help into a string and returns it. This creates a
  703. formatter and will call into the following formatting methods:
  704. """
  705. formatter = ctx.make_formatter()
  706. self.format_help(ctx, formatter)
  707. return formatter.getvalue().rstrip('\n')
  708. def format_help(self, ctx, formatter):
  709. """Writes the help into the formatter if it exists.
  710. This calls into the following methods:
  711. - :meth:`format_usage`
  712. - :meth:`format_help_text`
  713. - :meth:`format_options`
  714. - :meth:`format_epilog`
  715. """
  716. self.format_usage(ctx, formatter)
  717. self.format_help_text(ctx, formatter)
  718. self.format_options(ctx, formatter)
  719. self.format_epilog(ctx, formatter)
  720. def format_help_text(self, ctx, formatter):
  721. """Writes the help text to the formatter if it exists."""
  722. if self.help:
  723. formatter.write_paragraph()
  724. with formatter.indentation():
  725. formatter.write_text(self.help)
  726. def format_options(self, ctx, formatter):
  727. """Writes all the options into the formatter if they exist."""
  728. opts = []
  729. for param in self.get_params(ctx):
  730. rv = param.get_help_record(ctx)
  731. if rv is not None:
  732. opts.append(rv)
  733. if opts:
  734. with formatter.section('Options'):
  735. formatter.write_dl(opts)
  736. def format_epilog(self, ctx, formatter):
  737. """Writes the epilog into the formatter if it exists."""
  738. if self.epilog:
  739. formatter.write_paragraph()
  740. with formatter.indentation():
  741. formatter.write_text(self.epilog)
  742. def parse_args(self, ctx, args):
  743. parser = self.make_parser(ctx)
  744. opts, args, param_order = parser.parse_args(args=args)
  745. for param in iter_params_for_processing(
  746. param_order, self.get_params(ctx)):
  747. value, args = param.handle_parse_result(ctx, opts, args)
  748. if args and not ctx.allow_extra_args and not ctx.resilient_parsing:
  749. ctx.fail('Got unexpected extra argument%s (%s)'
  750. % (len(args) != 1 and 's' or '',
  751. ' '.join(map(make_str, args))))
  752. ctx.args = args
  753. return args
  754. def invoke(self, ctx):
  755. """Given a context, this invokes the attached callback (if it exists)
  756. in the right way.
  757. """
  758. if self.callback is not None:
  759. return ctx.invoke(self.callback, **ctx.params)
  760. class MultiCommand(Command):
  761. """A multi command is the basic implementation of a command that
  762. dispatches to subcommands. The most common version is the
  763. :class:`Group`.
  764. :param invoke_without_command: this controls how the multi command itself
  765. is invoked. By default it's only invoked
  766. if a subcommand is provided.
  767. :param no_args_is_help: this controls what happens if no arguments are
  768. provided. This option is enabled by default if
  769. `invoke_without_command` is disabled or disabled
  770. if it's enabled. If enabled this will add
  771. ``--help`` as argument if no arguments are
  772. passed.
  773. :param subcommand_metavar: the string that is used in the documentation
  774. to indicate the subcommand place.
  775. :param chain: if this is set to `True` chaining of multiple subcommands
  776. is enabled. This restricts the form of commands in that
  777. they cannot have optional arguments but it allows
  778. multiple commands to be chained together.
  779. :param result_callback: the result callback to attach to this multi
  780. command.
  781. """
  782. allow_extra_args = True
  783. allow_interspersed_args = False
  784. def __init__(self, name=None, invoke_without_command=False,
  785. no_args_is_help=None, subcommand_metavar=None,
  786. chain=False, result_callback=None, **attrs):
  787. Command.__init__(self, name, **attrs)
  788. if no_args_is_help is None:
  789. no_args_is_help = not invoke_without_command
  790. self.no_args_is_help = no_args_is_help
  791. self.invoke_without_command = invoke_without_command
  792. if subcommand_metavar is None:
  793. if chain:
  794. subcommand_metavar = SUBCOMMANDS_METAVAR
  795. else:
  796. subcommand_metavar = SUBCOMMAND_METAVAR
  797. self.subcommand_metavar = subcommand_metavar
  798. self.chain = chain
  799. #: The result callback that is stored. This can be set or
  800. #: overridden with the :func:`resultcallback` decorator.
  801. self.result_callback = result_callback
  802. if self.chain:
  803. for param in self.params:
  804. if isinstance(param, Argument) and not param.required:
  805. raise RuntimeError('Multi commands in chain mode cannot '
  806. 'have optional arguments.')
  807. def collect_usage_pieces(self, ctx):
  808. rv = Command.collect_usage_pieces(self, ctx)
  809. rv.append(self.subcommand_metavar)
  810. return rv
  811. def format_options(self, ctx, formatter):
  812. Command.format_options(self, ctx, formatter)
  813. self.format_commands(ctx, formatter)
  814. def resultcallback(self, replace=False):
  815. """Adds a result callback to the chain command. By default if a
  816. result callback is already registered this will chain them but
  817. this can be disabled with the `replace` parameter. The result
  818. callback is invoked with the return value of the subcommand
  819. (or the list of return values from all subcommands if chaining
  820. is enabled) as well as the parameters as they would be passed
  821. to the main callback.
  822. Example::
  823. @click.group()
  824. @click.option('-i', '--input', default=23)
  825. def cli(input):
  826. return 42
  827. @cli.resultcallback()
  828. def process_result(result, input):
  829. return result + input
  830. .. versionadded:: 3.0
  831. :param replace: if set to `True` an already existing result
  832. callback will be removed.
  833. """
  834. def decorator(f):
  835. old_callback = self.result_callback
  836. if old_callback is None or replace:
  837. self.result_callback = f
  838. return f
  839. def function(__value, *args, **kwargs):
  840. return f(old_callback(__value, *args, **kwargs),
  841. *args, **kwargs)
  842. self.result_callback = rv = update_wrapper(function, f)
  843. return rv
  844. return decorator
  845. def format_commands(self, ctx, formatter):
  846. """Extra format methods for multi methods that adds all the commands
  847. after the options.
  848. """
  849. rows = []
  850. for subcommand in self.list_commands(ctx):
  851. cmd = self.get_command(ctx, subcommand)
  852. # What is this, the tool lied about a command. Ignore it
  853. if cmd is None:
  854. continue
  855. help = cmd.short_help or ''
  856. rows.append((subcommand, help))
  857. if rows:
  858. with formatter.section('Commands'):
  859. formatter.write_dl(rows)
  860. def parse_args(self, ctx, args):
  861. if not args and self.no_args_is_help and not ctx.resilient_parsing:
  862. echo(ctx.get_help(), color=ctx.color)
  863. ctx.exit()
  864. rest = Command.parse_args(self, ctx, args)
  865. if self.chain:
  866. ctx.protected_args = rest
  867. ctx.args = []
  868. elif rest:
  869. ctx.protected_args, ctx.args = rest[:1], rest[1:]
  870. return ctx.args
  871. def invoke(self, ctx):
  872. def _process_result(value):
  873. if self.result_callback is not None:
  874. value = ctx.invoke(self.result_callback, value,
  875. **ctx.params)
  876. return value
  877. if not ctx.protected_args:
  878. # If we are invoked without command the chain flag controls
  879. # how this happens. If we are not in chain mode, the return
  880. # value here is the return value of the command.
  881. # If however we are in chain mode, the return value is the
  882. # return value of the result processor invoked with an empty
  883. # list (which means that no subcommand actually was executed).
  884. if self.invoke_without_command:
  885. if not self.chain:
  886. return Command.invoke(self, ctx)
  887. with ctx:
  888. Command.invoke(self, ctx)
  889. return _process_result([])
  890. ctx.fail('Missing command.')
  891. # Fetch args back out
  892. args = ctx.protected_args + ctx.args
  893. ctx.args = []
  894. ctx.protected_args = []
  895. # If we're not in chain mode, we only allow the invocation of a
  896. # single command but we also inform the current context about the
  897. # name of the command to invoke.
  898. if not self.chain:
  899. # Make sure the context is entered so we do not clean up
  900. # resources until the result processor has worked.
  901. with ctx:
  902. cmd_name, cmd, args = self.resolve_command(ctx, args)
  903. ctx.invoked_subcommand = cmd_name
  904. Command.invoke(self, ctx)
  905. sub_ctx = cmd.make_context(cmd_name, args, parent=ctx)
  906. with sub_ctx:
  907. return _process_result(sub_ctx.command.invoke(sub_ctx))
  908. # In chain mode we create the contexts step by step, but after the
  909. # base command has been invoked. Because at that point we do not
  910. # know the subcommands yet, the invoked subcommand attribute is
  911. # set to ``*`` to inform the command that subcommands are executed
  912. # but nothing else.
  913. with ctx:
  914. ctx.invoked_subcommand = args and '*' or None
  915. Command.invoke(self, ctx)
  916. # Otherwise we make every single context and invoke them in a
  917. # chain. In that case the return value to the result processor
  918. # is the list of all invoked subcommand's results.
  919. contexts = []
  920. while args:
  921. cmd_name, cmd, args = self.resolve_command(ctx, args)
  922. sub_ctx = cmd.make_context(cmd_name, args, parent=ctx,
  923. allow_extra_args=True,
  924. allow_interspersed_args=False)
  925. contexts.append(sub_ctx)
  926. args, sub_ctx.args = sub_ctx.args, []
  927. rv = []
  928. for sub_ctx in contexts:
  929. with sub_ctx:
  930. rv.append(sub_ctx.command.invoke(sub_ctx))
  931. return _process_result(rv)
  932. def resolve_command(self, ctx, args):
  933. cmd_name = make_str(args[0])
  934. original_cmd_name = cmd_name
  935. # Get the command
  936. cmd = self.get_command(ctx, cmd_name)
  937. # If we can't find the command but there is a normalization
  938. # function available, we try with that one.
  939. if cmd is None and ctx.token_normalize_func is not None:
  940. cmd_name = ctx.token_normalize_func(cmd_name)
  941. cmd = self.get_command(ctx, cmd_name)
  942. # If we don't find the command we want to show an error message
  943. # to the user that it was not provided. However, there is
  944. # something else we should do: if the first argument looks like
  945. # an option we want to kick off parsing again for arguments to
  946. # resolve things like --help which now should go to the main
  947. # place.
  948. if cmd is None:
  949. if split_opt(cmd_name)[0]:
  950. self.parse_args(ctx, ctx.args)
  951. ctx.fail('No such command "%s".' % original_cmd_name)
  952. return cmd_name, cmd, args[1:]
  953. def get_command(self, ctx, cmd_name):
  954. """Given a context and a command name, this returns a
  955. :class:`Command` object if it exists or returns `None`.
  956. """
  957. raise NotImplementedError()
  958. def list_commands(self, ctx):
  959. """Returns a list of subcommand names in the order they should
  960. appear.
  961. """
  962. return []
  963. class Group(MultiCommand):
  964. """A group allows a command to have subcommands attached. This is the
  965. most common way to implement nesting in Click.
  966. :param commands: a dictionary of commands.
  967. """
  968. def __init__(self, name=None, commands=None, **attrs):
  969. MultiCommand.__init__(self, name, **attrs)
  970. #: the registered subcommands by their exported names.
  971. self.commands = commands or {}
  972. def add_command(self, cmd, name=None):
  973. """Registers another :class:`Command` with this group. If the name
  974. is not provided, the name of the command is used.
  975. """
  976. name = name or cmd.name
  977. if name is None:
  978. raise TypeError('Command has no name.')
  979. _check_multicommand(self, name, cmd, register=True)
  980. self.commands[name] = cmd
  981. def command(self, *args, **kwargs):
  982. """A shortcut decorator for declaring and attaching a command to
  983. the group. This takes the same arguments as :func:`command` but
  984. immediately registers the created command with this instance by
  985. calling into :meth:`add_command`.
  986. """
  987. def decorator(f):
  988. cmd = command(*args, **kwargs)(f)
  989. self.add_command(cmd)
  990. return cmd
  991. return decorator
  992. def group(self, *args, **kwargs):
  993. """A shortcut decorator for declaring and attaching a group to
  994. the group. This takes the same arguments as :func:`group` but
  995. immediately registers the created command with this instance by
  996. calling into :meth:`add_command`.
  997. """
  998. def decorator(f):
  999. cmd = group(*args, **kwargs)(f)
  1000. self.add_command(cmd)
  1001. return cmd
  1002. return decorator
  1003. def get_command(self, ctx, cmd_name):
  1004. return self.commands.get(cmd_name)
  1005. def list_commands(self, ctx):
  1006. return sorted(self.commands)
  1007. class CommandCollection(MultiCommand):
  1008. """A command collection is a multi command that merges multiple multi
  1009. commands together into one. This is a straightforward implementation
  1010. that accepts a list of different multi commands as sources and
  1011. provides all the commands for each of them.
  1012. """
  1013. def __init__(self, name=None, sources=None, **attrs):
  1014. MultiCommand.__init__(self, name, **attrs)
  1015. #: The list of registered multi commands.
  1016. self.sources = sources or []
  1017. def add_source(self, multi_cmd):
  1018. """Adds a new multi command to the chain dispatcher."""
  1019. self.sources.append(multi_cmd)
  1020. def get_command(self, ctx, cmd_name):
  1021. for source in self.sources:
  1022. rv = source.get_command(ctx, cmd_name)
  1023. if rv is not None:
  1024. if self.chain:
  1025. _check_multicommand(self, cmd_name, rv)
  1026. return rv
  1027. def list_commands(self, ctx):
  1028. rv = set()
  1029. for source in self.sources:
  1030. rv.update(source.list_commands(ctx))
  1031. return sorted(rv)
  1032. class Parameter(object):
  1033. """A parameter to a command comes in two versions: they are either
  1034. :class:`Option`\s or :class:`Argument`\s. Other subclasses are currently
  1035. not supported by design as some of the internals for parsing are
  1036. intentionally not finalized.
  1037. Some settings are supported by both options and arguments.
  1038. .. versionchanged:: 2.0
  1039. Changed signature for parameter callback to also be passed the
  1040. parameter. In Click 2.0, the old callback format will still work,
  1041. but it will raise a warning to give you change to migrate the
  1042. code easier.
  1043. :param param_decls: the parameter declarations for this option or
  1044. argument. This is a list of flags or argument
  1045. names.
  1046. :param type: the type that should be used. Either a :class:`ParamType`
  1047. or a Python type. The later is converted into the former
  1048. automatically if supported.
  1049. :param required: controls if this is optional or not.
  1050. :param default: the default value if omitted. This can also be a callable,
  1051. in which case it's invoked when the default is needed
  1052. without any arguments.
  1053. :param callback: a callback that should be executed after the parameter
  1054. was matched. This is called as ``fn(ctx, param,
  1055. value)`` and needs to return the value. Before Click
  1056. 2.0, the signature was ``(ctx, value)``.
  1057. :param nargs: the number of arguments to match. If not ``1`` the return
  1058. value is a tuple instead of single value. The default for
  1059. nargs is ``1`` (except if the type is a tuple, then it's
  1060. the arity of the tuple).
  1061. :param metavar: how the value is represented in the help page.
  1062. :param expose_value: if this is `True` then the value is passed onwards
  1063. to the command callback and stored on the context,
  1064. otherwise it's skipped.
  1065. :param is_eager: eager values are processed before non eager ones. This
  1066. should not be set for arguments or it will inverse the
  1067. order of processing.
  1068. :param envvar: a string or list of strings that are environment variables
  1069. that should be checked.
  1070. """
  1071. param_type_name = 'parameter'
  1072. def __init__(self, param_decls=None, type=None, required=False,
  1073. default=None, callback=None, nargs=None, metavar=None,
  1074. expose_value=True, is_eager=False, envvar=None):
  1075. self.name, self.opts, self.secondary_opts = \
  1076. self._parse_decls(param_decls or (), expose_value)
  1077. self.type = convert_type(type, default)
  1078. # Default nargs to what the type tells us if we have that
  1079. # information available.
  1080. if nargs is None:
  1081. if self.type.is_composite:
  1082. nargs = self.type.arity
  1083. else:
  1084. nargs = 1
  1085. self.required = required
  1086. self.callback = callback
  1087. self.nargs = nargs
  1088. self.multiple = False
  1089. self.expose_value = expose_value
  1090. self.default = default
  1091. self.is_eager = is_eager
  1092. self.metavar = metavar
  1093. self.envvar = envvar
  1094. @property
  1095. def human_readable_name(self):
  1096. """Returns the human readable name of this parameter. This is the
  1097. same as the name for options, but the metavar for arguments.
  1098. """
  1099. return self.name
  1100. def make_metavar(self):
  1101. if self.metavar is not None:
  1102. return self.metavar
  1103. metavar = self.type.get_metavar(self)
  1104. if metavar is None:
  1105. metavar = self.type.name.upper()
  1106. if self.nargs != 1:
  1107. metavar += '...'
  1108. return metavar
  1109. def get_default(self, ctx):
  1110. """Given a context variable this calculates the default value."""
  1111. # Otherwise go with the regular default.
  1112. if callable(self.default):
  1113. rv = self.default()
  1114. else:
  1115. rv = self.default
  1116. return self.type_cast_value(ctx, rv)
  1117. def add_to_parser(self, parser, ctx):
  1118. pass
  1119. def consume_value(self, ctx, opts):
  1120. value = opts.get(self.name)
  1121. if value is None:
  1122. value = ctx.lookup_default(self.name)
  1123. if value is None:
  1124. value = self.value_from_envvar(ctx)
  1125. return value
  1126. def type_cast_value(self, ctx, value):
  1127. """Given a value this runs it properly through the type system.
  1128. This automatically handles things like `nargs` and `multiple` as
  1129. well as composite types.
  1130. """
  1131. if self.type.is_composite:
  1132. if self.nargs <= 1:
  1133. raise TypeError('Attempted to invoke composite type '
  1134. 'but nargs has been set to %s. This is '
  1135. 'not supported; nargs needs to be set to '
  1136. 'a fixed value > 1.' % self.nargs)
  1137. if self.multiple:
  1138. return tuple(self.type(x or (), self, ctx) for x in value or ())
  1139. return self.type(value or (), self, ctx)
  1140. def _convert(value, level):
  1141. if level == 0:
  1142. return self.type(value, self, ctx)
  1143. return tuple(_convert(x, level - 1) for x in value or ())
  1144. return _convert(value, (self.nargs != 1) + bool(self.multiple))
  1145. def process_value(self, ctx, value):
  1146. """Given a value and context this runs the logic to convert the
  1147. value as necessary.
  1148. """
  1149. # If the value we were given is None we do nothing. This way
  1150. # code that calls this can easily figure out if something was
  1151. # not provided. Otherwise it would be converted into an empty
  1152. # tuple for multiple invocations which is inconvenient.
  1153. if value is not None:
  1154. return self.type_cast_value(ctx, value)
  1155. def value_is_missing(self, value):
  1156. if value is None:
  1157. return True
  1158. if (self.nargs != 1 or self.multiple) and value == ():
  1159. return True
  1160. return False
  1161. def full_process_value(self, ctx, value):
  1162. value = self.process_value(ctx, value)
  1163. if value is None:
  1164. value = self.get_default(ctx)
  1165. if self.required and self.value_is_missing(value):
  1166. raise MissingParameter(ctx=ctx, param=self)
  1167. return value
  1168. def resolve_envvar_value(self, ctx):
  1169. if self.envvar is None:
  1170. return
  1171. if isinstance(self.envvar, (tuple, list)):
  1172. for envvar in self.envvar:
  1173. rv = os.environ.get(envvar)
  1174. if rv is not None:
  1175. return rv
  1176. else:
  1177. return os.environ.get(self.envvar)
  1178. def value_from_envvar(self, ctx):
  1179. rv = self.resolve_envvar_value(ctx)
  1180. if rv is not None and self.nargs != 1:
  1181. rv = self.type.split_envvar_value(rv)
  1182. return rv
  1183. def handle_parse_result(self, ctx, opts, args):
  1184. with augment_usage_errors(ctx, param=self):
  1185. value = self.consume_value(ctx, opts)
  1186. try:
  1187. value = self.full_process_value(ctx, value)
  1188. except Exception:
  1189. if not ctx.resilient_parsing:
  1190. raise
  1191. value = None
  1192. if self.callback is not None:
  1193. try:
  1194. value = invoke_param_callback(
  1195. self.callback, ctx, self, value)
  1196. except Exception:
  1197. if not ctx.resilient_parsing:
  1198. raise
  1199. if self.expose_value:
  1200. ctx.params[self.name] = value
  1201. return value, args
  1202. def get_help_record(self, ctx):
  1203. pass
  1204. def get_usage_pieces(self, ctx):
  1205. return []
  1206. class Option(Parameter):
  1207. """Options are usually optional values on the command line and
  1208. have some extra features that arguments don't have.
  1209. All other parameters are passed onwards to the parameter constructor.
  1210. :param show_default: controls if the default value should be shown on the
  1211. help page. Normally, defaults are not shown.
  1212. :param prompt: if set to `True` or a non empty string then the user will
  1213. be prompted for input if not set. If set to `True` the
  1214. prompt will be the option name capitalized.
  1215. :param confirmation_prompt: if set then the value will need to be confirmed
  1216. if it was prompted for.
  1217. :param hide_input: if this is `True` then the input on the prompt will be
  1218. hidden from the user. This is useful for password
  1219. input.
  1220. :param is_flag: forces this option to act as a flag. The default is
  1221. auto detection.
  1222. :param flag_value: which value should be used for this flag if it's
  1223. enabled. This is set to a boolean automatically if
  1224. the option string contains a slash to mark two options.
  1225. :param multiple: if this is set to `True` then the argument is accepted
  1226. multiple times and recorded. This is similar to ``nargs``
  1227. in how it works but supports arbitrary number of
  1228. arguments.
  1229. :param count: this flag makes an option increment an integer.
  1230. :param allow_from_autoenv: if this is enabled then the value of this
  1231. parameter will be pulled from an environment
  1232. variable in case a prefix is defined on the
  1233. context.
  1234. :param help: the help string.
  1235. """
  1236. param_type_name = 'option'
  1237. def __init__(self, param_decls=None, show_default=False,
  1238. prompt=False, confirmation_prompt=False,
  1239. hide_input=False, is_flag=None, flag_value=None,
  1240. multiple=False, count=False, allow_from_autoenv=True,
  1241. type=None, help=None, **attrs):
  1242. default_is_missing = attrs.get('default', _missing) is _missing
  1243. Parameter.__init__(self, param_decls, type=type, **attrs)
  1244. if prompt is True:
  1245. prompt_text = self.name.replace('_', ' ').capitalize()
  1246. elif prompt is False:
  1247. prompt_text = None
  1248. else:
  1249. prompt_text = prompt
  1250. self.prompt = prompt_text
  1251. self.confirmation_prompt = confirmation_prompt
  1252. self.hide_input = hide_input
  1253. # Flags
  1254. if is_flag is None:
  1255. if flag_value is not None:
  1256. is_flag = True
  1257. else:
  1258. is_flag = bool(self.secondary_opts)
  1259. if is_flag and default_is_missing:
  1260. self.default = False
  1261. if flag_value is None:
  1262. flag_value = not self.default
  1263. self.is_flag = is_flag
  1264. self.flag_value = flag_value
  1265. if self.is_flag and isinstance(self.flag_value, bool) \
  1266. and type is None:
  1267. self.type = BOOL
  1268. self.is_bool_flag = True
  1269. else:
  1270. self.is_bool_flag = False
  1271. # Counting
  1272. self.count = count
  1273. if count:
  1274. if type is None:
  1275. self.type = IntRange(min=0)
  1276. if default_is_missing:
  1277. self.default = 0
  1278. self.multiple = multiple
  1279. self.allow_from_autoenv = allow_from_autoenv
  1280. self.help = help
  1281. self.show_default = show_default
  1282. # Sanity check for stuff we don't support
  1283. if __debug__:
  1284. if self.nargs < 0:
  1285. raise TypeError('Options cannot have nargs < 0')
  1286. if self.prompt and self.is_flag and not self.is_bool_flag:
  1287. raise TypeError('Cannot prompt for flags that are not bools.')
  1288. if not self.is_bool_flag and self.secondary_opts:
  1289. raise TypeError('Got secondary option for non boolean flag.')
  1290. if self.is_bool_flag and self.hide_input \
  1291. and self.prompt is not None:
  1292. raise TypeError('Hidden input does not work with boolean '
  1293. 'flag prompts.')
  1294. if self.count:
  1295. if self.multiple:
  1296. raise TypeError('Options cannot be multiple and count '
  1297. 'at the same time.')
  1298. elif self.is_flag:
  1299. raise TypeError('Options cannot be count and flags at '
  1300. 'the same time.')
  1301. def _parse_decls(self, decls, expose_value):
  1302. opts = []
  1303. secondary_opts = []
  1304. name = None
  1305. possible_names = []
  1306. for decl in decls:
  1307. if isidentifier(decl):
  1308. if name is not None:
  1309. raise TypeError('Name defined twice')
  1310. name = decl
  1311. else:
  1312. split_char = decl[:1] == '/' and ';' or '/'
  1313. if split_char in decl:
  1314. first, second = decl.split(split_char, 1)
  1315. first = first.rstrip()
  1316. if first:
  1317. possible_names.append(split_opt(first))
  1318. opts.append(first)
  1319. second = second.lstrip()
  1320. if second:
  1321. secondary_opts.append(second.lstrip())
  1322. else:
  1323. possible_names.append(split_opt(decl))
  1324. opts.append(decl)
  1325. if name is None and possible_names:
  1326. possible_names.sort(key=lambda x: len(x[0]))
  1327. name = possible_names[-1][1].replace('-', '_').lower()
  1328. if not isidentifier(name):
  1329. name = None
  1330. if name is None:
  1331. if not expose_value:
  1332. return None, opts, secondary_opts
  1333. raise TypeError('Could not determine name for option')
  1334. if not opts and not secondary_opts:
  1335. raise TypeError('No options defined but a name was passed (%s). '
  1336. 'Did you mean to declare an argument instead '
  1337. 'of an option?' % name)
  1338. return name, opts, secondary_opts
  1339. def add_to_parser(self, parser, ctx):
  1340. kwargs = {
  1341. 'dest': self.name,
  1342. 'nargs': self.nargs,
  1343. 'obj': self,
  1344. }
  1345. if self.multiple:
  1346. action = 'append'
  1347. elif self.count:
  1348. action = 'count'
  1349. else:
  1350. action = 'store'
  1351. if self.is_flag:
  1352. kwargs.pop('nargs', None)
  1353. if self.is_bool_flag and self.secondary_opts:
  1354. parser.add_option(self.opts, action=action + '_const',
  1355. const=True, **kwargs)
  1356. parser.add_option(self.secondary_opts, action=action +
  1357. '_const', const=False, **kwargs)
  1358. else:
  1359. parser.add_option(self.opts, action=action + '_const',
  1360. const=self.flag_value,
  1361. **kwargs)
  1362. else:
  1363. kwargs['action'] = action
  1364. parser.add_option(self.opts, **kwargs)
  1365. def get_help_record(self, ctx):
  1366. any_prefix_is_slash = []
  1367. def _write_opts(opts):
  1368. rv, any_slashes = join_options(opts)
  1369. if any_slashes:
  1370. any_prefix_is_slash[:] = [True]
  1371. if not self.is_flag and not self.count:
  1372. rv += ' ' + self.make_metavar()
  1373. return rv
  1374. rv = [_write_opts(self.opts)]
  1375. if self.secondary_opts:
  1376. rv.append(_write_opts(self.secondary_opts))
  1377. help = self.help or ''
  1378. extra = []
  1379. if self.default is not None and self.show_default:
  1380. extra.append('default: %s' % (
  1381. ', '.join('%s' % d for d in self.default)
  1382. if isinstance(self.default, (list, tuple))
  1383. else self.default, ))
  1384. if self.required:
  1385. extra.append('required')
  1386. if extra:
  1387. help = '%s[%s]' % (help and help + ' ' or '', '; '.join(extra))
  1388. return ((any_prefix_is_slash and '; ' or ' / ').join(rv), help)
  1389. def get_default(self, ctx):
  1390. # If we're a non boolean flag out default is more complex because
  1391. # we need to look at all flags in the same group to figure out
  1392. # if we're the the default one in which case we return the flag
  1393. # value as default.
  1394. if self.is_flag and not self.is_bool_flag:
  1395. for param in ctx.command.params:
  1396. if param.name == self.name and param.default:
  1397. return param.flag_value
  1398. return None
  1399. return Parameter.get_default(self, ctx)
  1400. def prompt_for_value(self, ctx):
  1401. """This is an alternative flow that can be activated in the full
  1402. value processing if a value does not exist. It will prompt the
  1403. user until a valid value exists and then returns the processed
  1404. value as result.
  1405. """
  1406. # Calculate the default before prompting anything to be stable.
  1407. default = self.get_default(ctx)
  1408. # If this is a prompt for a flag we need to handle this
  1409. # differently.
  1410. if self.is_bool_flag:
  1411. return confirm(self.prompt, default)
  1412. return prompt(self.prompt, default=default,
  1413. hide_input=self.hide_input,
  1414. confirmation_prompt=self.confirmation_prompt,
  1415. value_proc=lambda x: self.process_value(ctx, x))
  1416. def resolve_envvar_value(self, ctx):
  1417. rv = Parameter.resolve_envvar_value(self, ctx)
  1418. if rv is not None:
  1419. return rv
  1420. if self.allow_from_autoenv and \
  1421. ctx.auto_envvar_prefix is not None:
  1422. envvar = '%s_%s' % (ctx.auto_envvar_prefix, self.name.upper())
  1423. return os.environ.get(envvar)
  1424. def value_from_envvar(self, ctx):
  1425. rv = self.resolve_envvar_value(ctx)
  1426. if rv is None:
  1427. return None
  1428. value_depth = (self.nargs != 1) + bool(self.multiple)
  1429. if value_depth > 0 and rv is not None:
  1430. rv = self.type.split_envvar_value(rv)
  1431. if self.multiple and self.nargs != 1:
  1432. rv = batch(rv, self.nargs)
  1433. return rv
  1434. def full_process_value(self, ctx, value):
  1435. if value is None and self.prompt is not None \
  1436. and not ctx.resilient_parsing:
  1437. return self.prompt_for_value(ctx)
  1438. return Parameter.full_process_value(self, ctx, value)
  1439. class Argument(Parameter):
  1440. """Arguments are positional parameters to a command. They generally
  1441. provide fewer features than options but can have infinite ``nargs``
  1442. and are required by default.
  1443. All parameters are passed onwards to the parameter constructor.
  1444. """
  1445. param_type_name = 'argument'
  1446. def __init__(self, param_decls, required=None, **attrs):
  1447. if required is None:
  1448. if attrs.get('default') is not None:
  1449. required = False
  1450. else:
  1451. required = attrs.get('nargs', 1) > 0
  1452. Parameter.__init__(self, param_decls, required=required, **attrs)
  1453. if self.default is not None and self.nargs < 0:
  1454. raise TypeError('nargs=-1 in combination with a default value '
  1455. 'is not supported.')
  1456. @property
  1457. def human_readable_name(self):
  1458. if self.metavar is not None:
  1459. return self.metavar
  1460. return self.name.upper()
  1461. def make_metavar(self):
  1462. if self.metavar is not None:
  1463. return self.metavar
  1464. var = self.name.upper()
  1465. if not self.required:
  1466. var = '[%s]' % var
  1467. if self.nargs != 1:
  1468. var += '...'
  1469. return var
  1470. def _parse_decls(self, decls, expose_value):
  1471. if not decls:
  1472. if not expose_value:
  1473. return None, [], []
  1474. raise TypeError('Could not determine name for argument')
  1475. if len(decls) == 1:
  1476. name = arg = decls[0]
  1477. name = name.replace('-', '_').lower()
  1478. elif len(decls) == 2:
  1479. name, arg = decls
  1480. else:
  1481. raise TypeError('Arguments take exactly one or two '
  1482. 'parameter declarations, got %d' % len(decls))
  1483. return name, [arg], []
  1484. def get_usage_pieces(self, ctx):
  1485. return [self.make_metavar()]
  1486. def add_to_parser(self, parser, ctx):
  1487. parser.add_argument(dest=self.name, nargs=self.nargs,
  1488. obj=self)
  1489. # Circular dependency between decorators and core
  1490. from .decorators import command, group