comparison planemo/lib/python3.7/site-packages/click/core.py @ 0:d30785e31577 draft

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