index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
9,380
asyncclick.core
call_on_close
Register a function to be called when the context tears down. This can be used to close resources opened during the script execution. Resources that support Python's context manager protocol which would be used in a ``with`` statement should be registered with :meth:`with_resource` instead. :param f: The function to execute on teardown.
def call_on_close(self, f: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]: """Register a function to be called when the context tears down. This can be used to close resources opened during the script execution. Resources that support Python's context manager protocol which would be used in a ``with`` statement should be registered with :meth:`with_resource` instead. :param f: The function to execute on teardown. """ return self._exit_stack.callback(f)
(self, f: Callable[..., Any]) -> Callable[..., Any]
9,381
asyncclick.core
close
Invoke all close callbacks registered with :meth:`call_on_close`, and exit all context managers entered with :meth:`with_resource`.
def close(self) -> None: """Invoke all close callbacks registered with :meth:`call_on_close`, and exit all context managers entered with :meth:`with_resource`. """ self._exit_stack.close() # In case the context is reused, create a new exit stack. self._exit_stack = ExitStack()
(self) -> NoneType
9,382
asyncclick.core
ensure_object
Like :meth:`find_object` but sets the innermost object to a new instance of `object_type` if it does not exist.
def ensure_object(self, object_type: t.Type[V]) -> V: """Like :meth:`find_object` but sets the innermost object to a new instance of `object_type` if it does not exist. """ rv = self.find_object(object_type) if rv is None: self.obj = rv = object_type() return rv
(self, object_type: Type[~V]) -> ~V
9,383
asyncclick.core
exit
Exits the application with a given exit code.
def exit(self, code: int = 0) -> "te.NoReturn": """Exits the application with a given exit code.""" raise Exit(code)
(self, code: int = 0) -> 'te.NoReturn'
9,384
asyncclick.core
fail
Aborts the execution of the program with a specific error message. :param message: the error message to fail with.
def fail(self, message: str) -> "te.NoReturn": """Aborts the execution of the program with a specific error message. :param message: the error message to fail with. """ raise UsageError(message, self)
(self, message: str) -> 'te.NoReturn'
9,385
asyncclick.core
find_object
Finds the closest object of a given type.
def find_object(self, object_type: t.Type[V]) -> t.Optional[V]: """Finds the closest object of a given type.""" node: t.Optional["Context"] = self while node is not None: if isinstance(node.obj, object_type): return node.obj node = node.parent return None
(self, object_type: Type[~V]) -> Optional[~V]
9,386
asyncclick.core
find_root
Finds the outermost context.
def find_root(self) -> "Context": """Finds the outermost context.""" node = self while node.parent is not None: node = node.parent return node
(self) -> asyncclick.core.Context
9,387
asyncclick.core
forward
Similar to :meth:`invoke` but fills in default keyword arguments from the current context if the other command expects it. This cannot invoke callbacks directly, only other commands. .. versionchanged:: 8.0 All ``kwargs`` are tracked in :attr:`params` so they will be passed if ``forward`` is called at multiple levels.
@t.overload async def invoke( __self, # noqa: B902 __callback: "Command", *args: t.Any, **kwargs: t.Any, ) -> t.Any: ...
(_Context__self, _Context__cmd: asyncclick.core.Command, *args: Any, **kwargs: Any) -> Any
9,388
asyncclick.core
get_help
Helper method to get formatted help page for the current context and command.
def get_help(self) -> str: """Helper method to get formatted help page for the current context and command. """ return self.command.get_help(self)
(self) -> str
9,389
asyncclick.core
get_parameter_source
Get the source of a parameter. This indicates the location from which the value of the parameter was obtained. This can be useful for determining when a user specified a value on the command line that is the same as the default value. It will be :attr:`~click.core.ParameterSource.DEFAULT` only if the value was actually taken from the default. :param name: The name of the parameter. :rtype: ParameterSource .. versionchanged:: 8.0 Returns ``None`` if the parameter was not provided from any source.
def get_parameter_source(self, name: str) -> t.Optional[ParameterSource]: """Get the source of a parameter. This indicates the location from which the value of the parameter was obtained. This can be useful for determining when a user specified a value on the command line that is the same as the default value. It will be :attr:`~click.core.ParameterSource.DEFAULT` only if the value was actually taken from the default. :param name: The name of the parameter. :rtype: ParameterSource .. versionchanged:: 8.0 Returns ``None`` if the parameter was not provided from any source. """ return self._parameter_source.get(name)
(self, name: str) -> Optional[asyncclick.core.ParameterSource]
9,390
asyncclick.core
get_usage
Helper method to get formatted usage string for the current context and command.
def get_usage(self) -> str: """Helper method to get formatted usage string for the current context and command. """ return self.command.get_usage(self)
(self) -> str
9,391
asyncclick.core
invoke
Invokes a command callback in exactly the way it expects. There are two ways to invoke this method: 1. the first argument can be a callback and all other arguments and keyword arguments are forwarded directly to the function. 2. the first argument is a click command object. In that case all arguments are forwarded as well but proper click parameters (options and click arguments) must be keyword arguments and Click will fill in defaults. Note that before Click 3.2 keyword arguments were not properly filled in against the intention of this code and no context was created. For more information about this change and why it was done in a bugfix release see :ref:`upgrade-to-3.2`. .. versionchanged:: 8.0 All ``kwargs`` are tracked in :attr:`params` so they will be passed if :meth:`forward` is called at multiple levels.
@t.overload async def invoke( __self, # noqa: B902 __callback: "Command", *args: t.Any, **kwargs: t.Any, ) -> t.Any: ...
(_Context__self, _Context__callback: Union[asyncclick.core.Command, Callable[..., ~V]], *args: Any, **kwargs: Any) -> Union[Any, ~V]
9,392
asyncclick.core
lookup_default
Get the default for a parameter from :attr:`default_map`. :param name: Name of the parameter. :param call: If the default is a callable, call it. Disable to return the callable instead. .. versionchanged:: 8.0 Added the ``call`` parameter.
def lookup_default(self, name: str, call: bool = True) -> t.Optional[t.Any]: """Get the default for a parameter from :attr:`default_map`. :param name: Name of the parameter. :param call: If the default is a callable, call it. Disable to return the callable instead. .. versionchanged:: 8.0 Added the ``call`` parameter. """ if self.default_map is not None: value = self.default_map.get(name) if call and callable(value): return value() return value return None
(self, name: str, call: bool = True) -> Optional[Any]
9,393
asyncclick.core
make_formatter
Creates the :class:`~click.HelpFormatter` for the help and usage output. To quickly customize the formatter class used without overriding this method, set the :attr:`formatter_class` attribute. .. versionchanged:: 8.0 Added the :attr:`formatter_class` attribute.
def make_formatter(self) -> HelpFormatter: """Creates the :class:`~click.HelpFormatter` for the help and usage output. To quickly customize the formatter class used without overriding this method, set the :attr:`formatter_class` attribute. .. versionchanged:: 8.0 Added the :attr:`formatter_class` attribute. """ return self.formatter_class( width=self.terminal_width, max_width=self.max_content_width )
(self) -> asyncclick.formatting.HelpFormatter
9,394
asyncclick.core
scope
This helper method can be used with the context object to promote it to the current thread local (see :func:`get_current_context`). The default behavior of this is to invoke the cleanup functions which can be disabled by setting `cleanup` to `False`. The cleanup functions are typically used for things such as closing file handles. If the cleanup is intended the context object can also be directly used as a context manager. Example usage:: async with ctx.scope(): assert get_current_context() is ctx This is equivalent:: async with ctx: assert get_current_context() is ctx .. versionadded:: 5.0 :param cleanup: controls if the cleanup functions should be run or not. The default is to run these functions. In some situations the context only wants to be temporarily pushed in which case this can be disabled. Nested pushes automatically defer the cleanup.
def __init__( self, command: "Command", parent: t.Optional["Context"] = None, info_name: t.Optional[str] = None, obj: t.Optional[t.Any] = None, auto_envvar_prefix: t.Optional[str] = None, default_map: t.Optional[t.MutableMapping[str, t.Any]] = None, terminal_width: t.Optional[int] = None, max_content_width: t.Optional[int] = None, resilient_parsing: bool = False, allow_extra_args: t.Optional[bool] = None, allow_interspersed_args: t.Optional[bool] = None, ignore_unknown_options: t.Optional[bool] = None, help_option_names: t.Optional[t.List[str]] = None, token_normalize_func: t.Optional[t.Callable[[str], str]] = None, color: t.Optional[bool] = None, show_default: t.Optional[bool] = None, ) -> None: #: the parent context or `None` if none exists. self.parent = parent #: the :class:`Command` for this context. self.command = command #: the descriptive information name self.info_name = info_name #: Map of parameter names to their parsed values. Parameters #: with ``expose_value=False`` are not stored. self.params: t.Dict[str, t.Any] = {} #: the leftover arguments. self.args: t.List[str] = [] #: protected arguments. These are arguments that are prepended #: to `args` when certain parsing scenarios are encountered but #: must be never propagated to another arguments. This is used #: to implement nested parsing. self.protected_args: t.List[str] = [] #: the collected prefixes of the command's options. self._opt_prefixes: t.Set[str] = set(parent._opt_prefixes) if parent else set() if obj is None and parent is not None: obj = parent.obj #: the user object stored. self.obj: t.Any = obj self._meta: t.Dict[str, t.Any] = getattr(parent, "meta", {}) #: A dictionary (-like object) with defaults for parameters. if ( default_map is None and info_name is not None and parent is not None and parent.default_map is not None ): default_map = parent.default_map.get(info_name) self.default_map: t.Optional[t.MutableMapping[str, t.Any]] = default_map #: This flag indicates if a subcommand is going to be executed. A #: group callback can use this information to figure out if it's #: being executed directly or because the execution flow passes #: onwards to a subcommand. By default it's None, but it can be #: the name of the subcommand to execute. #: #: If chaining is enabled this will be set to ``'*'`` in case #: any commands are executed. It is however not possible to #: figure out which ones. If you require this knowledge you #: should use a :func:`result_callback`. self.invoked_subcommand: t.Optional[str] = None if terminal_width is None and parent is not None: terminal_width = parent.terminal_width #: The width of the terminal (None is autodetection). self.terminal_width: t.Optional[int] = terminal_width if max_content_width is None and parent is not None: max_content_width = parent.max_content_width #: The maximum width of formatted content (None implies a sensible #: default which is 80 for most things). self.max_content_width: t.Optional[int] = max_content_width if allow_extra_args is None: allow_extra_args = command.allow_extra_args #: Indicates if the context allows extra args or if it should #: fail on parsing. #: #: .. versionadded:: 3.0 self.allow_extra_args = allow_extra_args if allow_interspersed_args is None: allow_interspersed_args = command.allow_interspersed_args #: Indicates if the context allows mixing of arguments and #: options or not. #: #: .. versionadded:: 3.0 self.allow_interspersed_args: bool = allow_interspersed_args if ignore_unknown_options is None: ignore_unknown_options = command.ignore_unknown_options #: Instructs click to ignore options that a command does not #: understand and will store it on the context for later #: processing. This is primarily useful for situations where you #: want to call into external programs. Generally this pattern is #: strongly discouraged because it's not possibly to losslessly #: forward all arguments. #: #: .. versionadded:: 4.0 self.ignore_unknown_options: bool = ignore_unknown_options if help_option_names is None: if parent is not None: help_option_names = parent.help_option_names else: help_option_names = ["--help"] #: The names for the help options. self.help_option_names: t.List[str] = help_option_names if token_normalize_func is None and parent is not None: token_normalize_func = parent.token_normalize_func #: An optional normalization function for tokens. This is #: options, choices, commands etc. self.token_normalize_func: t.Optional[ t.Callable[[str], str] ] = token_normalize_func #: Indicates if resilient parsing is enabled. In that case Click #: will do its best to not cause any failures and default values #: will be ignored. Useful for completion. self.resilient_parsing: bool = resilient_parsing # If there is no envvar prefix yet, but the parent has one and # the command on this level has a name, we can expand the envvar # prefix automatically. if auto_envvar_prefix is None: if ( parent is not None and parent.auto_envvar_prefix is not None and self.info_name is not None ): auto_envvar_prefix = ( f"{parent.auto_envvar_prefix}_{self.info_name.upper()}" ) else: auto_envvar_prefix = auto_envvar_prefix.upper() if auto_envvar_prefix is not None: auto_envvar_prefix = auto_envvar_prefix.replace("-", "_") self.auto_envvar_prefix: t.Optional[str] = auto_envvar_prefix if color is None and parent is not None: color = parent.color #: Controls if styling output is wanted or not. self.color: t.Optional[bool] = color if show_default is None and parent is not None: show_default = parent.show_default #: Show option default values when formatting help text. self.show_default: t.Optional[bool] = show_default self._close_callbacks: t.List[t.Callable[[], t.Any]] = [] self._depth = 0 self._parameter_source: t.Dict[str, ParameterSource] = {} self._exit_stack = ExitStack()
(self, cleanup: bool = True) -> AsyncIterator[asyncclick.core.Context]
9,395
asyncclick.core
set_parameter_source
Set the source of a parameter. This indicates the location from which the value of the parameter was obtained. :param name: The name of the parameter. :param source: A member of :class:`~click.core.ParameterSource`.
def set_parameter_source(self, name: str, source: ParameterSource) -> None: """Set the source of a parameter. This indicates the location from which the value of the parameter was obtained. :param name: The name of the parameter. :param source: A member of :class:`~click.core.ParameterSource`. """ self._parameter_source[name] = source
(self, name: str, source: asyncclick.core.ParameterSource) -> NoneType
9,396
asyncclick.core
to_info_dict
Gather information that could be useful for a tool generating user-facing documentation. This traverses the entire CLI structure. .. code-block:: python with Context(cli) as ctx: info = ctx.to_info_dict() .. versionadded:: 8.0
def __init__( self, command: "Command", parent: t.Optional["Context"] = None, info_name: t.Optional[str] = None, obj: t.Optional[t.Any] = None, auto_envvar_prefix: t.Optional[str] = None, default_map: t.Optional[t.MutableMapping[str, t.Any]] = None, terminal_width: t.Optional[int] = None, max_content_width: t.Optional[int] = None, resilient_parsing: bool = False, allow_extra_args: t.Optional[bool] = None, allow_interspersed_args: t.Optional[bool] = None, ignore_unknown_options: t.Optional[bool] = None, help_option_names: t.Optional[t.List[str]] = None, token_normalize_func: t.Optional[t.Callable[[str], str]] = None, color: t.Optional[bool] = None, show_default: t.Optional[bool] = None, ) -> None: #: the parent context or `None` if none exists. self.parent = parent #: the :class:`Command` for this context. self.command = command #: the descriptive information name self.info_name = info_name #: Map of parameter names to their parsed values. Parameters #: with ``expose_value=False`` are not stored. self.params: t.Dict[str, t.Any] = {} #: the leftover arguments. self.args: t.List[str] = [] #: protected arguments. These are arguments that are prepended #: to `args` when certain parsing scenarios are encountered but #: must be never propagated to another arguments. This is used #: to implement nested parsing. self.protected_args: t.List[str] = [] #: the collected prefixes of the command's options. self._opt_prefixes: t.Set[str] = set(parent._opt_prefixes) if parent else set() if obj is None and parent is not None: obj = parent.obj #: the user object stored. self.obj: t.Any = obj self._meta: t.Dict[str, t.Any] = getattr(parent, "meta", {}) #: A dictionary (-like object) with defaults for parameters. if ( default_map is None and info_name is not None and parent is not None and parent.default_map is not None ): default_map = parent.default_map.get(info_name) self.default_map: t.Optional[t.MutableMapping[str, t.Any]] = default_map #: This flag indicates if a subcommand is going to be executed. A #: group callback can use this information to figure out if it's #: being executed directly or because the execution flow passes #: onwards to a subcommand. By default it's None, but it can be #: the name of the subcommand to execute. #: #: If chaining is enabled this will be set to ``'*'`` in case #: any commands are executed. It is however not possible to #: figure out which ones. If you require this knowledge you #: should use a :func:`result_callback`. self.invoked_subcommand: t.Optional[str] = None if terminal_width is None and parent is not None: terminal_width = parent.terminal_width #: The width of the terminal (None is autodetection). self.terminal_width: t.Optional[int] = terminal_width if max_content_width is None and parent is not None: max_content_width = parent.max_content_width #: The maximum width of formatted content (None implies a sensible #: default which is 80 for most things). self.max_content_width: t.Optional[int] = max_content_width if allow_extra_args is None: allow_extra_args = command.allow_extra_args #: Indicates if the context allows extra args or if it should #: fail on parsing. #: #: .. versionadded:: 3.0 self.allow_extra_args = allow_extra_args if allow_interspersed_args is None: allow_interspersed_args = command.allow_interspersed_args #: Indicates if the context allows mixing of arguments and #: options or not. #: #: .. versionadded:: 3.0 self.allow_interspersed_args: bool = allow_interspersed_args if ignore_unknown_options is None: ignore_unknown_options = command.ignore_unknown_options #: Instructs click to ignore options that a command does not #: understand and will store it on the context for later #: processing. This is primarily useful for situations where you #: want to call into external programs. Generally this pattern is #: strongly discouraged because it's not possibly to losslessly #: forward all arguments. #: #: .. versionadded:: 4.0 self.ignore_unknown_options: bool = ignore_unknown_options if help_option_names is None: if parent is not None: help_option_names = parent.help_option_names else: help_option_names = ["--help"] #: The names for the help options. self.help_option_names: t.List[str] = help_option_names if token_normalize_func is None and parent is not None: token_normalize_func = parent.token_normalize_func #: An optional normalization function for tokens. This is #: options, choices, commands etc. self.token_normalize_func: t.Optional[ t.Callable[[str], str] ] = token_normalize_func #: Indicates if resilient parsing is enabled. In that case Click #: will do its best to not cause any failures and default values #: will be ignored. Useful for completion. self.resilient_parsing: bool = resilient_parsing # If there is no envvar prefix yet, but the parent has one and # the command on this level has a name, we can expand the envvar # prefix automatically. if auto_envvar_prefix is None: if ( parent is not None and parent.auto_envvar_prefix is not None and self.info_name is not None ): auto_envvar_prefix = ( f"{parent.auto_envvar_prefix}_{self.info_name.upper()}" ) else: auto_envvar_prefix = auto_envvar_prefix.upper() if auto_envvar_prefix is not None: auto_envvar_prefix = auto_envvar_prefix.replace("-", "_") self.auto_envvar_prefix: t.Optional[str] = auto_envvar_prefix if color is None and parent is not None: color = parent.color #: Controls if styling output is wanted or not. self.color: t.Optional[bool] = color if show_default is None and parent is not None: show_default = parent.show_default #: Show option default values when formatting help text. self.show_default: t.Optional[bool] = show_default self._close_callbacks: t.List[t.Callable[[], t.Any]] = [] self._depth = 0 self._parameter_source: t.Dict[str, ParameterSource] = {} self._exit_stack = ExitStack()
(self) -> Dict[str, Any]
9,397
asyncclick.core
with_async_resource
Register a resource as if it were used in an ``async with`` statement. The resource will be cleaned up when the context is popped. Uses :meth:`contextlib.ExitStack.enter_context`. It calls the resource's ``__enter__()`` method and returns the result. When the context is popped, it closes the stack, which calls the resource's ``__exit__()`` method. To register a cleanup function for something that isn't a context manager, use :meth:`call_on_close`. Or use something from :mod:`contextlib` to turn it into a context manager first. .. code-block:: python @click.group() @click.option("--name") @click.pass_context def cli(ctx): ctx.obj = ctx.with_resource(connect_db(name)) :param context_manager: The context manager to enter. :return: Whatever ``context_manager.__enter__()`` returns. .. versionadded:: 8.0
def with_async_resource(self, context_manager: t.AsyncContextManager[V]) -> "t.Awaitable[V]": """Register a resource as if it were used in an ``async with`` statement. The resource will be cleaned up when the context is popped. Uses :meth:`contextlib.ExitStack.enter_context`. It calls the resource's ``__enter__()`` method and returns the result. When the context is popped, it closes the stack, which calls the resource's ``__exit__()`` method. To register a cleanup function for something that isn't a context manager, use :meth:`call_on_close`. Or use something from :mod:`contextlib` to turn it into a context manager first. .. code-block:: python @click.group() @click.option("--name") @click.pass_context def cli(ctx): ctx.obj = ctx.with_resource(connect_db(name)) :param context_manager: The context manager to enter. :return: Whatever ``context_manager.__enter__()`` returns. .. versionadded:: 8.0 """ return self._ctx_mgr.enter_async_context(context_manager)
(self, context_manager: AsyncContextManager[~V]) -> Awaitable[~V]
9,398
asyncclick.core
with_resource
Register a resource as if it were used in a ``with`` statement. The resource will be cleaned up when the context is popped. Uses :meth:`contextlib.ExitStack.enter_context`. It calls the resource's ``__enter__()`` method and returns the result. When the context is popped, it closes the stack, which calls the resource's ``__exit__()`` method. To register a cleanup function for something that isn't a context manager, use :meth:`call_on_close`. Or use something from :mod:`contextlib` to turn it into a context manager first. .. code-block:: python @click.group() @click.option("--name") @click.pass_context def cli(ctx): ctx.obj = ctx.with_resource(connect_db(name)) :param context_manager: The context manager to enter. :return: Whatever ``context_manager.__enter__()`` returns. .. versionadded:: 8.0
def with_resource(self, context_manager: t.ContextManager[V]) -> V: """Register a resource as if it were used in a ``with`` statement. The resource will be cleaned up when the context is popped. Uses :meth:`contextlib.ExitStack.enter_context`. It calls the resource's ``__enter__()`` method and returns the result. When the context is popped, it closes the stack, which calls the resource's ``__exit__()`` method. To register a cleanup function for something that isn't a context manager, use :meth:`call_on_close`. Or use something from :mod:`contextlib` to turn it into a context manager first. .. code-block:: python @click.group() @click.option("--name") @click.pass_context def cli(ctx): ctx.obj = ctx.with_resource(connect_db(name)) :param context_manager: The context manager to enter. :return: Whatever ``context_manager.__enter__()`` returns. .. versionadded:: 8.0 """ return self._ctx_mgr.enter_context(context_manager)
(self, context_manager: ContextManager[~V]) -> ~V
9,399
asyncclick.types
DateTime
The DateTime type converts date strings into `datetime` objects. The format strings which are checked are configurable, but default to some common (non-timezone aware) ISO 8601 formats. When specifying *DateTime* formats, you should only pass a list or a tuple. Other iterables, like generators, may lead to surprising results. The format strings are processed using ``datetime.strptime``, and this consequently defines the format strings which are allowed. Parsing is tried using each format, in order, and the first format which parses successfully is used. :param formats: A list or tuple of date format strings, in the order in which they should be tried. Defaults to ``'%Y-%m-%d'``, ``'%Y-%m-%dT%H:%M:%S'``, ``'%Y-%m-%d %H:%M:%S'``.
class DateTime(ParamType): """The DateTime type converts date strings into `datetime` objects. The format strings which are checked are configurable, but default to some common (non-timezone aware) ISO 8601 formats. When specifying *DateTime* formats, you should only pass a list or a tuple. Other iterables, like generators, may lead to surprising results. The format strings are processed using ``datetime.strptime``, and this consequently defines the format strings which are allowed. Parsing is tried using each format, in order, and the first format which parses successfully is used. :param formats: A list or tuple of date format strings, in the order in which they should be tried. Defaults to ``'%Y-%m-%d'``, ``'%Y-%m-%dT%H:%M:%S'``, ``'%Y-%m-%d %H:%M:%S'``. """ name = "datetime" def __init__(self, formats: t.Optional[t.Sequence[str]] = None): self.formats: t.Sequence[str] = formats or [ "%Y-%m-%d", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d %H:%M:%S", ] async def to_info_dict(self) -> t.Dict[str, t.Any]: info_dict = await super().to_info_dict() info_dict["formats"] = self.formats return info_dict def get_metavar(self, param: "Parameter") -> str: return f"[{'|'.join(self.formats)}]" def _try_to_convert_date(self, value: t.Any, format: str) -> t.Optional[datetime]: try: return datetime.strptime(value, format) except ValueError: return None def convert( self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"] ) -> t.Any: if isinstance(value, datetime): return value for format in self.formats: converted = self._try_to_convert_date(value, format) if converted is not None: return converted formats_str = ", ".join(map(repr, self.formats)) self.fail( ngettext( "{value!r} does not match the format {format}.", "{value!r} does not match the formats {formats}.", len(self.formats), ).format(value=value, format=formats_str, formats=formats_str), param, ctx, ) def __repr__(self) -> str: return "DateTime"
(formats: Optional[Sequence[str]] = None)
9,401
asyncclick.types
__init__
null
def __init__(self, formats: t.Optional[t.Sequence[str]] = None): self.formats: t.Sequence[str] = formats or [ "%Y-%m-%d", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d %H:%M:%S", ]
(self, formats: Optional[Sequence[str]] = None)
9,402
asyncclick.types
__repr__
null
def __repr__(self) -> str: return "DateTime"
(self) -> str
9,403
asyncclick.types
_try_to_convert_date
null
def _try_to_convert_date(self, value: t.Any, format: str) -> t.Optional[datetime]: try: return datetime.strptime(value, format) except ValueError: return None
(self, value: Any, format: str) -> Optional[datetime.datetime]
9,404
asyncclick.types
convert
null
def convert( self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"] ) -> t.Any: if isinstance(value, datetime): return value for format in self.formats: converted = self._try_to_convert_date(value, format) if converted is not None: return converted formats_str = ", ".join(map(repr, self.formats)) self.fail( ngettext( "{value!r} does not match the format {format}.", "{value!r} does not match the formats {formats}.", len(self.formats), ).format(value=value, format=formats_str, formats=formats_str), param, ctx, )
(self, value: Any, param: Optional[ForwardRef('Parameter')], ctx: Optional[ForwardRef('Context')]) -> Any
9,406
asyncclick.types
get_metavar
null
def get_metavar(self, param: "Parameter") -> str: return f"[{'|'.join(self.formats)}]"
(self, param: 'Parameter') -> str
9,407
asyncclick.types
get_missing_message
Optionally might return extra information about a missing parameter. .. versionadded:: 2.0
def get_missing_message(self, param: "Parameter") -> t.Optional[str]: """Optionally might return extra information about a missing parameter. .. versionadded:: 2.0 """
(self, param: 'Parameter') -> Optional[str]
9,408
asyncclick.types
shell_complete
Return a list of :class:`~click.shell_completion.CompletionItem` objects for the incomplete value. Most types do not provide completions, but some do, and this allows custom types to provide custom completions as well. :param ctx: Invocation context for this command. :param param: The parameter that is requesting completion. :param incomplete: Value being completed. May be empty. .. versionadded:: 8.0
def shell_complete( self, ctx: "Context", param: "Parameter", incomplete: str ) -> t.List["CompletionItem"]: """Return a list of :class:`~click.shell_completion.CompletionItem` objects for the incomplete value. Most types do not provide completions, but some do, and this allows custom types to provide custom completions as well. :param ctx: Invocation context for this command. :param param: The parameter that is requesting completion. :param incomplete: Value being completed. May be empty. .. versionadded:: 8.0 """ return []
(self, ctx: 'Context', param: 'Parameter', incomplete: str) -> List[ForwardRef('CompletionItem')]
9,411
asyncclick.types
File
Declares a parameter to be a file for reading or writing. The file is automatically closed once the context tears down (after the command finished working). Files can be opened for reading or writing. The special value ``-`` indicates stdin or stdout depending on the mode. By default, the file is opened for reading text data, but it can also be opened in binary mode or for writing. The encoding parameter can be used to force a specific encoding. The `lazy` flag controls if the file should be opened immediately or upon first IO. The default is to be non-lazy for standard input and output streams as well as files opened for reading, `lazy` otherwise. When opening a file lazily for reading, it is still opened temporarily for validation, but will not be held open until first IO. lazy is mainly useful when opening for writing to avoid creating the file until it is needed. Starting with Click 2.0, files can also be opened atomically in which case all writes go into a separate file in the same folder and upon completion the file will be moved over to the original location. This is useful if a file regularly read by other users is modified. See :ref:`file-args` for more information.
class File(ParamType): """Declares a parameter to be a file for reading or writing. The file is automatically closed once the context tears down (after the command finished working). Files can be opened for reading or writing. The special value ``-`` indicates stdin or stdout depending on the mode. By default, the file is opened for reading text data, but it can also be opened in binary mode or for writing. The encoding parameter can be used to force a specific encoding. The `lazy` flag controls if the file should be opened immediately or upon first IO. The default is to be non-lazy for standard input and output streams as well as files opened for reading, `lazy` otherwise. When opening a file lazily for reading, it is still opened temporarily for validation, but will not be held open until first IO. lazy is mainly useful when opening for writing to avoid creating the file until it is needed. Starting with Click 2.0, files can also be opened atomically in which case all writes go into a separate file in the same folder and upon completion the file will be moved over to the original location. This is useful if a file regularly read by other users is modified. See :ref:`file-args` for more information. """ name = "filename" envvar_list_splitter: t.ClassVar[str] = os.path.pathsep def __init__( self, mode: str = "r", encoding: t.Optional[str] = None, errors: t.Optional[str] = "strict", lazy: t.Optional[bool] = None, atomic: bool = False, ) -> None: self.mode = mode self.encoding = encoding self.errors = errors self.lazy = lazy self.atomic = atomic async def to_info_dict(self) -> t.Dict[str, t.Any]: info_dict = await super().to_info_dict() info_dict.update(mode=self.mode, encoding=self.encoding) return info_dict def resolve_lazy_flag(self, value: "t.Union[str, os.PathLike[str]]") -> bool: if self.lazy is not None: return self.lazy if os.fspath(value) == "-": return False elif "w" in self.mode: return True return False def convert( self, value: t.Union[str, "os.PathLike[str]", t.IO[t.Any]], param: t.Optional["Parameter"], ctx: t.Optional["Context"], ) -> t.IO[t.Any]: if _is_file_like(value): return value value = t.cast("t.Union[str, os.PathLike[str]]", value) try: lazy = self.resolve_lazy_flag(value) if lazy: lf = LazyFile( value, self.mode, self.encoding, self.errors, atomic=self.atomic ) if ctx is not None: ctx.call_on_close(lf.close_intelligently) return t.cast(t.IO[t.Any], lf) f, should_close = open_stream( value, self.mode, self.encoding, self.errors, atomic=self.atomic ) # If a context is provided, we automatically close the file # at the end of the context execution (or flush out). If a # context does not exist, it's the caller's responsibility to # properly close the file. This for instance happens when the # type is used with prompts. if ctx is not None: if should_close: ctx.call_on_close(safecall(f.close)) else: ctx.call_on_close(safecall(f.flush)) return f except OSError as e: # noqa: B014 self.fail(f"'{format_filename(value)}': {e.strerror}", param, ctx) def shell_complete( self, ctx: "Context", param: "Parameter", incomplete: str ) -> t.List["CompletionItem"]: """Return a special completion marker that tells the completion system to use the shell to provide file path completions. :param ctx: Invocation context for this command. :param param: The parameter that is requesting completion. :param incomplete: Value being completed. May be empty. .. versionadded:: 8.0 """ from .shell_completion import CompletionItem return [CompletionItem(incomplete, type="file")]
(mode: str = 'r', encoding: Optional[str] = None, errors: Optional[str] = 'strict', lazy: Optional[bool] = None, atomic: bool = False) -> None
9,413
asyncclick.types
__init__
null
def __init__( self, mode: str = "r", encoding: t.Optional[str] = None, errors: t.Optional[str] = "strict", lazy: t.Optional[bool] = None, atomic: bool = False, ) -> None: self.mode = mode self.encoding = encoding self.errors = errors self.lazy = lazy self.atomic = atomic
(self, mode: str = 'r', encoding: Optional[str] = None, errors: Optional[str] = 'strict', lazy: Optional[bool] = None, atomic: bool = False) -> NoneType
9,414
asyncclick.types
convert
null
def convert( self, value: t.Union[str, "os.PathLike[str]", t.IO[t.Any]], param: t.Optional["Parameter"], ctx: t.Optional["Context"], ) -> t.IO[t.Any]: if _is_file_like(value): return value value = t.cast("t.Union[str, os.PathLike[str]]", value) try: lazy = self.resolve_lazy_flag(value) if lazy: lf = LazyFile( value, self.mode, self.encoding, self.errors, atomic=self.atomic ) if ctx is not None: ctx.call_on_close(lf.close_intelligently) return t.cast(t.IO[t.Any], lf) f, should_close = open_stream( value, self.mode, self.encoding, self.errors, atomic=self.atomic ) # If a context is provided, we automatically close the file # at the end of the context execution (or flush out). If a # context does not exist, it's the caller's responsibility to # properly close the file. This for instance happens when the # type is used with prompts. if ctx is not None: if should_close: ctx.call_on_close(safecall(f.close)) else: ctx.call_on_close(safecall(f.flush)) return f except OSError as e: # noqa: B014 self.fail(f"'{format_filename(value)}': {e.strerror}", param, ctx)
(self, value: Union[str, ForwardRef('os.PathLike[str]'), IO[Any]], param: Optional[ForwardRef('Parameter')], ctx: Optional[ForwardRef('Context')]) -> IO[Any]
9,416
asyncclick.types
get_metavar
Returns the metavar default for this param if it provides one.
def get_metavar(self, param: "Parameter") -> t.Optional[str]: """Returns the metavar default for this param if it provides one."""
(self, param: 'Parameter') -> Optional[str]
9,418
asyncclick.types
resolve_lazy_flag
null
def resolve_lazy_flag(self, value: "t.Union[str, os.PathLike[str]]") -> bool: if self.lazy is not None: return self.lazy if os.fspath(value) == "-": return False elif "w" in self.mode: return True return False
(self, value: Union[str, os.PathLike[str]]) -> bool
9,419
asyncclick.types
shell_complete
Return a special completion marker that tells the completion system to use the shell to provide file path completions. :param ctx: Invocation context for this command. :param param: The parameter that is requesting completion. :param incomplete: Value being completed. May be empty. .. versionadded:: 8.0
def shell_complete( self, ctx: "Context", param: "Parameter", incomplete: str ) -> t.List["CompletionItem"]: """Return a special completion marker that tells the completion system to use the shell to provide file path completions. :param ctx: Invocation context for this command. :param param: The parameter that is requesting completion. :param incomplete: Value being completed. May be empty. .. versionadded:: 8.0 """ from .shell_completion import CompletionItem return [CompletionItem(incomplete, type="file")]
(self, ctx: 'Context', param: 'Parameter', incomplete: str) -> List[ForwardRef('CompletionItem')]
9,422
asyncclick.exceptions
FileError
Raised if a file cannot be opened.
class FileError(ClickException): """Raised if a file cannot be opened.""" def __init__(self, filename: str, hint: t.Optional[str] = None) -> None: if hint is None: hint = _("unknown error") super().__init__(hint) self.ui_filename: str = format_filename(filename) self.filename = filename def format_message(self) -> str: return _("Could not open file {filename!r}: {message}").format( filename=self.ui_filename, message=self.message )
(filename: str, hint: Optional[str] = None) -> None
9,423
asyncclick.exceptions
__init__
null
def __init__(self, filename: str, hint: t.Optional[str] = None) -> None: if hint is None: hint = _("unknown error") super().__init__(hint) self.ui_filename: str = format_filename(filename) self.filename = filename
(self, filename: str, hint: Optional[str] = None) -> NoneType
9,425
asyncclick.exceptions
format_message
null
def format_message(self) -> str: return _("Could not open file {filename!r}: {message}").format( filename=self.ui_filename, message=self.message )
(self) -> str
9,427
asyncclick.types
FloatRange
Restrict a :data:`click.FLOAT` value to a range of accepted values. See :ref:`ranges`. If ``min`` or ``max`` are not passed, any value is accepted in that direction. If ``min_open`` or ``max_open`` are enabled, the corresponding boundary is not included in the range. If ``clamp`` is enabled, a value outside the range is clamped to the boundary instead of failing. This is not supported if either boundary is marked ``open``. .. versionchanged:: 8.0 Added the ``min_open`` and ``max_open`` parameters.
class FloatRange(_NumberRangeBase, FloatParamType): """Restrict a :data:`click.FLOAT` value to a range of accepted values. See :ref:`ranges`. If ``min`` or ``max`` are not passed, any value is accepted in that direction. If ``min_open`` or ``max_open`` are enabled, the corresponding boundary is not included in the range. If ``clamp`` is enabled, a value outside the range is clamped to the boundary instead of failing. This is not supported if either boundary is marked ``open``. .. versionchanged:: 8.0 Added the ``min_open`` and ``max_open`` parameters. """ name = "float range" def __init__( self, min: t.Optional[float] = None, max: t.Optional[float] = None, min_open: bool = False, max_open: bool = False, clamp: bool = False, ) -> None: super().__init__( min=min, max=max, min_open=min_open, max_open=max_open, clamp=clamp ) if (min_open or max_open) and clamp: raise TypeError("Clamping is not supported for open bounds.") def _clamp(self, bound: float, dir: "te.Literal[1, -1]", open: bool) -> float: if not open: return bound # Could use Python 3.9's math.nextafter here, but clamping an # open float range doesn't seem to be particularly useful. It's # left up to the user to write a callback to do it if needed. raise RuntimeError("Clamping is not supported for open bounds.")
(min: Optional[float] = None, max: Optional[float] = None, min_open: bool = False, max_open: bool = False, clamp: bool = False) -> None
9,429
asyncclick.types
__init__
null
def __init__( self, min: t.Optional[float] = None, max: t.Optional[float] = None, min_open: bool = False, max_open: bool = False, clamp: bool = False, ) -> None: super().__init__( min=min, max=max, min_open=min_open, max_open=max_open, clamp=clamp ) if (min_open or max_open) and clamp: raise TypeError("Clamping is not supported for open bounds.")
(self, min: Optional[float] = None, max: Optional[float] = None, min_open: bool = False, max_open: bool = False, clamp: bool = False) -> NoneType
9,430
asyncclick.types
__repr__
null
def __repr__(self) -> str: clamp = " clamped" if self.clamp else "" return f"<{type(self).__name__} {self._describe_range()}{clamp}>"
(self) -> str
9,431
asyncclick.types
_clamp
null
def _clamp(self, bound: float, dir: "te.Literal[1, -1]", open: bool) -> float: if not open: return bound # Could use Python 3.9's math.nextafter here, but clamping an # open float range doesn't seem to be particularly useful. It's # left up to the user to write a callback to do it if needed. raise RuntimeError("Clamping is not supported for open bounds.")
(self, bound: float, dir: 'te.Literal[1, -1]', open: bool) -> float
9,432
asyncclick.types
_describe_range
Describe the range for use in help text.
def _describe_range(self) -> str: """Describe the range for use in help text.""" if self.min is None: op = "<" if self.max_open else "<=" return f"x{op}{self.max}" if self.max is None: op = ">" if self.min_open else ">=" return f"x{op}{self.min}" lop = "<" if self.min_open else "<=" rop = "<" if self.max_open else "<=" return f"{self.min}{lop}x{rop}{self.max}"
(self) -> str
9,433
asyncclick.types
convert
null
def convert( self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"] ) -> t.Any: import operator rv = super().convert(value, param, ctx) lt_min: bool = self.min is not None and ( operator.le if self.min_open else operator.lt )(rv, self.min) gt_max: bool = self.max is not None and ( operator.ge if self.max_open else operator.gt )(rv, self.max) if self.clamp: if lt_min: return self._clamp(self.min, 1, self.min_open) # type: ignore if gt_max: return self._clamp(self.max, -1, self.max_open) # type: ignore if lt_min or gt_max: self.fail( _("{value} is not in the range {range}.").format( value=rv, range=self._describe_range() ), param, ctx, ) return rv
(self, value: Any, param: Optional[ForwardRef('Parameter')], ctx: Optional[ForwardRef('Context')]) -> Any
9,439
asyncclick.types
to_info_dict
null
def __init__( self, min: t.Optional[float] = None, max: t.Optional[float] = None, min_open: bool = False, max_open: bool = False, clamp: bool = False, ) -> None: self.min = min self.max = max self.min_open = min_open self.max_open = max_open self.clamp = clamp
(self) -> Dict[str, Any]
9,440
asyncclick.core
Group
A group allows a command to have subcommands attached. This is the most common way to implement nesting in Click. :param name: The name of the group command. :param commands: A dict mapping names to :class:`Command` objects. Can also be a list of :class:`Command`, which will use :attr:`Command.name` to create the dict. :param attrs: Other command arguments described in :class:`MultiCommand`, :class:`Command`, and :class:`BaseCommand`. .. versionchanged:: 8.0 The ``commands`` argument can be a list of command objects.
class Group(MultiCommand): """A group allows a command to have subcommands attached. This is the most common way to implement nesting in Click. :param name: The name of the group command. :param commands: A dict mapping names to :class:`Command` objects. Can also be a list of :class:`Command`, which will use :attr:`Command.name` to create the dict. :param attrs: Other command arguments described in :class:`MultiCommand`, :class:`Command`, and :class:`BaseCommand`. .. versionchanged:: 8.0 The ``commands`` argument can be a list of command objects. """ #: If set, this is used by the group's :meth:`command` decorator #: as the default :class:`Command` class. This is useful to make all #: subcommands use a custom command class. #: #: .. versionadded:: 8.0 command_class: t.Optional[t.Type[Command]] = None #: If set, this is used by the group's :meth:`group` decorator #: as the default :class:`Group` class. This is useful to make all #: subgroups use a custom group class. #: #: If set to the special value :class:`type` (literally #: ``group_class = type``), this group's class will be used as the #: default class. This makes a custom group class continue to make #: custom groups. #: #: .. versionadded:: 8.0 group_class: t.Optional[t.Union[t.Type["Group"], t.Type[type]]] = None # Literal[type] isn't valid, so use Type[type] def __init__( self, name: t.Optional[str] = None, commands: t.Optional[ t.Union[t.MutableMapping[str, Command], t.Sequence[Command]] ] = None, **attrs: t.Any, ) -> None: super().__init__(name, **attrs) if commands is None: commands = {} elif isinstance(commands, abc.Sequence): commands = {c.name: c for c in commands if c.name is not None} #: The registered subcommands by their exported names. self.commands: t.MutableMapping[str, Command] = commands def add_command(self, cmd: Command, name: t.Optional[str] = None) -> None: """Registers another :class:`Command` with this group. If the name is not provided, the name of the command is used. """ name = name or cmd.name if name is None: raise TypeError("Command has no name.") _check_multicommand(self, name, cmd, register=True) self.commands[name] = cmd @t.overload def command(self, __func: t.Callable[..., t.Any]) -> Command: ... @t.overload def command( self, *args: t.Any, **kwargs: t.Any ) -> t.Callable[[t.Callable[..., t.Any]], Command]: ... def command( self, *args: t.Any, **kwargs: t.Any ) -> t.Union[t.Callable[[t.Callable[..., t.Any]], Command], Command]: """A shortcut decorator for declaring and attaching a command to the group. This takes the same arguments as :func:`command` and immediately registers the created command with this group by calling :meth:`add_command`. To customize the command class used, set the :attr:`command_class` attribute. .. versionchanged:: 8.1 This decorator can be applied without parentheses. .. versionchanged:: 8.0 Added the :attr:`command_class` attribute. """ from .decorators import command func: t.Optional[t.Callable[..., t.Any]] = None if args and callable(args[0]): assert ( len(args) == 1 and not kwargs ), "Use 'command(**kwargs)(callable)' to provide arguments." (func,) = args args = () if self.command_class and kwargs.get("cls") is None: kwargs["cls"] = self.command_class def decorator(f: t.Callable[..., t.Any]) -> Command: cmd: Command = command(*args, **kwargs)(f) self.add_command(cmd) return cmd if func is not None: return decorator(func) return decorator @t.overload def group(self, __func: t.Callable[..., t.Any]) -> "Group": ... @t.overload def group( self, *args: t.Any, **kwargs: t.Any ) -> t.Callable[[t.Callable[..., t.Any]], "Group"]: ... def group( self, *args: t.Any, **kwargs: t.Any ) -> t.Union[t.Callable[[t.Callable[..., t.Any]], "Group"], "Group"]: """A shortcut decorator for declaring and attaching a group to the group. This takes the same arguments as :func:`group` and immediately registers the created group with this group by calling :meth:`add_command`. To customize the group class used, set the :attr:`group_class` attribute. .. versionchanged:: 8.1 This decorator can be applied without parentheses. .. versionchanged:: 8.0 Added the :attr:`group_class` attribute. """ from .decorators import group func: t.Optional[t.Callable[..., t.Any]] = None if args and callable(args[0]): assert ( len(args) == 1 and not kwargs ), "Use 'group(**kwargs)(callable)' to provide arguments." (func,) = args args = () if self.group_class is not None and kwargs.get("cls") is None: if self.group_class is type: kwargs["cls"] = type(self) else: kwargs["cls"] = self.group_class def decorator(f: t.Callable[..., t.Any]) -> "Group": cmd: Group = group(*args, **kwargs)(f) self.add_command(cmd) return cmd if func is not None: return decorator(func) return decorator def get_command(self, ctx: Context, cmd_name: str) -> t.Optional[Command]: return self.commands.get(cmd_name) def list_commands(self, ctx: Context) -> t.List[str]: return sorted(self.commands)
(name: Optional[str] = None, commands: Union[MutableMapping[str, asyncclick.core.Command], Sequence[asyncclick.core.Command], NoneType] = None, **attrs: Any) -> None
9,442
asyncclick.core
__init__
null
def __init__( self, name: t.Optional[str] = None, commands: t.Optional[ t.Union[t.MutableMapping[str, Command], t.Sequence[Command]] ] = None, **attrs: t.Any, ) -> None: super().__init__(name, **attrs) if commands is None: commands = {} elif isinstance(commands, abc.Sequence): commands = {c.name: c for c in commands if c.name is not None} #: The registered subcommands by their exported names. self.commands: t.MutableMapping[str, Command] = commands
(self, name: Optional[str] = None, commands: Union[MutableMapping[str, asyncclick.core.Command], Sequence[asyncclick.core.Command], NoneType] = None, **attrs: Any) -> NoneType
9,446
asyncclick.core
add_command
Registers another :class:`Command` with this group. If the name is not provided, the name of the command is used.
def add_command(self, cmd: Command, name: t.Optional[str] = None) -> None: """Registers another :class:`Command` with this group. If the name is not provided, the name of the command is used. """ name = name or cmd.name if name is None: raise TypeError("Command has no name.") _check_multicommand(self, name, cmd, register=True) self.commands[name] = cmd
(self, cmd: asyncclick.core.Command, name: Optional[str] = None) -> NoneType
9,448
asyncclick.core
command
A shortcut decorator for declaring and attaching a command to the group. This takes the same arguments as :func:`command` and immediately registers the created command with this group by calling :meth:`add_command`. To customize the command class used, set the :attr:`command_class` attribute. .. versionchanged:: 8.1 This decorator can be applied without parentheses. .. versionchanged:: 8.0 Added the :attr:`command_class` attribute.
def command( self, *args: t.Any, **kwargs: t.Any ) -> t.Union[t.Callable[[t.Callable[..., t.Any]], Command], Command]: """A shortcut decorator for declaring and attaching a command to the group. This takes the same arguments as :func:`command` and immediately registers the created command with this group by calling :meth:`add_command`. To customize the command class used, set the :attr:`command_class` attribute. .. versionchanged:: 8.1 This decorator can be applied without parentheses. .. versionchanged:: 8.0 Added the :attr:`command_class` attribute. """ from .decorators import command func: t.Optional[t.Callable[..., t.Any]] = None if args and callable(args[0]): assert ( len(args) == 1 and not kwargs ), "Use 'command(**kwargs)(callable)' to provide arguments." (func,) = args args = () if self.command_class and kwargs.get("cls") is None: kwargs["cls"] = self.command_class def decorator(f: t.Callable[..., t.Any]) -> Command: cmd: Command = command(*args, **kwargs)(f) self.add_command(cmd) return cmd if func is not None: return decorator(func) return decorator
(self, *args: Any, **kwargs: Any) -> Union[Callable[[Callable[..., Any]], asyncclick.core.Command], asyncclick.core.Command]
9,455
asyncclick.core
get_command
null
def get_command(self, ctx: Context, cmd_name: str) -> t.Optional[Command]: return self.commands.get(cmd_name)
(self, ctx: asyncclick.core.Context, cmd_name: str) -> Optional[asyncclick.core.Command]
9,462
asyncclick.core
group
A shortcut decorator for declaring and attaching a group to the group. This takes the same arguments as :func:`group` and immediately registers the created group with this group by calling :meth:`add_command`. To customize the group class used, set the :attr:`group_class` attribute. .. versionchanged:: 8.1 This decorator can be applied without parentheses. .. versionchanged:: 8.0 Added the :attr:`group_class` attribute.
def group( self, *args: t.Any, **kwargs: t.Any ) -> t.Union[t.Callable[[t.Callable[..., t.Any]], "Group"], "Group"]: """A shortcut decorator for declaring and attaching a group to the group. This takes the same arguments as :func:`group` and immediately registers the created group with this group by calling :meth:`add_command`. To customize the group class used, set the :attr:`group_class` attribute. .. versionchanged:: 8.1 This decorator can be applied without parentheses. .. versionchanged:: 8.0 Added the :attr:`group_class` attribute. """ from .decorators import group func: t.Optional[t.Callable[..., t.Any]] = None if args and callable(args[0]): assert ( len(args) == 1 and not kwargs ), "Use 'group(**kwargs)(callable)' to provide arguments." (func,) = args args = () if self.group_class is not None and kwargs.get("cls") is None: if self.group_class is type: kwargs["cls"] = type(self) else: kwargs["cls"] = self.group_class def decorator(f: t.Callable[..., t.Any]) -> "Group": cmd: Group = group(*args, **kwargs)(f) self.add_command(cmd) return cmd if func is not None: return decorator(func) return decorator
(self, *args: Any, **kwargs: Any) -> Union[Callable[[Callable[..., Any]], asyncclick.core.Group], asyncclick.core.Group]
9,464
asyncclick.core
list_commands
null
def list_commands(self, ctx: Context) -> t.List[str]: return sorted(self.commands)
(self, ctx: asyncclick.core.Context) -> List[str]
9,473
asyncclick.formatting
HelpFormatter
This class helps with formatting text-based help pages. It's usually just needed for very special internal cases, but it's also exposed so that developers can write their own fancy outputs. At present, it always writes into memory. :param indent_increment: the additional increment for each level. :param width: the width for the text. This defaults to the terminal width clamped to a maximum of 78.
class HelpFormatter: """This class helps with formatting text-based help pages. It's usually just needed for very special internal cases, but it's also exposed so that developers can write their own fancy outputs. At present, it always writes into memory. :param indent_increment: the additional increment for each level. :param width: the width for the text. This defaults to the terminal width clamped to a maximum of 78. """ def __init__( self, indent_increment: int = 2, width: t.Optional[int] = None, max_width: t.Optional[int] = None, ) -> None: import shutil self.indent_increment = indent_increment if max_width is None: max_width = 80 if width is None: width = FORCED_WIDTH if width is None: width = max(min(shutil.get_terminal_size().columns, max_width) - 2, 50) self.width = width self.current_indent = 0 self.buffer: t.List[str] = [] def write(self, string: str) -> None: """Writes a unicode string into the internal buffer.""" self.buffer.append(string) def indent(self) -> None: """Increases the indentation.""" self.current_indent += self.indent_increment def dedent(self) -> None: """Decreases the indentation.""" self.current_indent -= self.indent_increment def write_usage( self, prog: str, args: str = "", prefix: t.Optional[str] = None ) -> None: """Writes a usage line into the buffer. :param prog: the program name. :param args: whitespace separated list of arguments. :param prefix: The prefix for the first line. Defaults to ``"Usage: "``. """ if prefix is None: prefix = f"{_('Usage:')} " usage_prefix = f"{prefix:>{self.current_indent}}{prog} " text_width = self.width - self.current_indent if text_width >= (term_len(usage_prefix) + 20): # The arguments will fit to the right of the prefix. indent = " " * term_len(usage_prefix) self.write( wrap_text( args, text_width, initial_indent=usage_prefix, subsequent_indent=indent, ) ) else: # The prefix is too long, put the arguments on the next line. self.write(usage_prefix) self.write("\n") indent = " " * (max(self.current_indent, term_len(prefix)) + 4) self.write( wrap_text( args, text_width, initial_indent=indent, subsequent_indent=indent ) ) self.write("\n") def write_heading(self, heading: str) -> None: """Writes a heading into the buffer.""" self.write(f"{'':>{self.current_indent}}{heading}:\n") def write_paragraph(self) -> None: """Writes a paragraph into the buffer.""" if self.buffer: self.write("\n") def write_text(self, text: str) -> None: """Writes re-indented text into the buffer. This rewraps and preserves paragraphs. """ indent = " " * self.current_indent self.write( wrap_text( text, self.width, initial_indent=indent, subsequent_indent=indent, preserve_paragraphs=True, ) ) self.write("\n") def write_dl( self, rows: t.Sequence[t.Tuple[str, str]], col_max: int = 30, col_spacing: int = 2, ) -> None: """Writes a definition list into the buffer. This is how options and commands are usually formatted. :param rows: a list of two item tuples for the terms and values. :param col_max: the maximum width of the first column. :param col_spacing: the number of spaces between the first and second column. """ rows = list(rows) widths = measure_table(rows) if len(widths) != 2: raise TypeError("Expected two columns for definition list") first_col = min(widths[0], col_max) + col_spacing for first, second in iter_rows(rows, len(widths)): self.write(f"{'':>{self.current_indent}}{first}") if not second: self.write("\n") continue if term_len(first) <= first_col - col_spacing: self.write(" " * (first_col - term_len(first))) else: self.write("\n") self.write(" " * (first_col + self.current_indent)) text_width = max(self.width - first_col - 2, 10) wrapped_text = wrap_text(second, text_width, preserve_paragraphs=True) lines = wrapped_text.splitlines() if lines: self.write(f"{lines[0]}\n") for line in lines[1:]: self.write(f"{'':>{first_col + self.current_indent}}{line}\n") else: self.write("\n") @contextmanager def section(self, name: str) -> t.Iterator[None]: """Helpful context manager that writes a paragraph, a heading, and the indents. :param name: the section name that is written as heading. """ self.write_paragraph() self.write_heading(name) self.indent() try: yield finally: self.dedent() @contextmanager def indentation(self) -> t.Iterator[None]: """A context manager that increases the indentation.""" self.indent() try: yield finally: self.dedent() def getvalue(self) -> str: """Returns the buffer contents.""" return "".join(self.buffer)
(indent_increment: int = 2, width: Optional[int] = None, max_width: Optional[int] = None) -> None
9,474
asyncclick.formatting
__init__
null
def __init__( self, indent_increment: int = 2, width: t.Optional[int] = None, max_width: t.Optional[int] = None, ) -> None: import shutil self.indent_increment = indent_increment if max_width is None: max_width = 80 if width is None: width = FORCED_WIDTH if width is None: width = max(min(shutil.get_terminal_size().columns, max_width) - 2, 50) self.width = width self.current_indent = 0 self.buffer: t.List[str] = []
(self, indent_increment: int = 2, width: Optional[int] = None, max_width: Optional[int] = None) -> NoneType
9,475
asyncclick.formatting
dedent
Decreases the indentation.
def dedent(self) -> None: """Decreases the indentation.""" self.current_indent -= self.indent_increment
(self) -> NoneType
9,476
asyncclick.formatting
getvalue
Returns the buffer contents.
def getvalue(self) -> str: """Returns the buffer contents.""" return "".join(self.buffer)
(self) -> str
9,477
asyncclick.formatting
indent
Increases the indentation.
def indent(self) -> None: """Increases the indentation.""" self.current_indent += self.indent_increment
(self) -> NoneType
9,478
asyncclick.formatting
indentation
A context manager that increases the indentation.
def getvalue(self) -> str: """Returns the buffer contents.""" return "".join(self.buffer)
(self) -> Iterator[NoneType]
9,479
asyncclick.formatting
section
Helpful context manager that writes a paragraph, a heading, and the indents. :param name: the section name that is written as heading.
def getvalue(self) -> str: """Returns the buffer contents.""" return "".join(self.buffer)
(self, name: str) -> Iterator[NoneType]
9,480
asyncclick.formatting
write
Writes a unicode string into the internal buffer.
def write(self, string: str) -> None: """Writes a unicode string into the internal buffer.""" self.buffer.append(string)
(self, string: str) -> NoneType
9,481
asyncclick.formatting
write_dl
Writes a definition list into the buffer. This is how options and commands are usually formatted. :param rows: a list of two item tuples for the terms and values. :param col_max: the maximum width of the first column. :param col_spacing: the number of spaces between the first and second column.
def write_dl( self, rows: t.Sequence[t.Tuple[str, str]], col_max: int = 30, col_spacing: int = 2, ) -> None: """Writes a definition list into the buffer. This is how options and commands are usually formatted. :param rows: a list of two item tuples for the terms and values. :param col_max: the maximum width of the first column. :param col_spacing: the number of spaces between the first and second column. """ rows = list(rows) widths = measure_table(rows) if len(widths) != 2: raise TypeError("Expected two columns for definition list") first_col = min(widths[0], col_max) + col_spacing for first, second in iter_rows(rows, len(widths)): self.write(f"{'':>{self.current_indent}}{first}") if not second: self.write("\n") continue if term_len(first) <= first_col - col_spacing: self.write(" " * (first_col - term_len(first))) else: self.write("\n") self.write(" " * (first_col + self.current_indent)) text_width = max(self.width - first_col - 2, 10) wrapped_text = wrap_text(second, text_width, preserve_paragraphs=True) lines = wrapped_text.splitlines() if lines: self.write(f"{lines[0]}\n") for line in lines[1:]: self.write(f"{'':>{first_col + self.current_indent}}{line}\n") else: self.write("\n")
(self, rows: Sequence[Tuple[str, str]], col_max: int = 30, col_spacing: int = 2) -> NoneType
9,482
asyncclick.formatting
write_heading
Writes a heading into the buffer.
def write_heading(self, heading: str) -> None: """Writes a heading into the buffer.""" self.write(f"{'':>{self.current_indent}}{heading}:\n")
(self, heading: str) -> NoneType
9,483
asyncclick.formatting
write_paragraph
Writes a paragraph into the buffer.
def write_paragraph(self) -> None: """Writes a paragraph into the buffer.""" if self.buffer: self.write("\n")
(self) -> NoneType
9,484
asyncclick.formatting
write_text
Writes re-indented text into the buffer. This rewraps and preserves paragraphs.
def write_text(self, text: str) -> None: """Writes re-indented text into the buffer. This rewraps and preserves paragraphs. """ indent = " " * self.current_indent self.write( wrap_text( text, self.width, initial_indent=indent, subsequent_indent=indent, preserve_paragraphs=True, ) ) self.write("\n")
(self, text: str) -> NoneType
9,485
asyncclick.formatting
write_usage
Writes a usage line into the buffer. :param prog: the program name. :param args: whitespace separated list of arguments. :param prefix: The prefix for the first line. Defaults to ``"Usage: "``.
def write_usage( self, prog: str, args: str = "", prefix: t.Optional[str] = None ) -> None: """Writes a usage line into the buffer. :param prog: the program name. :param args: whitespace separated list of arguments. :param prefix: The prefix for the first line. Defaults to ``"Usage: "``. """ if prefix is None: prefix = f"{_('Usage:')} " usage_prefix = f"{prefix:>{self.current_indent}}{prog} " text_width = self.width - self.current_indent if text_width >= (term_len(usage_prefix) + 20): # The arguments will fit to the right of the prefix. indent = " " * term_len(usage_prefix) self.write( wrap_text( args, text_width, initial_indent=usage_prefix, subsequent_indent=indent, ) ) else: # The prefix is too long, put the arguments on the next line. self.write(usage_prefix) self.write("\n") indent = " " * (max(self.current_indent, term_len(prefix)) + 4) self.write( wrap_text( args, text_width, initial_indent=indent, subsequent_indent=indent ) ) self.write("\n")
(self, prog: str, args: str = '', prefix: Optional[str] = None) -> NoneType
9,486
asyncclick.types
IntRange
Restrict an :data:`click.INT` value to a range of accepted values. See :ref:`ranges`. If ``min`` or ``max`` are not passed, any value is accepted in that direction. If ``min_open`` or ``max_open`` are enabled, the corresponding boundary is not included in the range. If ``clamp`` is enabled, a value outside the range is clamped to the boundary instead of failing. .. versionchanged:: 8.0 Added the ``min_open`` and ``max_open`` parameters.
class IntRange(_NumberRangeBase, IntParamType): """Restrict an :data:`click.INT` value to a range of accepted values. See :ref:`ranges`. If ``min`` or ``max`` are not passed, any value is accepted in that direction. If ``min_open`` or ``max_open`` are enabled, the corresponding boundary is not included in the range. If ``clamp`` is enabled, a value outside the range is clamped to the boundary instead of failing. .. versionchanged:: 8.0 Added the ``min_open`` and ``max_open`` parameters. """ name = "integer range" def _clamp( # type: ignore self, bound: int, dir: "te.Literal[1, -1]", open: bool ) -> int: if not open: return bound return bound + dir
(min: Optional[float] = None, max: Optional[float] = None, min_open: bool = False, max_open: bool = False, clamp: bool = False) -> None
9,490
asyncclick.types
_clamp
null
def _clamp( # type: ignore self, bound: int, dir: "te.Literal[1, -1]", open: bool ) -> int: if not open: return bound return bound + dir
(self, bound: int, dir: 'te.Literal[1, -1]', open: bool) -> int
9,499
asyncclick.exceptions
MissingParameter
Raised if click required an option or argument but it was not provided when invoking the script. .. versionadded:: 4.0 :param param_type: a string that indicates the type of the parameter. The default is to inherit the parameter type from the given `param`. Valid values are ``'parameter'``, ``'option'`` or ``'argument'``.
class MissingParameter(BadParameter): """Raised if click required an option or argument but it was not provided when invoking the script. .. versionadded:: 4.0 :param param_type: a string that indicates the type of the parameter. The default is to inherit the parameter type from the given `param`. Valid values are ``'parameter'``, ``'option'`` or ``'argument'``. """ def __init__( self, message: t.Optional[str] = None, ctx: t.Optional["Context"] = None, param: t.Optional["Parameter"] = None, param_hint: t.Optional[str] = None, param_type: t.Optional[str] = None, ) -> None: super().__init__(message or "", ctx, param, param_hint) self.param_type = param_type def format_message(self) -> str: if self.param_hint is not None: param_hint: t.Optional[str] = self.param_hint elif self.param is not None: param_hint = self.param.get_error_hint(self.ctx) # type: ignore else: param_hint = None param_hint = _join_param_hints(param_hint) param_hint = f" {param_hint}" if param_hint else "" param_type = self.param_type if param_type is None and self.param is not None: param_type = self.param.param_type_name msg = self.message if self.param is not None: msg_extra = self.param.type.get_missing_message(self.param) if msg_extra: if msg: msg += f". {msg_extra}" else: msg = msg_extra msg = f" {msg}" if msg else "" # Translate param_type for known types. if param_type == "argument": missing = _("Missing argument") elif param_type == "option": missing = _("Missing option") elif param_type == "parameter": missing = _("Missing parameter") else: missing = _("Missing {param_type}").format(param_type=param_type) return f"{missing}{param_hint}.{msg}" def __str__(self) -> str: if not self.message: param_name = self.param.name if self.param else None return _("Missing parameter: {param_name}").format(param_name=param_name) else: return self.message
(message: Optional[str] = None, ctx: Optional[ForwardRef('Context')] = None, param: Optional[ForwardRef('Parameter')] = None, param_hint: Optional[str] = None, param_type: Optional[str] = None) -> None
9,500
asyncclick.exceptions
__init__
null
def __init__( self, message: t.Optional[str] = None, ctx: t.Optional["Context"] = None, param: t.Optional["Parameter"] = None, param_hint: t.Optional[str] = None, param_type: t.Optional[str] = None, ) -> None: super().__init__(message or "", ctx, param, param_hint) self.param_type = param_type
(self, message: Optional[str] = None, ctx: Optional[ForwardRef('Context')] = None, param: Optional[ForwardRef('Parameter')] = None, param_hint: Optional[str] = None, param_type: Optional[str] = None) -> None
9,501
asyncclick.exceptions
__str__
null
def __str__(self) -> str: if not self.message: param_name = self.param.name if self.param else None return _("Missing parameter: {param_name}").format(param_name=param_name) else: return self.message
(self) -> str
9,502
asyncclick.exceptions
format_message
null
def format_message(self) -> str: if self.param_hint is not None: param_hint: t.Optional[str] = self.param_hint elif self.param is not None: param_hint = self.param.get_error_hint(self.ctx) # type: ignore else: param_hint = None param_hint = _join_param_hints(param_hint) param_hint = f" {param_hint}" if param_hint else "" param_type = self.param_type if param_type is None and self.param is not None: param_type = self.param.param_type_name msg = self.message if self.param is not None: msg_extra = self.param.type.get_missing_message(self.param) if msg_extra: if msg: msg += f". {msg_extra}" else: msg = msg_extra msg = f" {msg}" if msg else "" # Translate param_type for known types. if param_type == "argument": missing = _("Missing argument") elif param_type == "option": missing = _("Missing option") elif param_type == "parameter": missing = _("Missing parameter") else: missing = _("Missing {param_type}").format(param_type=param_type) return f"{missing}{param_hint}.{msg}"
(self) -> str
9,504
asyncclick.core
MultiCommand
A multi command is the basic implementation of a command that dispatches to subcommands. The most common version is the :class:`Group`. :param invoke_without_command: this controls how the multi command itself is invoked. By default it's only invoked if a subcommand is provided. :param no_args_is_help: this controls what happens if no arguments are provided. This option is enabled by default if `invoke_without_command` is disabled or disabled if it's enabled. If enabled this will add ``--help`` as argument if no arguments are passed. :param subcommand_metavar: the string that is used in the documentation to indicate the subcommand place. :param chain: if this is set to `True` chaining of multiple subcommands is enabled. This restricts the form of commands in that they cannot have optional arguments but it allows multiple commands to be chained together. :param result_callback: The result callback to attach to this multi command. This can be set or changed later with the :meth:`result_callback` decorator. :param attrs: Other command arguments described in :class:`Command`.
class MultiCommand(Command): """A multi command is the basic implementation of a command that dispatches to subcommands. The most common version is the :class:`Group`. :param invoke_without_command: this controls how the multi command itself is invoked. By default it's only invoked if a subcommand is provided. :param no_args_is_help: this controls what happens if no arguments are provided. This option is enabled by default if `invoke_without_command` is disabled or disabled if it's enabled. If enabled this will add ``--help`` as argument if no arguments are passed. :param subcommand_metavar: the string that is used in the documentation to indicate the subcommand place. :param chain: if this is set to `True` chaining of multiple subcommands is enabled. This restricts the form of commands in that they cannot have optional arguments but it allows multiple commands to be chained together. :param result_callback: The result callback to attach to this multi command. This can be set or changed later with the :meth:`result_callback` decorator. :param attrs: Other command arguments described in :class:`Command`. """ allow_extra_args = True allow_interspersed_args = False def __init__( self, name: t.Optional[str] = None, invoke_without_command: bool = False, no_args_is_help: t.Optional[bool] = None, subcommand_metavar: t.Optional[str] = None, chain: bool = False, result_callback: t.Optional[t.Callable[..., t.Any]] = None, **attrs: t.Any, ) -> None: super().__init__(name, **attrs) if no_args_is_help is None: no_args_is_help = not invoke_without_command self.no_args_is_help = no_args_is_help self.invoke_without_command = invoke_without_command if subcommand_metavar is None: if chain: subcommand_metavar = "COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]..." else: subcommand_metavar = "COMMAND [ARGS]..." self.subcommand_metavar = subcommand_metavar self.chain = chain # The result callback that is stored. This can be set or # overridden with the :func:`result_callback` decorator. self._result_callback = result_callback if self.chain: for param in self.params: if isinstance(param, Argument) and not param.required: raise RuntimeError( "Multi commands in chain mode cannot have" " optional arguments." ) async def to_info_dict(self, ctx: Context) -> t.Dict[str, t.Any]: info_dict = await super().to_info_dict(ctx) commands = {} for name in self.list_commands(ctx): command = self.get_command(ctx, name) if command is None: continue sub_ctx = ctx._make_sub_context(command) async with sub_ctx.scope(cleanup=False): commands[name] = await command.to_info_dict(sub_ctx) info_dict.update(commands=commands, chain=self.chain) return info_dict def collect_usage_pieces(self, ctx: Context) -> t.List[str]: rv = super().collect_usage_pieces(ctx) rv.append(self.subcommand_metavar) return rv def format_options(self, ctx: Context, formatter: HelpFormatter) -> None: super().format_options(ctx, formatter) self.format_commands(ctx, formatter) def result_callback(self, replace: bool = False) -> t.Callable[[F], F]: """Adds a result callback to the command. By default if a result callback is already registered this will chain them but this can be disabled with the `replace` parameter. The result callback is invoked with the return value of the subcommand (or the list of return values from all subcommands if chaining is enabled) as well as the parameters as they would be passed to the main callback. Example:: @click.group() @click.option('-i', '--input', default=23) def cli(input): return 42 @cli.result_callback() def process_result(result, input): return result + input :param replace: if set to `True` an already existing result callback will be removed. .. versionchanged:: 8.0 Renamed from ``resultcallback``. .. versionadded:: 3.0 """ def decorator(f: F) -> F: old_callback = self._result_callback if old_callback is None or replace: self._result_callback = f return f def function(__value, *args, **kwargs): # type: ignore inner = old_callback(__value, *args, **kwargs) return f(inner, *args, **kwargs) self._result_callback = rv = update_wrapper(t.cast(F, function), f) return rv return decorator def format_commands(self, ctx: Context, formatter: HelpFormatter) -> None: """Extra format methods for multi methods that adds all the commands after the options. """ commands = [] for subcommand in self.list_commands(ctx): cmd = self.get_command(ctx, subcommand) # What is this, the tool lied about a command. Ignore it if cmd is None: continue if cmd.hidden: continue commands.append((subcommand, cmd)) # allow for 3 times the default spacing if len(commands): limit = formatter.width - 6 - max(len(cmd[0]) for cmd in commands) rows = [] for subcommand, cmd in commands: help = cmd.get_short_help_str(limit) rows.append((subcommand, help)) if rows: with formatter.section(_("Commands")): formatter.write_dl(rows) async def parse_args(self, ctx: Context, args: t.List[str]) -> t.List[str]: if not args and self.no_args_is_help and not ctx.resilient_parsing: echo(ctx.get_help(), color=ctx.color) ctx.exit() rest = await super().parse_args(ctx, args) if self.chain: ctx.protected_args = rest ctx.args = [] elif rest: ctx.protected_args, ctx.args = rest[:1], rest[1:] return ctx.args async def invoke(self, ctx: Context) -> t.Any: async def _process_result(value: t.Any) -> t.Any: if self._result_callback is not None: value = await ctx.invoke(self._result_callback, value, **ctx.params) return value if not ctx.protected_args: if self.invoke_without_command: # No subcommand was invoked, so the result callback is # invoked with the group return value for regular # groups, or an empty list for chained groups. async with ctx: rv = await super().invoke(ctx) return await _process_result([] if self.chain else rv) ctx.fail(_("Missing command.")) # Fetch args back out args = [*ctx.protected_args, *ctx.args] ctx.args = [] ctx.protected_args = [] # If we're not in chain mode, we only allow the invocation of a # single command but we also inform the current context about the # name of the command to invoke. if not self.chain: # Make sure the context is entered so we do not clean up # resources until the result processor has worked. async with ctx: cmd_name, cmd, args = await self.resolve_command(ctx, args) assert cmd is not None ctx.invoked_subcommand = cmd_name await super().invoke(ctx) sub_ctx = await cmd.make_context(cmd_name, args, parent=ctx) async with sub_ctx: return await _process_result(await sub_ctx.command.invoke(sub_ctx)) # In chain mode we create the contexts step by step, but after the # base command has been invoked. Because at that point we do not # know the subcommands yet, the invoked subcommand attribute is # set to ``*`` to inform the command that subcommands are executed # but nothing else. async with ctx: ctx.invoked_subcommand = "*" if args else None await super().invoke(ctx) # Otherwise we make every single context and invoke them in a # chain. In that case the return value to the result processor # is the list of all invoked subcommand's results. contexts = [] while args: cmd_name, cmd, args = await self.resolve_command(ctx, args) assert cmd is not None sub_ctx = await cmd.make_context( cmd_name, args, parent=ctx, allow_extra_args=True, allow_interspersed_args=False, ) contexts.append(sub_ctx) args, sub_ctx.args = sub_ctx.args, [] rv = [] for sub_ctx in contexts: async with sub_ctx: rv.append(await sub_ctx.command.invoke(sub_ctx)) return await _process_result(rv) async def resolve_command( self, ctx: Context, args: t.List[str] ) -> t.Tuple[t.Optional[str], t.Optional[Command], t.List[str]]: cmd_name = make_str(args[0]) original_cmd_name = cmd_name # Get the command cmd = self.get_command(ctx, cmd_name) # If we can't find the command but there is a normalization # function available, we try with that one. if cmd is None and ctx.token_normalize_func is not None: cmd_name = ctx.token_normalize_func(cmd_name) cmd = self.get_command(ctx, cmd_name) # If we don't find the command we want to show an error message # to the user that it was not provided. However, there is # something else we should do: if the first argument looks like # an option we want to kick off parsing again for arguments to # resolve things like --help which now should go to the main # place. if cmd is None and not ctx.resilient_parsing: if split_opt(cmd_name)[0]: await self.parse_args(ctx, ctx.args) ctx.fail(_("No such command {name!r}.").format(name=original_cmd_name)) return cmd_name if cmd else None, cmd, args[1:] def get_command(self, ctx: Context, cmd_name: str) -> t.Optional[Command]: """Given a context and a command name, this returns a :class:`Command` object if it exists or returns `None`. """ raise NotImplementedError def list_commands(self, ctx: Context) -> t.List[str]: """Returns a list of subcommand names in the order they should appear. """ return [] def shell_complete(self, ctx: Context, incomplete: str) -> t.List["CompletionItem"]: """Return a list of completions for the incomplete value. Looks at the names of options, subcommands, and chained multi-commands. :param ctx: Invocation context for this command. :param incomplete: Value being completed. May be empty. .. versionadded:: 8.0 """ from .shell_completion import CompletionItem results = [ CompletionItem(name, help=command.get_short_help_str()) for name, command in _complete_visible_commands(ctx, incomplete) ] results.extend(super().shell_complete(ctx, incomplete)) return results
(name: Optional[str] = None, invoke_without_command: bool = False, no_args_is_help: Optional[bool] = None, subcommand_metavar: Optional[str] = None, chain: bool = False, result_callback: Optional[Callable[..., Any]] = None, **attrs: Any) -> None
9,517
asyncclick.core
get_command
Given a context and a command name, this returns a :class:`Command` object if it exists or returns `None`.
def get_command(self, ctx: Context, cmd_name: str) -> t.Optional[Command]: """Given a context and a command name, this returns a :class:`Command` object if it exists or returns `None`. """ raise NotImplementedError
(self, ctx: asyncclick.core.Context, cmd_name: str) -> Optional[asyncclick.core.Command]
9,525
asyncclick.core
list_commands
Returns a list of subcommand names in the order they should appear.
def list_commands(self, ctx: Context) -> t.List[str]: """Returns a list of subcommand names in the order they should appear. """ return []
(self, ctx: asyncclick.core.Context) -> List[str]
9,534
asyncclick.exceptions
NoSuchOption
Raised if click attempted to handle an option that does not exist. .. versionadded:: 4.0
class NoSuchOption(UsageError): """Raised if click attempted to handle an option that does not exist. .. versionadded:: 4.0 """ def __init__( self, option_name: str, message: t.Optional[str] = None, possibilities: t.Optional[t.Sequence[str]] = None, ctx: t.Optional["Context"] = None, ) -> None: if message is None: message = _("No such option: {name}").format(name=option_name) super().__init__(message, ctx) self.option_name = option_name self.possibilities = possibilities def format_message(self) -> str: if not self.possibilities: return self.message possibility_str = ", ".join(sorted(self.possibilities)) suggest = ngettext( "Did you mean {possibility}?", "(Possible options: {possibilities})", len(self.possibilities), ).format(possibility=possibility_str, possibilities=possibility_str) return f"{self.message} {suggest}"
(option_name: str, message: Optional[str] = None, possibilities: Optional[Sequence[str]] = None, ctx: Optional[ForwardRef('Context')] = None) -> None
9,535
asyncclick.exceptions
__init__
null
def __init__( self, option_name: str, message: t.Optional[str] = None, possibilities: t.Optional[t.Sequence[str]] = None, ctx: t.Optional["Context"] = None, ) -> None: if message is None: message = _("No such option: {name}").format(name=option_name) super().__init__(message, ctx) self.option_name = option_name self.possibilities = possibilities
(self, option_name: str, message: Optional[str] = None, possibilities: Optional[Sequence[str]] = None, ctx: Optional[ForwardRef('Context')] = None) -> None
9,537
asyncclick.exceptions
format_message
null
def format_message(self) -> str: if not self.possibilities: return self.message possibility_str = ", ".join(sorted(self.possibilities)) suggest = ngettext( "Did you mean {possibility}?", "(Possible options: {possibilities})", len(self.possibilities), ).format(possibility=possibility_str, possibilities=possibility_str) return f"{self.message} {suggest}"
(self) -> str
9,539
asyncclick.core
Option
Options are usually optional values on the command line and have some extra features that arguments don't have. All other parameters are passed onwards to the parameter constructor. :param show_default: Show the default value for this option in its help text. Values are not shown by default, unless :attr:`Context.show_default` is ``True``. If this value is a string, it shows that string in parentheses instead of the actual value. This is particularly useful for dynamic options. For single option boolean flags, the default remains hidden if its value is ``False``. :param show_envvar: Controls if an environment variable should be shown on the help page. Normally, environment variables are not shown. :param prompt: If set to ``True`` or a non empty string then the user will be prompted for input. If set to ``True`` the prompt will be the option name capitalized. :param confirmation_prompt: Prompt a second time to confirm the value if it was prompted for. Can be set to a string instead of ``True`` to customize the message. :param prompt_required: If set to ``False``, the user will be prompted for input only when the option was specified as a flag without a value. :param hide_input: If this is ``True`` then the input on the prompt will be hidden from the user. This is useful for password input. :param is_flag: forces this option to act as a flag. The default is auto detection. :param flag_value: which value should be used for this flag if it's enabled. This is set to a boolean automatically if the option string contains a slash to mark two options. :param multiple: if this is set to `True` then the argument is accepted multiple times and recorded. This is similar to ``nargs`` in how it works but supports arbitrary number of arguments. :param count: this flag makes an option increment an integer. :param allow_from_autoenv: if this is enabled then the value of this parameter will be pulled from an environment variable in case a prefix is defined on the context. :param help: the help string. :param hidden: hide this option from help outputs. :param attrs: Other command arguments described in :class:`Parameter`. .. versionchanged:: 8.1.0 Help text indentation is cleaned here instead of only in the ``@option`` decorator. .. versionchanged:: 8.1.0 The ``show_default`` parameter overrides ``Context.show_default``. .. versionchanged:: 8.1.0 The default of a single option boolean flag is not shown if the default value is ``False``. .. versionchanged:: 8.0.1 ``type`` is detected from ``flag_value`` if given.
class Option(Parameter): """Options are usually optional values on the command line and have some extra features that arguments don't have. All other parameters are passed onwards to the parameter constructor. :param show_default: Show the default value for this option in its help text. Values are not shown by default, unless :attr:`Context.show_default` is ``True``. If this value is a string, it shows that string in parentheses instead of the actual value. This is particularly useful for dynamic options. For single option boolean flags, the default remains hidden if its value is ``False``. :param show_envvar: Controls if an environment variable should be shown on the help page. Normally, environment variables are not shown. :param prompt: If set to ``True`` or a non empty string then the user will be prompted for input. If set to ``True`` the prompt will be the option name capitalized. :param confirmation_prompt: Prompt a second time to confirm the value if it was prompted for. Can be set to a string instead of ``True`` to customize the message. :param prompt_required: If set to ``False``, the user will be prompted for input only when the option was specified as a flag without a value. :param hide_input: If this is ``True`` then the input on the prompt will be hidden from the user. This is useful for password input. :param is_flag: forces this option to act as a flag. The default is auto detection. :param flag_value: which value should be used for this flag if it's enabled. This is set to a boolean automatically if the option string contains a slash to mark two options. :param multiple: if this is set to `True` then the argument is accepted multiple times and recorded. This is similar to ``nargs`` in how it works but supports arbitrary number of arguments. :param count: this flag makes an option increment an integer. :param allow_from_autoenv: if this is enabled then the value of this parameter will be pulled from an environment variable in case a prefix is defined on the context. :param help: the help string. :param hidden: hide this option from help outputs. :param attrs: Other command arguments described in :class:`Parameter`. .. versionchanged:: 8.1.0 Help text indentation is cleaned here instead of only in the ``@option`` decorator. .. versionchanged:: 8.1.0 The ``show_default`` parameter overrides ``Context.show_default``. .. versionchanged:: 8.1.0 The default of a single option boolean flag is not shown if the default value is ``False``. .. versionchanged:: 8.0.1 ``type`` is detected from ``flag_value`` if given. """ param_type_name = "option" def __init__( self, param_decls: t.Optional[t.Sequence[str]] = None, show_default: t.Union[bool, str, None] = None, prompt: t.Union[bool, str] = False, confirmation_prompt: t.Union[bool, str] = False, prompt_required: bool = True, hide_input: bool = False, is_flag: t.Optional[bool] = None, flag_value: t.Optional[t.Any] = None, multiple: bool = False, count: bool = False, allow_from_autoenv: bool = True, type: t.Optional[t.Union[types.ParamType, t.Any]] = None, help: t.Optional[str] = None, hidden: bool = False, show_choices: bool = True, show_envvar: bool = False, **attrs: t.Any, ) -> None: if help: help = inspect.cleandoc(help) default_is_missing = "default" not in attrs super().__init__(param_decls, type=type, multiple=multiple, **attrs) if prompt is True: if self.name is None: raise TypeError("'name' is required with 'prompt=True'.") prompt_text: t.Optional[str] = self.name.replace("_", " ").capitalize() elif prompt is False: prompt_text = None else: prompt_text = prompt self.prompt = prompt_text self.confirmation_prompt = confirmation_prompt self.prompt_required = prompt_required self.hide_input = hide_input self.hidden = hidden # If prompt is enabled but not required, then the option can be # used as a flag to indicate using prompt or flag_value. self._flag_needs_value = self.prompt is not None and not self.prompt_required if is_flag is None: if flag_value is not None: # Implicitly a flag because flag_value was set. is_flag = True elif self._flag_needs_value: # Not a flag, but when used as a flag it shows a prompt. is_flag = False else: # Implicitly a flag because flag options were given. is_flag = bool(self.secondary_opts) elif is_flag is False and not self._flag_needs_value: # Not a flag, and prompt is not enabled, can be used as a # flag if flag_value is set. self._flag_needs_value = flag_value is not None self.default: t.Union[t.Any, t.Callable[[], t.Any]] if is_flag and default_is_missing and not self.required: if multiple: self.default = () else: self.default = False if flag_value is None: flag_value = not self.default self.type: types.ParamType if is_flag and type is None: # Re-guess the type from the flag value instead of the # default. self.type = types.convert_type(None, flag_value) self.is_flag: bool = is_flag self.is_bool_flag: bool = is_flag and isinstance(self.type, types.BoolParamType) self.flag_value: t.Any = flag_value # Counting self.count = count if count: if type is None: self.type = types.IntRange(min=0) if default_is_missing: self.default = 0 self.allow_from_autoenv = allow_from_autoenv self.help = help self.show_default = show_default self.show_choices = show_choices self.show_envvar = show_envvar if __debug__: if self.nargs == -1: raise TypeError("nargs=-1 is not supported for options.") if self.prompt and self.is_flag and not self.is_bool_flag: raise TypeError("'prompt' is not valid for non-boolean flag.") if not self.is_bool_flag and self.secondary_opts: raise TypeError("Secondary flag is not valid for non-boolean flag.") if self.is_bool_flag and self.hide_input and self.prompt is not None: raise TypeError( "'prompt' with 'hide_input' is not valid for boolean flag." ) if self.count: if self.multiple: raise TypeError("'count' is not valid with 'multiple'.") if self.is_flag: raise TypeError("'count' is not valid with 'is_flag'.") async def to_info_dict(self) -> t.Dict[str, t.Any]: info_dict = await super().to_info_dict() info_dict.update( help=self.help, prompt=self.prompt, is_flag=self.is_flag, flag_value=self.flag_value, count=self.count, hidden=self.hidden, ) return info_dict def _parse_decls( self, decls: t.Sequence[str], expose_value: bool ) -> t.Tuple[t.Optional[str], t.List[str], t.List[str]]: opts = [] secondary_opts = [] name = None possible_names = [] for decl in decls: if decl.isidentifier(): if name is not None: raise TypeError(f"Name '{name}' defined twice") name = decl else: split_char = ";" if decl[:1] == "/" else "/" if split_char in decl: first, second = decl.split(split_char, 1) first = first.rstrip() if first: possible_names.append(split_opt(first)) opts.append(first) second = second.lstrip() if second: secondary_opts.append(second.lstrip()) if first == second: raise ValueError( f"Boolean option {decl!r} cannot use the" " same flag for true/false." ) else: possible_names.append(split_opt(decl)) opts.append(decl) if name is None and possible_names: possible_names.sort(key=lambda x: -len(x[0])) # group long options first name = possible_names[0][1].replace("-", "_").lower() if not name.isidentifier(): name = None if name is None: if not expose_value: return None, opts, secondary_opts raise TypeError("Could not determine name for option") if not opts and not secondary_opts: raise TypeError( f"No options defined but a name was passed ({name})." " Did you mean to declare an argument instead? Did" f" you mean to pass '--{name}'?" ) return name, opts, secondary_opts def add_to_parser(self, parser: OptionParser, ctx: Context) -> None: if self.multiple: action = "append" elif self.count: action = "count" else: action = "store" if self.is_flag: action = f"{action}_const" if self.is_bool_flag and self.secondary_opts: parser.add_option( obj=self, opts=self.opts, dest=self.name, action=action, const=True ) parser.add_option( obj=self, opts=self.secondary_opts, dest=self.name, action=action, const=False, ) else: parser.add_option( obj=self, opts=self.opts, dest=self.name, action=action, const=self.flag_value, ) else: parser.add_option( obj=self, opts=self.opts, dest=self.name, action=action, nargs=self.nargs, ) def get_help_record(self, ctx: Context) -> t.Optional[t.Tuple[str, str]]: if self.hidden: return None any_prefix_is_slash = False def _write_opts(opts: t.Sequence[str]) -> str: nonlocal any_prefix_is_slash rv, any_slashes = join_options(opts) if any_slashes: any_prefix_is_slash = True if not self.is_flag and not self.count: rv += f" {self.make_metavar()}" return rv rv = [_write_opts(self.opts)] if self.secondary_opts: rv.append(_write_opts(self.secondary_opts)) help = self.help or "" extra = [] if self.show_envvar: envvar = self.envvar if envvar is None: if ( self.allow_from_autoenv and ctx.auto_envvar_prefix is not None and self.name is not None ): envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}" if envvar is not None: var_str = ( envvar if isinstance(envvar, str) else ", ".join(str(d) for d in envvar) ) extra.append(_("env var: {var}").format(var=var_str)) # Temporarily enable resilient parsing to avoid type casting # failing for the default. Might be possible to extend this to # help formatting in general. resilient = ctx.resilient_parsing ctx.resilient_parsing = True try: default_value = self.get_default(ctx, call=False) finally: ctx.resilient_parsing = resilient show_default = False show_default_is_str = False if self.show_default is not None: if isinstance(self.show_default, str): show_default_is_str = show_default = True else: show_default = self.show_default elif ctx.show_default is not None: show_default = ctx.show_default if show_default_is_str or (show_default and (default_value is not None)): if show_default_is_str: default_string = f"({self.show_default})" elif isinstance(default_value, (list, tuple)): default_string = ", ".join(str(d) for d in default_value) elif inspect.isfunction(default_value): default_string = _("(dynamic)") elif self.is_bool_flag and self.secondary_opts: # For boolean flags that have distinct True/False opts, # use the opt without prefix instead of the value. default_string = split_opt( (self.opts if self.default else self.secondary_opts)[0] )[1] elif self.is_bool_flag and not self.secondary_opts and not default_value: default_string = "" else: default_string = str(default_value) if default_string: extra.append(_("default: {default}").format(default=default_string)) if ( isinstance(self.type, types._NumberRangeBase) # skip count with default range type and not (self.count and self.type.min == 0 and self.type.max is None) ): range_str = self.type._describe_range() if range_str: extra.append(range_str) if self.required: extra.append(_("required")) if extra: extra_str = "; ".join(extra) help = f"{help} [{extra_str}]" if help else f"[{extra_str}]" return ("; " if any_prefix_is_slash else " / ").join(rv), help @t.overload def get_default( self, ctx: Context, call: "te.Literal[True]" = True ) -> t.Optional[t.Any]: ... @t.overload def get_default( self, ctx: Context, call: bool = ... ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]: ... def get_default( self, ctx: Context, call: bool = True ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]: # If we're a non boolean flag our default is more complex because # we need to look at all flags in the same group to figure out # if we're the default one in which case we return the flag # value as default. if self.is_flag and not self.is_bool_flag: for param in ctx.command.params: if param.name == self.name and param.default: return t.cast(Option, param).flag_value return None return super().get_default(ctx, call=call) def prompt_for_value(self, ctx: Context) -> t.Any: """This is an alternative flow that can be activated in the full value processing if a value does not exist. It will prompt the user until a valid value exists and then returns the processed value as result. """ assert self.prompt is not None # Calculate the default before prompting anything to be stable. default = self.get_default(ctx) # If this is a prompt for a flag we need to handle this # differently. if self.is_bool_flag: return confirm(self.prompt, default) return prompt( self.prompt, default=default, type=self.type, hide_input=self.hide_input, show_choices=self.show_choices, confirmation_prompt=self.confirmation_prompt, value_proc=lambda x: self.process_value(ctx, x), ) def resolve_envvar_value(self, ctx: Context) -> t.Optional[str]: rv = super().resolve_envvar_value(ctx) if rv is not None: return rv if ( self.allow_from_autoenv and ctx.auto_envvar_prefix is not None and self.name is not None ): envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}" rv = os.environ.get(envvar) if rv: return rv return None def value_from_envvar(self, ctx: Context) -> t.Optional[t.Any]: rv: t.Optional[t.Any] = self.resolve_envvar_value(ctx) if rv is None: return None value_depth = (self.nargs != 1) + bool(self.multiple) if value_depth > 0: rv = self.type.split_envvar_value(rv) if self.multiple and self.nargs != 1: rv = batch(rv, self.nargs) return rv def consume_value( self, ctx: Context, opts: t.Mapping[str, "Parameter"] ) -> t.Tuple[t.Any, ParameterSource]: value, source = super().consume_value(ctx, opts) # The parser will emit a sentinel value if the option can be # given as a flag without a value. This is different from None # to distinguish from the flag not being given at all. if value is _flag_needs_value: if self.prompt is not None and not ctx.resilient_parsing: value = self.prompt_for_value(ctx) source = ParameterSource.PROMPT else: value = self.flag_value source = ParameterSource.COMMANDLINE elif ( self.multiple and value is not None and any(v is _flag_needs_value for v in value) ): value = [self.flag_value if v is _flag_needs_value else v for v in value] source = ParameterSource.COMMANDLINE # The value wasn't set, or used the param's default, prompt if # prompting is enabled. elif ( source in {None, ParameterSource.DEFAULT} and self.prompt is not None and (self.required or self.prompt_required) and not ctx.resilient_parsing ): value = self.prompt_for_value(ctx) source = ParameterSource.PROMPT return value, source
(param_decls: Optional[Sequence[str]] = None, show_default: Union[bool, str, NoneType] = None, prompt: Union[bool, str] = False, confirmation_prompt: Union[bool, str] = False, prompt_required: bool = True, hide_input: bool = False, is_flag: Optional[bool] = None, flag_value: Optional[Any] = None, multiple: bool = False, count: bool = False, allow_from_autoenv: bool = True, type: Union[asyncclick.types.ParamType, Any, NoneType] = None, help: Optional[str] = None, hidden: bool = False, show_choices: bool = True, show_envvar: bool = False, **attrs: Any) -> None
9,540
asyncclick.core
__init__
null
def __init__( self, param_decls: t.Optional[t.Sequence[str]] = None, show_default: t.Union[bool, str, None] = None, prompt: t.Union[bool, str] = False, confirmation_prompt: t.Union[bool, str] = False, prompt_required: bool = True, hide_input: bool = False, is_flag: t.Optional[bool] = None, flag_value: t.Optional[t.Any] = None, multiple: bool = False, count: bool = False, allow_from_autoenv: bool = True, type: t.Optional[t.Union[types.ParamType, t.Any]] = None, help: t.Optional[str] = None, hidden: bool = False, show_choices: bool = True, show_envvar: bool = False, **attrs: t.Any, ) -> None: if help: help = inspect.cleandoc(help) default_is_missing = "default" not in attrs super().__init__(param_decls, type=type, multiple=multiple, **attrs) if prompt is True: if self.name is None: raise TypeError("'name' is required with 'prompt=True'.") prompt_text: t.Optional[str] = self.name.replace("_", " ").capitalize() elif prompt is False: prompt_text = None else: prompt_text = prompt self.prompt = prompt_text self.confirmation_prompt = confirmation_prompt self.prompt_required = prompt_required self.hide_input = hide_input self.hidden = hidden # If prompt is enabled but not required, then the option can be # used as a flag to indicate using prompt or flag_value. self._flag_needs_value = self.prompt is not None and not self.prompt_required if is_flag is None: if flag_value is not None: # Implicitly a flag because flag_value was set. is_flag = True elif self._flag_needs_value: # Not a flag, but when used as a flag it shows a prompt. is_flag = False else: # Implicitly a flag because flag options were given. is_flag = bool(self.secondary_opts) elif is_flag is False and not self._flag_needs_value: # Not a flag, and prompt is not enabled, can be used as a # flag if flag_value is set. self._flag_needs_value = flag_value is not None self.default: t.Union[t.Any, t.Callable[[], t.Any]] if is_flag and default_is_missing and not self.required: if multiple: self.default = () else: self.default = False if flag_value is None: flag_value = not self.default self.type: types.ParamType if is_flag and type is None: # Re-guess the type from the flag value instead of the # default. self.type = types.convert_type(None, flag_value) self.is_flag: bool = is_flag self.is_bool_flag: bool = is_flag and isinstance(self.type, types.BoolParamType) self.flag_value: t.Any = flag_value # Counting self.count = count if count: if type is None: self.type = types.IntRange(min=0) if default_is_missing: self.default = 0 self.allow_from_autoenv = allow_from_autoenv self.help = help self.show_default = show_default self.show_choices = show_choices self.show_envvar = show_envvar if __debug__: if self.nargs == -1: raise TypeError("nargs=-1 is not supported for options.") if self.prompt and self.is_flag and not self.is_bool_flag: raise TypeError("'prompt' is not valid for non-boolean flag.") if not self.is_bool_flag and self.secondary_opts: raise TypeError("Secondary flag is not valid for non-boolean flag.") if self.is_bool_flag and self.hide_input and self.prompt is not None: raise TypeError( "'prompt' with 'hide_input' is not valid for boolean flag." ) if self.count: if self.multiple: raise TypeError("'count' is not valid with 'multiple'.") if self.is_flag: raise TypeError("'count' is not valid with 'is_flag'.")
(self, param_decls: Optional[Sequence[str]] = None, show_default: Union[bool, str, NoneType] = None, prompt: Union[bool, str] = False, confirmation_prompt: Union[bool, str] = False, prompt_required: bool = True, hide_input: bool = False, is_flag: Optional[bool] = None, flag_value: Optional[Any] = None, multiple: bool = False, count: bool = False, allow_from_autoenv: bool = True, type: Union[asyncclick.types.ParamType, Any, NoneType] = None, help: Optional[str] = None, hidden: bool = False, show_choices: bool = True, show_envvar: bool = False, **attrs: Any) -> NoneType
9,542
asyncclick.core
_parse_decls
null
def _parse_decls( self, decls: t.Sequence[str], expose_value: bool ) -> t.Tuple[t.Optional[str], t.List[str], t.List[str]]: opts = [] secondary_opts = [] name = None possible_names = [] for decl in decls: if decl.isidentifier(): if name is not None: raise TypeError(f"Name '{name}' defined twice") name = decl else: split_char = ";" if decl[:1] == "/" else "/" if split_char in decl: first, second = decl.split(split_char, 1) first = first.rstrip() if first: possible_names.append(split_opt(first)) opts.append(first) second = second.lstrip() if second: secondary_opts.append(second.lstrip()) if first == second: raise ValueError( f"Boolean option {decl!r} cannot use the" " same flag for true/false." ) else: possible_names.append(split_opt(decl)) opts.append(decl) if name is None and possible_names: possible_names.sort(key=lambda x: -len(x[0])) # group long options first name = possible_names[0][1].replace("-", "_").lower() if not name.isidentifier(): name = None if name is None: if not expose_value: return None, opts, secondary_opts raise TypeError("Could not determine name for option") if not opts and not secondary_opts: raise TypeError( f"No options defined but a name was passed ({name})." " Did you mean to declare an argument instead? Did" f" you mean to pass '--{name}'?" ) return name, opts, secondary_opts
(self, decls: Sequence[str], expose_value: bool) -> Tuple[Optional[str], List[str], List[str]]
9,543
asyncclick.core
add_to_parser
null
def add_to_parser(self, parser: OptionParser, ctx: Context) -> None: if self.multiple: action = "append" elif self.count: action = "count" else: action = "store" if self.is_flag: action = f"{action}_const" if self.is_bool_flag and self.secondary_opts: parser.add_option( obj=self, opts=self.opts, dest=self.name, action=action, const=True ) parser.add_option( obj=self, opts=self.secondary_opts, dest=self.name, action=action, const=False, ) else: parser.add_option( obj=self, opts=self.opts, dest=self.name, action=action, const=self.flag_value, ) else: parser.add_option( obj=self, opts=self.opts, dest=self.name, action=action, nargs=self.nargs, )
(self, parser: asyncclick.parser.OptionParser, ctx: asyncclick.core.Context) -> NoneType
9,544
asyncclick.core
consume_value
null
def consume_value( self, ctx: Context, opts: t.Mapping[str, "Parameter"] ) -> t.Tuple[t.Any, ParameterSource]: value, source = super().consume_value(ctx, opts) # The parser will emit a sentinel value if the option can be # given as a flag without a value. This is different from None # to distinguish from the flag not being given at all. if value is _flag_needs_value: if self.prompt is not None and not ctx.resilient_parsing: value = self.prompt_for_value(ctx) source = ParameterSource.PROMPT else: value = self.flag_value source = ParameterSource.COMMANDLINE elif ( self.multiple and value is not None and any(v is _flag_needs_value for v in value) ): value = [self.flag_value if v is _flag_needs_value else v for v in value] source = ParameterSource.COMMANDLINE # The value wasn't set, or used the param's default, prompt if # prompting is enabled. elif ( source in {None, ParameterSource.DEFAULT} and self.prompt is not None and (self.required or self.prompt_required) and not ctx.resilient_parsing ): value = self.prompt_for_value(ctx) source = ParameterSource.PROMPT return value, source
(self, ctx: asyncclick.core.Context, opts: Mapping[str, asyncclick.core.Parameter]) -> Tuple[Any, asyncclick.core.ParameterSource]
9,545
asyncclick.core
get_default
null
def get_default( self, ctx: Context, call: bool = True ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]: # If we're a non boolean flag our default is more complex because # we need to look at all flags in the same group to figure out # if we're the default one in which case we return the flag # value as default. if self.is_flag and not self.is_bool_flag: for param in ctx.command.params: if param.name == self.name and param.default: return t.cast(Option, param).flag_value return None return super().get_default(ctx, call=call)
(self, ctx: asyncclick.core.Context, call: bool = True) -> Union[Any, Callable[[], Any], NoneType]
9,546
asyncclick.core
get_error_hint
Get a stringified version of the param for use in error messages to indicate which param caused the error.
def get_error_hint(self, ctx: Context) -> str: """Get a stringified version of the param for use in error messages to indicate which param caused the error. """ hint_list = self.opts or [self.human_readable_name] return " / ".join(f"'{x}'" for x in hint_list)
(self, ctx: asyncclick.core.Context) -> str
9,547
asyncclick.core
get_help_record
null
def get_help_record(self, ctx: Context) -> t.Optional[t.Tuple[str, str]]: if self.hidden: return None any_prefix_is_slash = False def _write_opts(opts: t.Sequence[str]) -> str: nonlocal any_prefix_is_slash rv, any_slashes = join_options(opts) if any_slashes: any_prefix_is_slash = True if not self.is_flag and not self.count: rv += f" {self.make_metavar()}" return rv rv = [_write_opts(self.opts)] if self.secondary_opts: rv.append(_write_opts(self.secondary_opts)) help = self.help or "" extra = [] if self.show_envvar: envvar = self.envvar if envvar is None: if ( self.allow_from_autoenv and ctx.auto_envvar_prefix is not None and self.name is not None ): envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}" if envvar is not None: var_str = ( envvar if isinstance(envvar, str) else ", ".join(str(d) for d in envvar) ) extra.append(_("env var: {var}").format(var=var_str)) # Temporarily enable resilient parsing to avoid type casting # failing for the default. Might be possible to extend this to # help formatting in general. resilient = ctx.resilient_parsing ctx.resilient_parsing = True try: default_value = self.get_default(ctx, call=False) finally: ctx.resilient_parsing = resilient show_default = False show_default_is_str = False if self.show_default is not None: if isinstance(self.show_default, str): show_default_is_str = show_default = True else: show_default = self.show_default elif ctx.show_default is not None: show_default = ctx.show_default if show_default_is_str or (show_default and (default_value is not None)): if show_default_is_str: default_string = f"({self.show_default})" elif isinstance(default_value, (list, tuple)): default_string = ", ".join(str(d) for d in default_value) elif inspect.isfunction(default_value): default_string = _("(dynamic)") elif self.is_bool_flag and self.secondary_opts: # For boolean flags that have distinct True/False opts, # use the opt without prefix instead of the value. default_string = split_opt( (self.opts if self.default else self.secondary_opts)[0] )[1] elif self.is_bool_flag and not self.secondary_opts and not default_value: default_string = "" else: default_string = str(default_value) if default_string: extra.append(_("default: {default}").format(default=default_string)) if ( isinstance(self.type, types._NumberRangeBase) # skip count with default range type and not (self.count and self.type.min == 0 and self.type.max is None) ): range_str = self.type._describe_range() if range_str: extra.append(range_str) if self.required: extra.append(_("required")) if extra: extra_str = "; ".join(extra) help = f"{help} [{extra_str}]" if help else f"[{extra_str}]" return ("; " if any_prefix_is_slash else " / ").join(rv), help
(self, ctx: asyncclick.core.Context) -> Optional[Tuple[str, str]]
9,548
asyncclick.core
get_usage_pieces
null
def get_usage_pieces(self, ctx: Context) -> t.List[str]: return []
(self, ctx: asyncclick.core.Context) -> List[str]
9,550
asyncclick.core
make_metavar
null
def make_metavar(self) -> str: if self.metavar is not None: return self.metavar metavar = self.type.get_metavar(self) if metavar is None: metavar = self.type.name.upper() if self.nargs != 1: metavar += "..." return metavar
(self) -> str
9,552
asyncclick.core
prompt_for_value
This is an alternative flow that can be activated in the full value processing if a value does not exist. It will prompt the user until a valid value exists and then returns the processed value as result.
def prompt_for_value(self, ctx: Context) -> t.Any: """This is an alternative flow that can be activated in the full value processing if a value does not exist. It will prompt the user until a valid value exists and then returns the processed value as result. """ assert self.prompt is not None # Calculate the default before prompting anything to be stable. default = self.get_default(ctx) # If this is a prompt for a flag we need to handle this # differently. if self.is_bool_flag: return confirm(self.prompt, default) return prompt( self.prompt, default=default, type=self.type, hide_input=self.hide_input, show_choices=self.show_choices, confirmation_prompt=self.confirmation_prompt, value_proc=lambda x: self.process_value(ctx, x), )
(self, ctx: asyncclick.core.Context) -> Any
9,553
asyncclick.core
resolve_envvar_value
null
def resolve_envvar_value(self, ctx: Context) -> t.Optional[str]: rv = super().resolve_envvar_value(ctx) if rv is not None: return rv if ( self.allow_from_autoenv and ctx.auto_envvar_prefix is not None and self.name is not None ): envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}" rv = os.environ.get(envvar) if rv: return rv return None
(self, ctx: asyncclick.core.Context) -> Optional[str]
9,557
asyncclick.core
value_from_envvar
null
def value_from_envvar(self, ctx: Context) -> t.Optional[t.Any]: rv: t.Optional[t.Any] = self.resolve_envvar_value(ctx) if rv is None: return None value_depth = (self.nargs != 1) + bool(self.multiple) if value_depth > 0: rv = self.type.split_envvar_value(rv) if self.multiple and self.nargs != 1: rv = batch(rv, self.nargs) return rv
(self, ctx: asyncclick.core.Context) -> Optional[Any]
9,559
asyncclick.parser
OptionParser
The option parser is an internal class that is ultimately used to parse options and arguments. It's modelled after optparse and brings a similar but vastly simplified API. It should generally not be used directly as the high level Click classes wrap it for you. It's not nearly as extensible as optparse or argparse as it does not implement features that are implemented on a higher level (such as types or defaults). :param ctx: optionally the :class:`~click.Context` where this parser should go with.
class OptionParser: """The option parser is an internal class that is ultimately used to parse options and arguments. It's modelled after optparse and brings a similar but vastly simplified API. It should generally not be used directly as the high level Click classes wrap it for you. It's not nearly as extensible as optparse or argparse as it does not implement features that are implemented on a higher level (such as types or defaults). :param ctx: optionally the :class:`~click.Context` where this parser should go with. """ def __init__(self, ctx: t.Optional["Context"] = None) -> None: #: The :class:`~click.Context` for this parser. This might be #: `None` for some advanced use cases. self.ctx = ctx #: This controls how the parser deals with interspersed arguments. #: If this is set to `False`, the parser will stop on the first #: non-option. Click uses this to implement nested subcommands #: safely. self.allow_interspersed_args: bool = True #: This tells the parser how to deal with unknown options. By #: default it will error out (which is sensible), but there is a #: second mode where it will ignore it and continue processing #: after shifting all the unknown options into the resulting args. self.ignore_unknown_options: bool = False if ctx is not None: self.allow_interspersed_args = ctx.allow_interspersed_args self.ignore_unknown_options = ctx.ignore_unknown_options self._short_opt: t.Dict[str, Option] = {} self._long_opt: t.Dict[str, Option] = {} self._opt_prefixes = {"-", "--"} self._args: t.List[Argument] = [] def add_option( self, obj: "CoreOption", opts: t.Sequence[str], dest: t.Optional[str], action: t.Optional[str] = None, nargs: int = 1, const: t.Optional[t.Any] = None, ) -> None: """Adds a new option named `dest` to the parser. The destination is not inferred (unlike with optparse) and needs to be explicitly provided. Action can be any of ``store``, ``store_const``, ``append``, ``append_const`` or ``count``. The `obj` can be used to identify the option in the order list that is returned from the parser. """ opts = [normalize_opt(opt, self.ctx) for opt in opts] option = Option(obj, opts, dest, action=action, nargs=nargs, const=const) self._opt_prefixes.update(option.prefixes) for opt in option._short_opts: self._short_opt[opt] = option for opt in option._long_opts: self._long_opt[opt] = option def add_argument( self, obj: "CoreArgument", dest: t.Optional[str], nargs: int = 1 ) -> None: """Adds a positional argument named `dest` to the parser. The `obj` can be used to identify the option in the order list that is returned from the parser. """ self._args.append(Argument(obj, dest=dest, nargs=nargs)) async def parse_args( self, args: t.List[str] ) -> t.Tuple[t.Dict[str, t.Any], t.List[str], t.List["CoreParameter"]]: """Parses positional arguments and returns ``(values, args, order)`` for the parsed options and arguments as well as the leftover arguments if there are any. The order is a list of objects as they appear on the command line. If arguments appear multiple times they will be memorized multiple times as well. """ state = ParsingState(args) try: self._process_args_for_options(state) self._process_args_for_args(state) except UsageError: if self.ctx is None or not self.ctx.resilient_parsing: raise return state.opts, state.largs, state.order def _process_args_for_args(self, state: ParsingState) -> None: pargs, args = _unpack_args( state.largs + state.rargs, [x.nargs for x in self._args] ) for idx, arg in enumerate(self._args): arg.process(pargs[idx], state) state.largs = args state.rargs = [] def _process_args_for_options(self, state: ParsingState) -> None: while state.rargs: arg = state.rargs.pop(0) arglen = len(arg) # Double dashes always handled explicitly regardless of what # prefixes are valid. if arg == "--": return elif arg[:1] in self._opt_prefixes and arglen > 1: self._process_opts(arg, state) elif self.allow_interspersed_args: state.largs.append(arg) else: state.rargs.insert(0, arg) return # Say this is the original argument list: # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)] # ^ # (we are about to process arg(i)). # # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of # [arg0, ..., arg(i-1)] (any options and their arguments will have # been removed from largs). # # The while loop will usually consume 1 or more arguments per pass. # If it consumes 1 (eg. arg is an option that takes no arguments), # then after _process_arg() is done the situation is: # # largs = subset of [arg0, ..., arg(i)] # rargs = [arg(i+1), ..., arg(N-1)] # # If allow_interspersed_args is false, largs will always be # *empty* -- still a subset of [arg0, ..., arg(i-1)], but # not a very interesting subset! def _match_long_opt( self, opt: str, explicit_value: t.Optional[str], state: ParsingState ) -> None: if opt not in self._long_opt: from difflib import get_close_matches possibilities = get_close_matches(opt, self._long_opt) raise NoSuchOption(opt, possibilities=possibilities, ctx=self.ctx) option = self._long_opt[opt] if option.takes_value: # At this point it's safe to modify rargs by injecting the # explicit value, because no exception is raised in this # branch. This means that the inserted value will be fully # consumed. if explicit_value is not None: state.rargs.insert(0, explicit_value) value = self._get_value_from_state(opt, option, state) elif explicit_value is not None: raise BadOptionUsage( opt, _("Option {name!r} does not take a value.").format(name=opt) ) else: value = None option.process(value, state) def _match_short_opt(self, arg: str, state: ParsingState) -> None: stop = False i = 1 prefix = arg[0] unknown_options = [] for ch in arg[1:]: opt = normalize_opt(f"{prefix}{ch}", self.ctx) option = self._short_opt.get(opt) i += 1 if not option: if self.ignore_unknown_options: unknown_options.append(ch) continue raise NoSuchOption(opt, ctx=self.ctx) if option.takes_value: # Any characters left in arg? Pretend they're the # next arg, and stop consuming characters of arg. if i < len(arg): state.rargs.insert(0, arg[i:]) stop = True value = self._get_value_from_state(opt, option, state) else: value = None option.process(value, state) if stop: break # If we got any unknown options we recombine the string of the # remaining options and re-attach the prefix, then report that # to the state as new larg. This way there is basic combinatorics # that can be achieved while still ignoring unknown arguments. if self.ignore_unknown_options and unknown_options: state.largs.append(f"{prefix}{''.join(unknown_options)}") def _get_value_from_state( self, option_name: str, option: Option, state: ParsingState ) -> t.Any: nargs = option.nargs if len(state.rargs) < nargs: if option.obj._flag_needs_value: # Option allows omitting the value. value = _flag_needs_value else: raise BadOptionUsage( option_name, ngettext( "Option {name!r} requires an argument.", "Option {name!r} requires {nargs} arguments.", nargs, ).format(name=option_name, nargs=nargs), ) elif nargs == 1: next_rarg = state.rargs[0] if ( option.obj._flag_needs_value and isinstance(next_rarg, str) and next_rarg[:1] in self._opt_prefixes and len(next_rarg) > 1 ): # The next arg looks like the start of an option, don't # use it as the value if omitting the value is allowed. value = _flag_needs_value else: value = state.rargs.pop(0) else: value = tuple(state.rargs[:nargs]) del state.rargs[:nargs] return value def _process_opts(self, arg: str, state: ParsingState) -> None: explicit_value = None # Long option handling happens in two parts. The first part is # supporting explicitly attached values. In any case, we will try # to long match the option first. if "=" in arg: long_opt, explicit_value = arg.split("=", 1) else: long_opt = arg norm_long_opt = normalize_opt(long_opt, self.ctx) # At this point we will match the (assumed) long option through # the long option matching code. Note that this allows options # like "-foo" to be matched as long options. try: self._match_long_opt(norm_long_opt, explicit_value, state) except NoSuchOption: # At this point the long option matching failed, and we need # to try with short options. However there is a special rule # which says, that if we have a two character options prefix # (applies to "--foo" for instance), we do not dispatch to the # short option code and will instead raise the no option # error. if arg[:2] not in self._opt_prefixes: self._match_short_opt(arg, state) return if not self.ignore_unknown_options: raise state.largs.append(arg)
(ctx: Optional[ForwardRef('Context')] = None) -> None
9,560
asyncclick.parser
__init__
null
def __init__(self, ctx: t.Optional["Context"] = None) -> None: #: The :class:`~click.Context` for this parser. This might be #: `None` for some advanced use cases. self.ctx = ctx #: This controls how the parser deals with interspersed arguments. #: If this is set to `False`, the parser will stop on the first #: non-option. Click uses this to implement nested subcommands #: safely. self.allow_interspersed_args: bool = True #: This tells the parser how to deal with unknown options. By #: default it will error out (which is sensible), but there is a #: second mode where it will ignore it and continue processing #: after shifting all the unknown options into the resulting args. self.ignore_unknown_options: bool = False if ctx is not None: self.allow_interspersed_args = ctx.allow_interspersed_args self.ignore_unknown_options = ctx.ignore_unknown_options self._short_opt: t.Dict[str, Option] = {} self._long_opt: t.Dict[str, Option] = {} self._opt_prefixes = {"-", "--"} self._args: t.List[Argument] = []
(self, ctx: Optional[ForwardRef('Context')] = None) -> None
9,561
asyncclick.parser
_get_value_from_state
null
def _get_value_from_state( self, option_name: str, option: Option, state: ParsingState ) -> t.Any: nargs = option.nargs if len(state.rargs) < nargs: if option.obj._flag_needs_value: # Option allows omitting the value. value = _flag_needs_value else: raise BadOptionUsage( option_name, ngettext( "Option {name!r} requires an argument.", "Option {name!r} requires {nargs} arguments.", nargs, ).format(name=option_name, nargs=nargs), ) elif nargs == 1: next_rarg = state.rargs[0] if ( option.obj._flag_needs_value and isinstance(next_rarg, str) and next_rarg[:1] in self._opt_prefixes and len(next_rarg) > 1 ): # The next arg looks like the start of an option, don't # use it as the value if omitting the value is allowed. value = _flag_needs_value else: value = state.rargs.pop(0) else: value = tuple(state.rargs[:nargs]) del state.rargs[:nargs] return value
(self, option_name: str, option: asyncclick.parser.Option, state: asyncclick.parser.ParsingState) -> Any
9,562
asyncclick.parser
_match_long_opt
null
def _match_long_opt( self, opt: str, explicit_value: t.Optional[str], state: ParsingState ) -> None: if opt not in self._long_opt: from difflib import get_close_matches possibilities = get_close_matches(opt, self._long_opt) raise NoSuchOption(opt, possibilities=possibilities, ctx=self.ctx) option = self._long_opt[opt] if option.takes_value: # At this point it's safe to modify rargs by injecting the # explicit value, because no exception is raised in this # branch. This means that the inserted value will be fully # consumed. if explicit_value is not None: state.rargs.insert(0, explicit_value) value = self._get_value_from_state(opt, option, state) elif explicit_value is not None: raise BadOptionUsage( opt, _("Option {name!r} does not take a value.").format(name=opt) ) else: value = None option.process(value, state)
(self, opt: str, explicit_value: Optional[str], state: asyncclick.parser.ParsingState) -> NoneType
9,563
asyncclick.parser
_match_short_opt
null
def _match_short_opt(self, arg: str, state: ParsingState) -> None: stop = False i = 1 prefix = arg[0] unknown_options = [] for ch in arg[1:]: opt = normalize_opt(f"{prefix}{ch}", self.ctx) option = self._short_opt.get(opt) i += 1 if not option: if self.ignore_unknown_options: unknown_options.append(ch) continue raise NoSuchOption(opt, ctx=self.ctx) if option.takes_value: # Any characters left in arg? Pretend they're the # next arg, and stop consuming characters of arg. if i < len(arg): state.rargs.insert(0, arg[i:]) stop = True value = self._get_value_from_state(opt, option, state) else: value = None option.process(value, state) if stop: break # If we got any unknown options we recombine the string of the # remaining options and re-attach the prefix, then report that # to the state as new larg. This way there is basic combinatorics # that can be achieved while still ignoring unknown arguments. if self.ignore_unknown_options and unknown_options: state.largs.append(f"{prefix}{''.join(unknown_options)}")
(self, arg: str, state: asyncclick.parser.ParsingState) -> NoneType
9,564
asyncclick.parser
_process_args_for_args
null
def _process_args_for_args(self, state: ParsingState) -> None: pargs, args = _unpack_args( state.largs + state.rargs, [x.nargs for x in self._args] ) for idx, arg in enumerate(self._args): arg.process(pargs[idx], state) state.largs = args state.rargs = []
(self, state: asyncclick.parser.ParsingState) -> NoneType
9,565
asyncclick.parser
_process_args_for_options
null
def _process_args_for_options(self, state: ParsingState) -> None: while state.rargs: arg = state.rargs.pop(0) arglen = len(arg) # Double dashes always handled explicitly regardless of what # prefixes are valid. if arg == "--": return elif arg[:1] in self._opt_prefixes and arglen > 1: self._process_opts(arg, state) elif self.allow_interspersed_args: state.largs.append(arg) else: state.rargs.insert(0, arg) return # Say this is the original argument list: # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)] # ^ # (we are about to process arg(i)). # # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of # [arg0, ..., arg(i-1)] (any options and their arguments will have # been removed from largs). # # The while loop will usually consume 1 or more arguments per pass. # If it consumes 1 (eg. arg is an option that takes no arguments), # then after _process_arg() is done the situation is: # # largs = subset of [arg0, ..., arg(i)] # rargs = [arg(i+1), ..., arg(N-1)] # # If allow_interspersed_args is false, largs will always be # *empty* -- still a subset of [arg0, ..., arg(i-1)], but # not a very interesting subset!
(self, state: asyncclick.parser.ParsingState) -> NoneType
9,566
asyncclick.parser
_process_opts
null
def _process_opts(self, arg: str, state: ParsingState) -> None: explicit_value = None # Long option handling happens in two parts. The first part is # supporting explicitly attached values. In any case, we will try # to long match the option first. if "=" in arg: long_opt, explicit_value = arg.split("=", 1) else: long_opt = arg norm_long_opt = normalize_opt(long_opt, self.ctx) # At this point we will match the (assumed) long option through # the long option matching code. Note that this allows options # like "-foo" to be matched as long options. try: self._match_long_opt(norm_long_opt, explicit_value, state) except NoSuchOption: # At this point the long option matching failed, and we need # to try with short options. However there is a special rule # which says, that if we have a two character options prefix # (applies to "--foo" for instance), we do not dispatch to the # short option code and will instead raise the no option # error. if arg[:2] not in self._opt_prefixes: self._match_short_opt(arg, state) return if not self.ignore_unknown_options: raise state.largs.append(arg)
(self, arg: str, state: asyncclick.parser.ParsingState) -> NoneType
9,567
asyncclick.parser
add_argument
Adds a positional argument named `dest` to the parser. The `obj` can be used to identify the option in the order list that is returned from the parser.
def add_argument( self, obj: "CoreArgument", dest: t.Optional[str], nargs: int = 1 ) -> None: """Adds a positional argument named `dest` to the parser. The `obj` can be used to identify the option in the order list that is returned from the parser. """ self._args.append(Argument(obj, dest=dest, nargs=nargs))
(self, obj: 'CoreArgument', dest: Optional[str], nargs: int = 1) -> None
9,568
asyncclick.parser
add_option
Adds a new option named `dest` to the parser. The destination is not inferred (unlike with optparse) and needs to be explicitly provided. Action can be any of ``store``, ``store_const``, ``append``, ``append_const`` or ``count``. The `obj` can be used to identify the option in the order list that is returned from the parser.
def add_option( self, obj: "CoreOption", opts: t.Sequence[str], dest: t.Optional[str], action: t.Optional[str] = None, nargs: int = 1, const: t.Optional[t.Any] = None, ) -> None: """Adds a new option named `dest` to the parser. The destination is not inferred (unlike with optparse) and needs to be explicitly provided. Action can be any of ``store``, ``store_const``, ``append``, ``append_const`` or ``count``. The `obj` can be used to identify the option in the order list that is returned from the parser. """ opts = [normalize_opt(opt, self.ctx) for opt in opts] option = Option(obj, opts, dest, action=action, nargs=nargs, const=const) self._opt_prefixes.update(option.prefixes) for opt in option._short_opts: self._short_opt[opt] = option for opt in option._long_opts: self._long_opt[opt] = option
(self, obj: 'CoreOption', opts: Sequence[str], dest: Optional[str], action: Optional[str] = None, nargs: int = 1, const: Optional[Any] = None) -> None
9,569
asyncclick.parser
parse_args
Parses positional arguments and returns ``(values, args, order)`` for the parsed options and arguments as well as the leftover arguments if there are any. The order is a list of objects as they appear on the command line. If arguments appear multiple times they will be memorized multiple times as well.
def add_argument( self, obj: "CoreArgument", dest: t.Optional[str], nargs: int = 1 ) -> None: """Adds a positional argument named `dest` to the parser. The `obj` can be used to identify the option in the order list that is returned from the parser. """ self._args.append(Argument(obj, dest=dest, nargs=nargs))
(self, args: List[str]) -> Tuple[Dict[str, Any], List[str], List[ForwardRef('CoreParameter')]]
9,570
asyncclick.types
ParamType
Represents the type of a parameter. Validates and converts values from the command line or Python into the correct type. To implement a custom type, subclass and implement at least the following: - The :attr:`name` class attribute must be set. - Calling an instance of the type with ``None`` must return ``None``. This is already implemented by default. - :meth:`convert` must convert string values to the correct type. - :meth:`convert` must accept values that are already the correct type. - It must be able to convert a value if the ``ctx`` and ``param`` arguments are ``None``. This can occur when converting prompt input.
class ParamType: """Represents the type of a parameter. Validates and converts values from the command line or Python into the correct type. To implement a custom type, subclass and implement at least the following: - The :attr:`name` class attribute must be set. - Calling an instance of the type with ``None`` must return ``None``. This is already implemented by default. - :meth:`convert` must convert string values to the correct type. - :meth:`convert` must accept values that are already the correct type. - It must be able to convert a value if the ``ctx`` and ``param`` arguments are ``None``. This can occur when converting prompt input. """ is_composite: t.ClassVar[bool] = False arity: t.ClassVar[int] = 1 #: the descriptive name of this type name: str #: if a list of this type is expected and the value is pulled from a #: string environment variable, this is what splits it up. `None` #: means any whitespace. For all parameters the general rule is that #: whitespace splits them up. The exception are paths and files which #: are split by ``os.path.pathsep`` by default (":" on Unix and ";" on #: Windows). envvar_list_splitter: t.ClassVar[t.Optional[str]] = None async def to_info_dict(self) -> t.Dict[str, t.Any]: """Gather information that could be useful for a tool generating user-facing documentation. Use :meth:`click.Context.to_info_dict` to traverse the entire CLI structure. .. versionadded:: 8.0 """ # The class name without the "ParamType" suffix. param_type = type(self).__name__.partition("ParamType")[0] param_type = param_type.partition("ParameterType")[0] # Custom subclasses might not remember to set a name. if hasattr(self, "name"): name = self.name else: name = param_type return {"param_type": param_type, "name": name} def __call__( self, value: t.Any, param: t.Optional["Parameter"] = None, ctx: t.Optional["Context"] = None, ) -> t.Any: if value is not None: return self.convert(value, param, ctx) def get_metavar(self, param: "Parameter") -> t.Optional[str]: """Returns the metavar default for this param if it provides one.""" def get_missing_message(self, param: "Parameter") -> t.Optional[str]: """Optionally might return extra information about a missing parameter. .. versionadded:: 2.0 """ def convert( self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"] ) -> t.Any: """Convert the value to the correct type. This is not called if the value is ``None`` (the missing value). This must accept string values from the command line, as well as values that are already the correct type. It may also convert other compatible types. The ``param`` and ``ctx`` arguments may be ``None`` in certain situations, such as when converting prompt input. If the value cannot be converted, call :meth:`fail` with a descriptive message. :param value: The value to convert. :param param: The parameter that is using this type to convert its value. May be ``None``. :param ctx: The current context that arrived at this value. May be ``None``. """ return value def split_envvar_value(self, rv: str) -> t.Sequence[str]: """Given a value from an environment variable this splits it up into small chunks depending on the defined envvar list splitter. If the splitter is set to `None`, which means that whitespace splits, then leading and trailing whitespace is ignored. Otherwise, leading and trailing splitters usually lead to empty items being included. """ return (rv or "").split(self.envvar_list_splitter) def fail( self, message: str, param: t.Optional["Parameter"] = None, ctx: t.Optional["Context"] = None, ) -> "t.NoReturn": """Helper method to fail with an invalid value message.""" raise BadParameter(message, ctx=ctx, param=param) def shell_complete( self, ctx: "Context", param: "Parameter", incomplete: str ) -> t.List["CompletionItem"]: """Return a list of :class:`~click.shell_completion.CompletionItem` objects for the incomplete value. Most types do not provide completions, but some do, and this allows custom types to provide custom completions as well. :param ctx: Invocation context for this command. :param param: The parameter that is requesting completion. :param incomplete: Value being completed. May be empty. .. versionadded:: 8.0 """ return []
()