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,235
dagster._core.launcher.base
join
null
def join(self, timeout: int = 30) -> None: pass
(self, timeout: int = 30) -> NoneType
9,236
dagster_docker.docker_run_launcher
launch_run
null
def launch_run(self, context: LaunchRunContext) -> None: run = context.dagster_run job_code_origin = check.not_none(context.job_code_origin) docker_image = self._get_docker_image(job_code_origin) command = ExecuteRunArgs( job_origin=job_code_origin, run_id=run.run_id, instance_ref=self._instance.get_ref(), ).get_command_args() self._launch_container_with_command(run, docker_image, command)
(self, context: dagster._core.launcher.base.LaunchRunContext) -> NoneType
9,237
dagster._core.instance
register_instance
null
def register_instance(self, instance: T_DagsterInstance) -> None: check.invariant( ( # Backcompat with custom subclasses that don't call super().__init__() # in their own __init__ implementations not hasattr(self, "_instance_weakref") or self._instance_weakref is None ), "Must only call initialize once", ) # Store a weakref to avoid a circular reference / enable GC self._instance_weakref = weakref.ref(instance)
(self, instance: ~T_DagsterInstance) -> NoneType
9,238
dagster_docker.docker_run_launcher
resume_run
null
def resume_run(self, context: ResumeRunContext) -> None: run = context.dagster_run job_code_origin = check.not_none(context.job_code_origin) docker_image = self._get_docker_image(job_code_origin) command = ResumeRunArgs( job_origin=job_code_origin, run_id=run.run_id, instance_ref=self._instance.get_ref(), ).get_command_args() self._launch_container_with_command(run, docker_image, command)
(self, context: dagster._core.launcher.base.ResumeRunContext) -> NoneType
9,239
dagster_docker.docker_run_launcher
terminate
null
def terminate(self, run_id): run = self._instance.get_run_by_id(run_id) if not run: return False self._instance.report_run_canceling(run) container = self._get_container(run) if not container: self._instance.report_engine_event( message="Unable to get docker container to send termination request to.", dagster_run=run, cls=self.__class__, ) return False container.stop() return True
(self, run_id)
9,240
dagster_docker.pipes
PipesDockerLogsMessageReader
null
class PipesDockerLogsMessageReader(PipesMessageReader): @contextmanager def read_messages( self, handler: PipesMessageHandler, ) -> Iterator[PipesParams]: self._handler = handler try: yield {PipesDefaultMessageWriter.STDIO_KEY: PipesDefaultMessageWriter.STDERR} finally: self._handler = None def consume_docker_logs(self, container) -> None: handler = check.not_none( self._handler, "Can only consume logs within context manager scope." ) for log_line in container.logs(stdout=True, stderr=True, stream=True, follow=True): if isinstance(log_line, bytes): log_entry = log_line.decode("utf-8") elif isinstance(log_line, str): log_entry = log_line else: continue extract_message_or_forward_to_stdout(handler, log_entry) def no_messages_debug_text(self) -> str: return "Attempted to read messages by extracting them from docker logs directly."
(*args, **kwargs)
9,241
dagster._core.decorator_utils
__init__
Initialize self. See help(type(self)) for accurate signature.
def _wrap_with_pre_call_fn( fn: T_Callable, pre_call_fn: Callable[[], None], condition: Optional[Callable[..., bool]] = None, ) -> T_Callable: @functools.wraps(fn) def wrapped_with_pre_call_fn(*args, **kwargs): if condition is None or condition(*args, **kwargs): pre_call_fn() return fn(*args, **kwargs) return cast(T_Callable, wrapped_with_pre_call_fn)
(self, /, *args, **kwargs)
9,242
dagster_docker.pipes
consume_docker_logs
null
def consume_docker_logs(self, container) -> None: handler = check.not_none( self._handler, "Can only consume logs within context manager scope." ) for log_line in container.logs(stdout=True, stderr=True, stream=True, follow=True): if isinstance(log_line, bytes): log_entry = log_line.decode("utf-8") elif isinstance(log_line, str): log_entry = log_line else: continue extract_message_or_forward_to_stdout(handler, log_entry)
(self, container) -> NoneType
9,243
dagster_docker.pipes
no_messages_debug_text
null
def no_messages_debug_text(self) -> str: return "Attempted to read messages by extracting them from docker logs directly."
(self) -> str
9,244
dagster._core.pipes.client
on_opened
Hook called when the external process has successfully launched and returned an opened payload. By default this is a no-op. Specific message readers can override this to action information that can only be obtained from the external process.
def on_opened(self, opened_payload: PipesOpenedData) -> None: """Hook called when the external process has successfully launched and returned an opened payload. By default this is a no-op. Specific message readers can override this to action information that can only be obtained from the external process. """
(self, opened_payload: dagster_pipes.PipesOpenedData) -> NoneType
9,248
dagster_docker.ops.docker_container_op
execute_docker_container
This function is a utility for executing a Docker container from within a Dagster op. Args: image (str): The image to use for the launched Docker container. entrypoint (Optional[Sequence[str]]): The ENTRYPOINT to run in the launched Docker container. Default: None. command (Optional[Sequence[str]]): The CMD to run in the launched Docker container. Default: None. networks (Optional[Sequence[str]]): Names of the Docker networks to which to connect the launched container. Default: None. registry: (Optional[Mapping[str, str]]): Information for using a non local/public Docker registry. Can have "url", "username", or "password" keys. env_vars (Optional[Sequence[str]]): List of environemnt variables to include in the launched container. ach can be of the form KEY=VALUE or just KEY (in which case the value will be pulled from the calling environment. container_kwargs (Optional[Dict[str[Any]]]): key-value pairs that can be passed into containers.create in the Docker Python API. See https://docker-py.readthedocs.io/en/stable/containers.html for the full list of available options.
null
(context: dagster._core.execution.context.compute.OpExecutionContext, image: str, entrypoint: Optional[Sequence[str]] = None, command: Optional[Sequence[str]] = None, networks: Optional[Sequence[str]] = None, registry: Optional[Mapping[str, str]] = None, env_vars: Optional[Sequence[str]] = None, container_kwargs: Optional[Mapping[str, Any]] = None)
9,253
asyncclick.exceptions
Abort
An internal signalling exception that signals Click to abort.
class Abort(RuntimeError): """An internal signalling exception that signals Click to abort."""
null
9,254
asyncclick.core
Argument
Arguments are positional parameters to a command. They generally provide fewer features than options but can have infinite ``nargs`` and are required by default. All parameters are passed onwards to the constructor of :class:`Parameter`.
class Argument(Parameter): """Arguments are positional parameters to a command. They generally provide fewer features than options but can have infinite ``nargs`` and are required by default. All parameters are passed onwards to the constructor of :class:`Parameter`. """ param_type_name = "argument" def __init__( self, param_decls: t.Sequence[str], required: t.Optional[bool] = None, **attrs: t.Any, ) -> None: if required is None: if attrs.get("default") is not None: required = False else: required = attrs.get("nargs", 1) > 0 if "multiple" in attrs: raise TypeError("__init__() got an unexpected keyword argument 'multiple'.") super().__init__(param_decls, required=required, **attrs) if __debug__: if self.default is not None and self.nargs == -1: raise TypeError("'default' is not supported for nargs=-1.") @property def human_readable_name(self) -> str: if self.metavar is not None: return self.metavar return self.name.upper() # type: ignore def make_metavar(self) -> str: if self.metavar is not None: return self.metavar var = self.type.get_metavar(self) if not var: var = self.name.upper() # type: ignore if not self.required: var = f"[{var}]" if self.nargs != 1: var += "..." return var def _parse_decls( self, decls: t.Sequence[str], expose_value: bool ) -> t.Tuple[t.Optional[str], t.List[str], t.List[str]]: if not decls: if not expose_value: return None, [], [] raise TypeError("Could not determine name for argument") if len(decls) == 1: name = arg = decls[0] name = name.replace("-", "_").lower() else: raise TypeError( "Arguments take exactly one parameter declaration, got" f" {len(decls)}." ) return name, [arg], [] def get_usage_pieces(self, ctx: Context) -> t.List[str]: return [self.make_metavar()] def get_error_hint(self, ctx: Context) -> str: return f"'{self.make_metavar()}'" def add_to_parser(self, parser: OptionParser, ctx: Context) -> None: parser.add_argument(dest=self.name, nargs=self.nargs, obj=self)
(param_decls: Sequence[str], required: Optional[bool] = None, **attrs: Any) -> None
9,255
asyncclick.core
__init__
null
def __init__( self, param_decls: t.Sequence[str], required: t.Optional[bool] = None, **attrs: t.Any, ) -> None: if required is None: if attrs.get("default") is not None: required = False else: required = attrs.get("nargs", 1) > 0 if "multiple" in attrs: raise TypeError("__init__() got an unexpected keyword argument 'multiple'.") super().__init__(param_decls, required=required, **attrs) if __debug__: if self.default is not None and self.nargs == -1: raise TypeError("'default' is not supported for nargs=-1.")
(self, param_decls: Sequence[str], required: Optional[bool] = None, **attrs: Any) -> NoneType
9,256
asyncclick.core
__repr__
null
def __repr__(self) -> str: return f"<{self.__class__.__name__} {self.name}>"
(self) -> str
9,257
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]]: if not decls: if not expose_value: return None, [], [] raise TypeError("Could not determine name for argument") if len(decls) == 1: name = arg = decls[0] name = name.replace("-", "_").lower() else: raise TypeError( "Arguments take exactly one parameter declaration, got" f" {len(decls)}." ) return name, [arg], []
(self, decls: Sequence[str], expose_value: bool) -> Tuple[Optional[str], List[str], List[str]]
9,258
asyncclick.core
add_to_parser
null
def add_to_parser(self, parser: OptionParser, ctx: Context) -> None: parser.add_argument(dest=self.name, nargs=self.nargs, obj=self)
(self, parser: asyncclick.parser.OptionParser, ctx: asyncclick.core.Context) -> NoneType
9,259
asyncclick.core
consume_value
null
def consume_value( self, ctx: Context, opts: t.Mapping[str, t.Any] ) -> t.Tuple[t.Any, ParameterSource]: value = opts.get(self.name) # type: ignore source = ParameterSource.COMMANDLINE if value is None: value = self.value_from_envvar(ctx) source = ParameterSource.ENVIRONMENT if value is None: value = ctx.lookup_default(self.name) # type: ignore source = ParameterSource.DEFAULT_MAP if value is None: value = self.get_default(ctx) source = ParameterSource.DEFAULT return value, source
(self, ctx: asyncclick.core.Context, opts: Mapping[str, Any]) -> Tuple[Any, asyncclick.core.ParameterSource]
9,260
asyncclick.core
get_default
Get the default for the parameter. Tries :meth:`Context.lookup_default` first, then the local default. :param ctx: Current context. :param call: If the default is a callable, call it. Disable to return the callable instead. .. versionchanged:: 8.0.2 Type casting is no longer performed when getting a default. .. versionchanged:: 8.0.1 Type casting can fail in resilient parsing mode. Invalid defaults will not prevent showing help text. .. versionchanged:: 8.0 Looks at ``ctx.default_map`` first. .. versionchanged:: 8.0 Added the ``call`` parameter.
def get_default( self, ctx: Context, call: bool = True ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]: """Get the default for the parameter. Tries :meth:`Context.lookup_default` first, then the local default. :param ctx: Current context. :param call: If the default is a callable, call it. Disable to return the callable instead. .. versionchanged:: 8.0.2 Type casting is no longer performed when getting a default. .. versionchanged:: 8.0.1 Type casting can fail in resilient parsing mode. Invalid defaults will not prevent showing help text. .. versionchanged:: 8.0 Looks at ``ctx.default_map`` first. .. versionchanged:: 8.0 Added the ``call`` parameter. """ value = ctx.lookup_default(self.name, call=False) # type: ignore if value is None: value = self.default if call and callable(value): value = value() return value
(self, ctx: asyncclick.core.Context, call: bool = True) -> Union[Any, Callable[[], Any], NoneType]
9,261
asyncclick.core
get_error_hint
null
def get_error_hint(self, ctx: Context) -> str: return f"'{self.make_metavar()}'"
(self, ctx: asyncclick.core.Context) -> str
9,262
asyncclick.core
get_help_record
null
def get_help_record(self, ctx: Context) -> t.Optional[t.Tuple[str, str]]: pass
(self, ctx: asyncclick.core.Context) -> Optional[Tuple[str, str]]
9,263
asyncclick.core
get_usage_pieces
null
def get_usage_pieces(self, ctx: Context) -> t.List[str]: return [self.make_metavar()]
(self, ctx: asyncclick.core.Context) -> List[str]
9,264
asyncclick.core
handle_parse_result
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 not None and self.nargs != 1: rv = self.type.split_envvar_value(rv) return rv
(self, ctx: asyncclick.core.Context, opts: Mapping[str, Any], args: List[str]) -> Tuple[Any, List[str]]
9,265
asyncclick.core
make_metavar
null
def make_metavar(self) -> str: if self.metavar is not None: return self.metavar var = self.type.get_metavar(self) if not var: var = self.name.upper() # type: ignore if not self.required: var = f"[{var}]" if self.nargs != 1: var += "..." return var
(self) -> str
9,266
asyncclick.core
process_value
null
def process_value(self, ctx: Context, value: t.Any) -> t.Any: value = self.type_cast_value(ctx, value) if self.required and self.value_is_missing(value): raise MissingParameter(ctx=ctx, param=self) if self.callback is not None: value = self.callback(ctx, self, value) return value
(self, ctx: asyncclick.core.Context, value: Any) -> Any
9,267
asyncclick.core
resolve_envvar_value
null
def resolve_envvar_value(self, ctx: Context) -> t.Optional[str]: if self.envvar is None: return None if isinstance(self.envvar, str): rv = os.environ.get(self.envvar) if rv: return rv else: for envvar in self.envvar: rv = os.environ.get(envvar) if rv: return rv return None
(self, ctx: asyncclick.core.Context) -> Optional[str]
9,268
asyncclick.core
shell_complete
Return a list of completions for the incomplete value. If a ``shell_complete`` function was given during init, it is used. Otherwise, the :attr:`type` :meth:`~click.types.ParamType.shell_complete` function is used. :param ctx: Invocation context for this command. :param incomplete: Value being completed. May be empty. .. versionadded:: 8.0
def shell_complete(self, ctx: Context, incomplete: str) -> t.List["CompletionItem"]: """Return a list of completions for the incomplete value. If a ``shell_complete`` function was given during init, it is used. Otherwise, the :attr:`type` :meth:`~click.types.ParamType.shell_complete` function is used. :param ctx: Invocation context for this command. :param incomplete: Value being completed. May be empty. .. versionadded:: 8.0 """ if self._custom_shell_complete is not None: results = self._custom_shell_complete(ctx, self, incomplete) if results and isinstance(results[0], str): from .shell_completion import CompletionItem results = [CompletionItem(c) for c in results] return t.cast(t.List["CompletionItem"], results) return self.type.shell_complete(ctx, self, incomplete)
(self, ctx: asyncclick.core.Context, incomplete: str) -> List[ForwardRef('CompletionItem')]
9,269
asyncclick.core
to_info_dict
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
def __init__( self, param_decls: t.Optional[t.Sequence[str]] = None, type: t.Optional[t.Union[types.ParamType, t.Any]] = None, required: bool = False, default: t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]] = None, callback: t.Optional[t.Callable[[Context, "Parameter", t.Any], t.Any]] = None, nargs: t.Optional[int] = None, multiple: bool = False, metavar: t.Optional[str] = None, expose_value: bool = True, is_eager: bool = False, envvar: t.Optional[t.Union[str, t.Sequence[str]]] = None, shell_complete: t.Optional[ t.Callable[ [Context, "Parameter", str], t.Union[t.List["CompletionItem"], t.List[str]], ] ] = None, ) -> None: self.name: t.Optional[str] self.opts: t.List[str] self.secondary_opts: t.List[str] self.name, self.opts, self.secondary_opts = self._parse_decls( param_decls or (), expose_value ) self.type: types.ParamType = types.convert_type(type, default) # Default nargs to what the type tells us if we have that # information available. if nargs is None: if self.type.is_composite: nargs = self.type.arity else: nargs = 1 self.required = required self.callback = callback self.nargs = nargs self.multiple = multiple self.expose_value = expose_value self.default = default self.is_eager = is_eager self.metavar = metavar self.envvar = envvar self._custom_shell_complete = shell_complete if __debug__: if self.type.is_composite and nargs != self.type.arity: raise ValueError( f"'nargs' must be {self.type.arity} (or None) for" f" type {self.type!r}, but it was {nargs}." ) # Skip no default or callable default. check_default = default if not callable(default) else None if check_default is not None: if multiple: try: # Only check the first value against nargs. check_default = next(_check_iter(check_default), None) except TypeError: raise ValueError( "'default' must be a list when 'multiple' is true." ) from None # Can be None for multiple with empty default. if nargs != 1 and check_default is not None: try: _check_iter(check_default) except TypeError: if multiple: message = ( "'default' must be a list of lists when 'multiple' is" " true and 'nargs' != 1." ) else: message = "'default' must be a list when 'nargs' != 1." raise ValueError(message) from None if nargs > 1 and len(check_default) != nargs: subject = "item length" if multiple else "length" raise ValueError( f"'default' {subject} must match nargs={nargs}." )
(self) -> Dict[str, Any]
9,270
asyncclick.core
type_cast_value
Convert and validate a value against the option's :attr:`type`, :attr:`multiple`, and :attr:`nargs`.
def type_cast_value(self, ctx: Context, value: t.Any) -> t.Any: """Convert and validate a value against the option's :attr:`type`, :attr:`multiple`, and :attr:`nargs`. """ if value is None: return () if self.multiple or self.nargs == -1 else None def check_iter(value: t.Any) -> t.Iterator[t.Any]: try: return _check_iter(value) except TypeError: # This should only happen when passing in args manually, # the parser should construct an iterable when parsing # the command line. raise BadParameter( _("Value must be an iterable."), ctx=ctx, param=self ) from None if self.nargs == 1 or self.type.is_composite: def convert(value: t.Any) -> t.Any: return self.type(value, param=self, ctx=ctx) elif self.nargs == -1: def convert(value: t.Any) -> t.Any: # t.Tuple[t.Any, ...] return tuple(self.type(x, self, ctx) for x in check_iter(value)) else: # nargs > 1 def convert(value: t.Any) -> t.Any: # t.Tuple[t.Any, ...] value = tuple(check_iter(value)) if len(value) != self.nargs: raise BadParameter( ngettext( "Takes {nargs} values but 1 was given.", "Takes {nargs} values but {len} were given.", len(value), ).format(nargs=self.nargs, len=len(value)), ctx=ctx, param=self, ) return tuple(self.type(x, self, ctx) for x in value) if self.multiple: return tuple(convert(x) for x in check_iter(value)) return convert(value)
(self, ctx: asyncclick.core.Context, value: Any) -> Any
9,272
asyncclick.core
value_is_missing
null
def value_is_missing(self, value: t.Any) -> bool: if value is None: return True if (self.nargs != 1 or self.multiple) and value == (): return True return False
(self, value: Any) -> bool
9,273
asyncclick.exceptions
BadArgumentUsage
Raised if an argument is generally supplied but the use of the argument was incorrect. This is for instance raised if the number of values for an argument is not correct. .. versionadded:: 6.0
class BadArgumentUsage(UsageError): """Raised if an argument is generally supplied but the use of the argument was incorrect. This is for instance raised if the number of values for an argument is not correct. .. versionadded:: 6.0 """
(message: str, ctx: Optional[ForwardRef('Context')] = None) -> None
9,274
asyncclick.exceptions
__init__
null
def __init__(self, message: str, ctx: t.Optional["Context"] = None) -> None: super().__init__(message) self.ctx = ctx self.cmd: t.Optional["Command"] = self.ctx.command if self.ctx else None
(self, message: str, ctx: Optional[ForwardRef('Context')] = None) -> None
9,275
asyncclick.exceptions
__str__
null
def __str__(self) -> str: return self.message
(self) -> str
9,276
asyncclick.exceptions
format_message
null
def format_message(self) -> str: return self.message
(self) -> str
9,277
asyncclick.exceptions
show
null
def show(self, file: t.Optional[t.IO[t.Any]] = None) -> None: if file is None: file = get_text_stderr() color = None hint = "" if ( self.ctx is not None and self.ctx.command.get_help_option(self.ctx) is not None ): hint = _("Try '{command} {option}' for help.").format( command=self.ctx.command_path, option=self.ctx.help_option_names[0] ) hint = f"{hint}\n" if self.ctx is not None: color = self.ctx.color echo(f"{self.ctx.get_usage()}\n{hint}", file=file, color=color) echo( _("Error: {message}").format(message=self.format_message()), file=file, color=color, )
(self, file: Optional[IO[Any]] = None) -> NoneType
9,278
asyncclick.exceptions
BadOptionUsage
Raised if an option is generally supplied but the use of the option was incorrect. This is for instance raised if the number of arguments for an option is not correct. .. versionadded:: 4.0 :param option_name: the name of the option being used incorrectly.
class BadOptionUsage(UsageError): """Raised if an option is generally supplied but the use of the option was incorrect. This is for instance raised if the number of arguments for an option is not correct. .. versionadded:: 4.0 :param option_name: the name of the option being used incorrectly. """ def __init__( self, option_name: str, message: str, ctx: t.Optional["Context"] = None ) -> None: super().__init__(message, ctx) self.option_name = option_name
(option_name: str, message: str, ctx: Optional[ForwardRef('Context')] = None) -> None
9,279
asyncclick.exceptions
__init__
null
def __init__( self, option_name: str, message: str, ctx: t.Optional["Context"] = None ) -> None: super().__init__(message, ctx) self.option_name = option_name
(self, option_name: str, message: str, ctx: Optional[ForwardRef('Context')] = None) -> None
9,283
asyncclick.exceptions
BadParameter
An exception that formats out a standardized error message for a bad parameter. This is useful when thrown from a callback or type as Click will attach contextual information to it (for instance, which parameter it is). .. versionadded:: 2.0 :param param: the parameter object that caused this error. This can be left out, and Click will attach this info itself if possible. :param param_hint: a string that shows up as parameter name. This can be used as alternative to `param` in cases where custom validation should happen. If it is a string it's used as such, if it's a list then each item is quoted and separated.
class BadParameter(UsageError): """An exception that formats out a standardized error message for a bad parameter. This is useful when thrown from a callback or type as Click will attach contextual information to it (for instance, which parameter it is). .. versionadded:: 2.0 :param param: the parameter object that caused this error. This can be left out, and Click will attach this info itself if possible. :param param_hint: a string that shows up as parameter name. This can be used as alternative to `param` in cases where custom validation should happen. If it is a string it's used as such, if it's a list then each item is quoted and separated. """ def __init__( self, message: str, ctx: t.Optional["Context"] = None, param: t.Optional["Parameter"] = None, param_hint: t.Optional[str] = None, ) -> None: super().__init__(message, ctx) self.param = param self.param_hint = param_hint def format_message(self) -> str: if self.param_hint is not None: param_hint = self.param_hint elif self.param is not None: param_hint = self.param.get_error_hint(self.ctx) # type: ignore else: return _("Invalid value: {message}").format(message=self.message) return _("Invalid value for {param_hint}: {message}").format( param_hint=_join_param_hints(param_hint), message=self.message )
(message: str, ctx: Optional[ForwardRef('Context')] = None, param: Optional[ForwardRef('Parameter')] = None, param_hint: Optional[str] = None) -> None
9,284
asyncclick.exceptions
__init__
null
def __init__( self, message: str, ctx: t.Optional["Context"] = None, param: t.Optional["Parameter"] = None, param_hint: t.Optional[str] = None, ) -> None: super().__init__(message, ctx) self.param = param self.param_hint = param_hint
(self, message: str, ctx: Optional[ForwardRef('Context')] = None, param: Optional[ForwardRef('Parameter')] = None, param_hint: Optional[str] = None) -> None
9,286
asyncclick.exceptions
format_message
null
def format_message(self) -> str: if self.param_hint is not None: param_hint = self.param_hint elif self.param is not None: param_hint = self.param.get_error_hint(self.ctx) # type: ignore else: return _("Invalid value: {message}").format(message=self.message) return _("Invalid value for {param_hint}: {message}").format( param_hint=_join_param_hints(param_hint), message=self.message )
(self) -> str
9,288
asyncclick.core
BaseCommand
The base command implements the minimal API contract of commands. Most code will never use this as it does not implement a lot of useful functionality but it can act as the direct subclass of alternative parsing methods that do not depend on the Click parser. For instance, this can be used to bridge Click and other systems like argparse or docopt. Because base commands do not implement a lot of the API that other parts of Click take for granted, they are not supported for all operations. For instance, they cannot be used with the decorators usually and they have no built-in callback system. .. versionchanged:: 2.0 Added the `context_settings` parameter. :param name: the name of the command to use unless a group overrides it. :param context_settings: an optional dictionary with defaults that are passed to the context object.
class BaseCommand: """The base command implements the minimal API contract of commands. Most code will never use this as it does not implement a lot of useful functionality but it can act as the direct subclass of alternative parsing methods that do not depend on the Click parser. For instance, this can be used to bridge Click and other systems like argparse or docopt. Because base commands do not implement a lot of the API that other parts of Click take for granted, they are not supported for all operations. For instance, they cannot be used with the decorators usually and they have no built-in callback system. .. versionchanged:: 2.0 Added the `context_settings` parameter. :param name: the name of the command to use unless a group overrides it. :param context_settings: an optional dictionary with defaults that are passed to the context object. """ #: The context class to create with :meth:`make_context`. #: #: .. versionadded:: 8.0 context_class: t.Type[Context] = Context #: the default for the :attr:`Context.allow_extra_args` flag. allow_extra_args = False #: the default for the :attr:`Context.allow_interspersed_args` flag. allow_interspersed_args = True #: the default for the :attr:`Context.ignore_unknown_options` flag. ignore_unknown_options = False def __init__( self, name: t.Optional[str], context_settings: t.Optional[t.MutableMapping[str, t.Any]] = None, ) -> None: #: the name the command thinks it has. Upon registering a command #: on a :class:`Group` the group will default the command name #: with this information. You should instead use the #: :class:`Context`\'s :attr:`~Context.info_name` attribute. self.name = name if context_settings is None: context_settings = {} #: an optional dictionary with defaults passed to the context. self.context_settings: t.MutableMapping[str, t.Any] = context_settings async def to_info_dict(self, ctx: Context) -> t.Dict[str, t.Any]: """Gather information that could be useful for a tool generating user-facing documentation. This traverses the entire structure below this command. Use :meth:`click.Context.to_info_dict` to traverse the entire CLI structure. :param ctx: A :class:`Context` representing this command. .. versionadded:: 8.0 """ return {"name": self.name} def __repr__(self) -> str: return f"<{self.__class__.__name__} {self.name}>" def get_usage(self, ctx: Context) -> str: raise NotImplementedError("Base commands cannot get usage") def get_help(self, ctx: Context) -> str: raise NotImplementedError("Base commands cannot get help") async def make_context( self, info_name: t.Optional[str], args: t.List[str], parent: t.Optional[Context] = None, **extra: t.Any, ) -> Context: """This function when given an info name and arguments will kick off the parsing and create a new :class:`Context`. It does not invoke the actual command callback though. To quickly customize the context class used without overriding this method, set the :attr:`context_class` attribute. :param info_name: the info name for this invocation. Generally this is the most descriptive name for the script or command. For the toplevel script it's usually the name of the script, for commands below it's the name of the command. :param args: the arguments to parse as list of strings. :param parent: the parent context if available. :param extra: extra keyword arguments forwarded to the context constructor. .. versionchanged:: 8.0 Added the :attr:`context_class` attribute. """ for key, value in self.context_settings.items(): if key not in extra: extra[key] = value ctx = self.context_class( self, info_name=info_name, parent=parent, **extra # type: ignore ) async with ctx.scope(cleanup=False): await self.parse_args(ctx, args) return ctx async def parse_args(self, ctx: Context, args: t.List[str]) -> t.List[str]: """Given a context and a list of arguments this creates the parser and parses the arguments, then modifies the context as necessary. This is automatically invoked by :meth:`make_context`. """ raise NotImplementedError("Base commands do not know how to parse arguments.") async def invoke(self, ctx: Context) -> t.Any: """Given a context, this invokes the command. The default implementation is raising a not implemented error. """ raise NotImplementedError("Base commands are not invocable by default") 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 chained multi-commands. Any command could be part of a chained multi-command, so sibling commands are valid at any point during command completion. Other command classes will return more completions. :param ctx: Invocation context for this command. :param incomplete: Value being completed. May be empty. .. versionadded:: 8.0 """ from .shell_completion import CompletionItem results: t.List["CompletionItem"] = [] while ctx.parent is not None: ctx = ctx.parent if isinstance(ctx.command, MultiCommand) and ctx.command.chain: results.extend( CompletionItem(name, help=command.get_short_help_str()) for name, command in _complete_visible_commands(ctx, incomplete) if name not in ctx.protected_args ) return results @t.overload async def main( self, args: t.Optional[t.Sequence[str]] = None, prog_name: t.Optional[str] = None, complete_var: t.Optional[str] = None, standalone_mode: "te.Literal[True]" = True, **extra: t.Any, ) -> "te.NoReturn": ... @t.overload async def main( self, args: t.Optional[t.Sequence[str]] = None, prog_name: t.Optional[str] = None, complete_var: t.Optional[str] = None, standalone_mode: bool = ..., **extra: t.Any, ) -> t.Any: ... async def main( self, args: t.Optional[t.Sequence[str]] = None, prog_name: t.Optional[str] = None, complete_var: t.Optional[str] = None, standalone_mode: bool = True, windows_expand_args: bool = True, **extra: t.Any, ) -> t.Any: """This is the way to invoke a script with all the bells and whistles as a command line application. This will always terminate the application after a call. If this is not wanted, ``SystemExit`` needs to be caught. This method is also available by directly calling the instance of a :class:`Command`. :param args: the arguments that should be used for parsing. If not provided, ``sys.argv[1:]`` is used. :param prog_name: the program name that should be used. By default the program name is constructed by taking the file name from ``sys.argv[0]``. :param complete_var: the environment variable that controls the bash completion support. The default is ``"_<prog_name>_COMPLETE"`` with prog_name in uppercase. :param standalone_mode: the default behavior is to invoke the script in standalone mode. Click will then handle exceptions and convert them into error messages and the function will never return but shut down the interpreter. If this is set to `False` they will be propagated to the caller and the return value of this function is the return value of :meth:`invoke`. :param windows_expand_args: Expand glob patterns, user dir, and env vars in command line args on Windows. :param extra: extra keyword arguments are forwarded to the context constructor. See :class:`Context` for more information. .. versionchanged:: 8.0.1 Added the ``windows_expand_args`` parameter to allow disabling command line arg expansion on Windows. .. versionchanged:: 8.0 When taking arguments from ``sys.argv`` on Windows, glob patterns, user dir, and env vars are expanded. .. versionchanged:: 3.0 Added the ``standalone_mode`` parameter. """ if args is None: args = sys.argv[1:] if os.name == "nt" and windows_expand_args: args = _expand_args(args) else: args = list(args) if prog_name is None: prog_name = _detect_program_name() # Process shell completion requests and exit early. await self._main_shell_completion(extra, prog_name, complete_var) try: try: async with await self.make_context(prog_name, args, **extra) as ctx: rv = await self.invoke(ctx) if not standalone_mode: return rv # it's not safe to `ctx.exit(rv)` here! # note that `rv` may actually contain data like "1" which # has obvious effects # more subtle case: `rv=[None, None]` can come out of # chained commands which all returned `None` -- so it's not # even always obvious that `rv` indicates success/failure # by its truthiness/falsiness ctx.exit() except (EOFError, KeyboardInterrupt) as e: echo(file=sys.stderr) raise Abort() from e except ClickException as e: if not standalone_mode: raise e.show() sys.exit(e.exit_code) except OSError as e: if e.errno == errno.EPIPE: sys.stdout = t.cast(t.TextIO, PacifyFlushWrapper(sys.stdout)) sys.stderr = t.cast(t.TextIO, PacifyFlushWrapper(sys.stderr)) sys.exit(1) else: raise except Exit as e: if standalone_mode: sys.exit(e.exit_code) else: # in non-standalone mode, return the exit code # note that this is only reached if `self.invoke` above raises # an Exit explicitly -- thus bypassing the check there which # would return its result # the results of non-standalone execution may therefore be # somewhat ambiguous: if there are codepaths which lead to # `ctx.exit(1)` and to `return 1`, the caller won't be able to # tell the difference between the two return e.exit_code except Abort: if not standalone_mode: raise echo(_("Aborted!"), file=sys.stderr) sys.exit(1) async def _main_shell_completion( self, ctx_args: t.MutableMapping[str, t.Any], prog_name: str, complete_var: t.Optional[str] = None, ) -> None: """Check if the shell is asking for tab completion, process that, then exit early. Called from :meth:`main` before the program is invoked. :param prog_name: Name of the executable in the shell. :param complete_var: Name of the environment variable that holds the completion instruction. Defaults to ``_{PROG_NAME}_COMPLETE``. .. versionchanged:: 8.2.0 Dots (``.``) in ``prog_name`` are replaced with underscores (``_``). """ if complete_var is None: complete_name = prog_name.replace("-", "_").replace(".", "_") complete_var = f"_{complete_name}_COMPLETE".upper() instruction = os.environ.get(complete_var) if not instruction: return from .shell_completion import shell_complete rv = await shell_complete(self, ctx_args, prog_name, complete_var, instruction) sys.exit(rv) def __call__(self, *args: t.Any, _anyio_backend: t.Optional[str] = None, _anyio_backend_options: t.Dict[str, t.Any] = {}, **kwargs: t.Any) -> t.Any: """Alias for :meth:`main`.""" main = self.main opts:t.Dict[str, t.Any] = {} if _anyio_backend: opts["backend"] = _anyio_backend if _anyio_backend_options: opts["backend_options"] = _anyio_backend_options return anyio.run(self._main, main, args, kwargs, **opts) async def _main(self, main:t.Callable[..., t.Awaitable[V]], args: t.List[t.Any], kwargs: t.Dict[str, t.Any]) -> V: return await main(*args, **kwargs)
(name: Optional[str], context_settings: Optional[MutableMapping[str, Any]] = None) -> None
9,289
asyncclick.core
__call__
Alias for :meth:`main`.
def __call__(self, *args: t.Any, _anyio_backend: t.Optional[str] = None, _anyio_backend_options: t.Dict[str, t.Any] = {}, **kwargs: t.Any) -> t.Any: """Alias for :meth:`main`.""" main = self.main opts:t.Dict[str, t.Any] = {} if _anyio_backend: opts["backend"] = _anyio_backend if _anyio_backend_options: opts["backend_options"] = _anyio_backend_options return anyio.run(self._main, main, args, kwargs, **opts)
(self, *args: Any, _anyio_backend: Optional[str] = None, _anyio_backend_options: Dict[str, Any] = {}, **kwargs: Any) -> Any
9,290
asyncclick.core
__init__
null
def __init__( self, name: t.Optional[str], context_settings: t.Optional[t.MutableMapping[str, t.Any]] = None, ) -> None: #: the name the command thinks it has. Upon registering a command #: on a :class:`Group` the group will default the command name #: with this information. You should instead use the #: :class:`Context`\'s :attr:`~Context.info_name` attribute. self.name = name if context_settings is None: context_settings = {} #: an optional dictionary with defaults passed to the context. self.context_settings: t.MutableMapping[str, t.Any] = context_settings
(self, name: Optional[str], context_settings: Optional[MutableMapping[str, Any]] = None) -> NoneType
9,292
asyncclick.core
_main
null
def __call__(self, *args: t.Any, _anyio_backend: t.Optional[str] = None, _anyio_backend_options: t.Dict[str, t.Any] = {}, **kwargs: t.Any) -> t.Any: """Alias for :meth:`main`.""" main = self.main opts:t.Dict[str, t.Any] = {} if _anyio_backend: opts["backend"] = _anyio_backend if _anyio_backend_options: opts["backend_options"] = _anyio_backend_options return anyio.run(self._main, main, args, kwargs, **opts)
(self, main: Callable[..., Awaitable[~V]], args: List[Any], kwargs: Dict[str, Any]) -> ~V
9,293
asyncclick.core
_main_shell_completion
Check if the shell is asking for tab completion, process that, then exit early. Called from :meth:`main` before the program is invoked. :param prog_name: Name of the executable in the shell. :param complete_var: Name of the environment variable that holds the completion instruction. Defaults to ``_{PROG_NAME}_COMPLETE``. .. versionchanged:: 8.2.0 Dots (``.``) in ``prog_name`` are replaced with underscores (``_``).
@t.overload async def main( self, args: t.Optional[t.Sequence[str]] = None, prog_name: t.Optional[str] = None, complete_var: t.Optional[str] = None, standalone_mode: bool = ..., **extra: t.Any, ) -> t.Any: ...
(self, ctx_args: MutableMapping[str, Any], prog_name: str, complete_var: Optional[str] = None) -> NoneType
9,294
asyncclick.core
get_help
null
def get_help(self, ctx: Context) -> str: raise NotImplementedError("Base commands cannot get help")
(self, ctx: asyncclick.core.Context) -> str
9,295
asyncclick.core
get_usage
null
def get_usage(self, ctx: Context) -> str: raise NotImplementedError("Base commands cannot get usage")
(self, ctx: asyncclick.core.Context) -> str
9,296
asyncclick.core
invoke
Given a context, this invokes the command. The default implementation is raising a not implemented error.
def get_help(self, ctx: Context) -> str: raise NotImplementedError("Base commands cannot get help")
(self, ctx: asyncclick.core.Context) -> Any
9,297
asyncclick.core
main
This is the way to invoke a script with all the bells and whistles as a command line application. This will always terminate the application after a call. If this is not wanted, ``SystemExit`` needs to be caught. This method is also available by directly calling the instance of a :class:`Command`. :param args: the arguments that should be used for parsing. If not provided, ``sys.argv[1:]`` is used. :param prog_name: the program name that should be used. By default the program name is constructed by taking the file name from ``sys.argv[0]``. :param complete_var: the environment variable that controls the bash completion support. The default is ``"_<prog_name>_COMPLETE"`` with prog_name in uppercase. :param standalone_mode: the default behavior is to invoke the script in standalone mode. Click will then handle exceptions and convert them into error messages and the function will never return but shut down the interpreter. If this is set to `False` they will be propagated to the caller and the return value of this function is the return value of :meth:`invoke`. :param windows_expand_args: Expand glob patterns, user dir, and env vars in command line args on Windows. :param extra: extra keyword arguments are forwarded to the context constructor. See :class:`Context` for more information. .. versionchanged:: 8.0.1 Added the ``windows_expand_args`` parameter to allow disabling command line arg expansion on Windows. .. versionchanged:: 8.0 When taking arguments from ``sys.argv`` on Windows, glob patterns, user dir, and env vars are expanded. .. versionchanged:: 3.0 Added the ``standalone_mode`` parameter.
@t.overload async def main( self, args: t.Optional[t.Sequence[str]] = None, prog_name: t.Optional[str] = None, complete_var: t.Optional[str] = None, standalone_mode: bool = ..., **extra: t.Any, ) -> t.Any: ...
(self, args: Optional[Sequence[str]] = None, prog_name: Optional[str] = None, complete_var: Optional[str] = None, standalone_mode: bool = True, windows_expand_args: bool = True, **extra: Any) -> Any
9,298
asyncclick.core
make_context
This function when given an info name and arguments will kick off the parsing and create a new :class:`Context`. It does not invoke the actual command callback though. To quickly customize the context class used without overriding this method, set the :attr:`context_class` attribute. :param info_name: the info name for this invocation. Generally this is the most descriptive name for the script or command. For the toplevel script it's usually the name of the script, for commands below it's the name of the command. :param args: the arguments to parse as list of strings. :param parent: the parent context if available. :param extra: extra keyword arguments forwarded to the context constructor. .. versionchanged:: 8.0 Added the :attr:`context_class` attribute.
def get_help(self, ctx: Context) -> str: raise NotImplementedError("Base commands cannot get help")
(self, info_name: Optional[str], args: List[str], parent: Optional[asyncclick.core.Context] = None, **extra: Any) -> asyncclick.core.Context
9,299
asyncclick.core
parse_args
Given a context and a list of arguments this creates the parser and parses the arguments, then modifies the context as necessary. This is automatically invoked by :meth:`make_context`.
def get_help(self, ctx: Context) -> str: raise NotImplementedError("Base commands cannot get help")
(self, ctx: asyncclick.core.Context, args: List[str]) -> List[str]
9,300
asyncclick.core
shell_complete
Return a list of completions for the incomplete value. Looks at the names of chained multi-commands. Any command could be part of a chained multi-command, so sibling commands are valid at any point during command completion. Other command classes will return more completions. :param ctx: Invocation context for this command. :param incomplete: Value being completed. May be empty. .. versionadded:: 8.0
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 chained multi-commands. Any command could be part of a chained multi-command, so sibling commands are valid at any point during command completion. Other command classes will return more completions. :param ctx: Invocation context for this command. :param incomplete: Value being completed. May be empty. .. versionadded:: 8.0 """ from .shell_completion import CompletionItem results: t.List["CompletionItem"] = [] while ctx.parent is not None: ctx = ctx.parent if isinstance(ctx.command, MultiCommand) and ctx.command.chain: results.extend( CompletionItem(name, help=command.get_short_help_str()) for name, command in _complete_visible_commands(ctx, incomplete) if name not in ctx.protected_args ) return results
(self, ctx: asyncclick.core.Context, incomplete: str) -> List[ForwardRef('CompletionItem')]
9,301
asyncclick.core
to_info_dict
Gather information that could be useful for a tool generating user-facing documentation. This traverses the entire structure below this command. Use :meth:`click.Context.to_info_dict` to traverse the entire CLI structure. :param ctx: A :class:`Context` representing this command. .. versionadded:: 8.0
def __init__( self, name: t.Optional[str], context_settings: t.Optional[t.MutableMapping[str, t.Any]] = None, ) -> None: #: the name the command thinks it has. Upon registering a command #: on a :class:`Group` the group will default the command name #: with this information. You should instead use the #: :class:`Context`\'s :attr:`~Context.info_name` attribute. self.name = name if context_settings is None: context_settings = {} #: an optional dictionary with defaults passed to the context. self.context_settings: t.MutableMapping[str, t.Any] = context_settings
(self, ctx: asyncclick.core.Context) -> Dict[str, Any]
9,302
asyncclick.types
Choice
The choice type allows a value to be checked against a fixed set of supported values. All of these values have to be strings. You should only pass a list or tuple of choices. Other iterables (like generators) may lead to surprising results. The resulting value will always be one of the originally passed choices regardless of ``case_sensitive`` or any ``ctx.token_normalize_func`` being specified. See :ref:`choice-opts` for an example. :param case_sensitive: Set to false to make choices case insensitive. Defaults to true.
class Choice(ParamType): """The choice type allows a value to be checked against a fixed set of supported values. All of these values have to be strings. You should only pass a list or tuple of choices. Other iterables (like generators) may lead to surprising results. The resulting value will always be one of the originally passed choices regardless of ``case_sensitive`` or any ``ctx.token_normalize_func`` being specified. See :ref:`choice-opts` for an example. :param case_sensitive: Set to false to make choices case insensitive. Defaults to true. """ name = "choice" def __init__(self, choices: t.Sequence[str], case_sensitive: bool = True) -> None: self.choices = choices self.case_sensitive = case_sensitive async def to_info_dict(self) -> t.Dict[str, t.Any]: info_dict = await super().to_info_dict() info_dict["choices"] = self.choices info_dict["case_sensitive"] = self.case_sensitive return info_dict def get_metavar(self, param: "Parameter") -> str: choices_str = "|".join(self.choices) # Use curly braces to indicate a required argument. if param.required and param.param_type_name == "argument": return f"{{{choices_str}}}" # Use square braces to indicate an option or optional argument. return f"[{choices_str}]" def get_missing_message(self, param: "Parameter") -> str: return _("Choose from:\n\t{choices}").format(choices=",\n\t".join(self.choices)) def convert( self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"] ) -> t.Any: # Match through normalization and case sensitivity # first do token_normalize_func, then lowercase # preserve original `value` to produce an accurate message in # `self.fail` normed_value = value normed_choices = {choice: choice for choice in self.choices} if ctx is not None and ctx.token_normalize_func is not None: normed_value = ctx.token_normalize_func(value) normed_choices = { ctx.token_normalize_func(normed_choice): original for normed_choice, original in normed_choices.items() } if not self.case_sensitive: normed_value = normed_value.casefold() normed_choices = { normed_choice.casefold(): original for normed_choice, original in normed_choices.items() } if normed_value in normed_choices: return normed_choices[normed_value] choices_str = ", ".join(map(repr, self.choices)) self.fail( ngettext( "{value!r} is not {choice}.", "{value!r} is not one of {choices}.", len(self.choices), ).format(value=value, choice=choices_str, choices=choices_str), param, ctx, ) def __repr__(self) -> str: return f"Choice({list(self.choices)})" def shell_complete( self, ctx: "Context", param: "Parameter", incomplete: str ) -> t.List["CompletionItem"]: """Complete choices that start with the incomplete value. :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 str_choices = map(str, self.choices) if self.case_sensitive: matched = (c for c in str_choices if c.startswith(incomplete)) else: incomplete = incomplete.lower() matched = (c for c in str_choices if c.lower().startswith(incomplete)) return [CompletionItem(c) for c in matched]
(choices: Sequence[str], case_sensitive: bool = True) -> None
9,303
asyncclick.types
__call__
null
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)
(self, value: Any, param: Optional[ForwardRef('Parameter')] = None, ctx: Optional[ForwardRef('Context')] = None) -> Any
9,304
asyncclick.types
__init__
null
def __init__(self, choices: t.Sequence[str], case_sensitive: bool = True) -> None: self.choices = choices self.case_sensitive = case_sensitive
(self, choices: Sequence[str], case_sensitive: bool = True) -> NoneType
9,305
asyncclick.types
__repr__
null
def __repr__(self) -> str: return f"Choice({list(self.choices)})"
(self) -> str
9,306
asyncclick.types
convert
null
def convert( self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"] ) -> t.Any: # Match through normalization and case sensitivity # first do token_normalize_func, then lowercase # preserve original `value` to produce an accurate message in # `self.fail` normed_value = value normed_choices = {choice: choice for choice in self.choices} if ctx is not None and ctx.token_normalize_func is not None: normed_value = ctx.token_normalize_func(value) normed_choices = { ctx.token_normalize_func(normed_choice): original for normed_choice, original in normed_choices.items() } if not self.case_sensitive: normed_value = normed_value.casefold() normed_choices = { normed_choice.casefold(): original for normed_choice, original in normed_choices.items() } if normed_value in normed_choices: return normed_choices[normed_value] choices_str = ", ".join(map(repr, self.choices)) self.fail( ngettext( "{value!r} is not {choice}.", "{value!r} is not one of {choices}.", len(self.choices), ).format(value=value, choice=choices_str, choices=choices_str), param, ctx, )
(self, value: Any, param: Optional[ForwardRef('Parameter')], ctx: Optional[ForwardRef('Context')]) -> Any
9,307
asyncclick.types
fail
Helper method to fail with an invalid value message.
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)
(self, message: str, param: Optional[ForwardRef('Parameter')] = None, ctx: Optional[ForwardRef('Context')] = None) -> 't.NoReturn'
9,308
asyncclick.types
get_metavar
null
def get_metavar(self, param: "Parameter") -> str: choices_str = "|".join(self.choices) # Use curly braces to indicate a required argument. if param.required and param.param_type_name == "argument": return f"{{{choices_str}}}" # Use square braces to indicate an option or optional argument. return f"[{choices_str}]"
(self, param: 'Parameter') -> str
9,309
asyncclick.types
get_missing_message
null
def get_missing_message(self, param: "Parameter") -> str: return _("Choose from:\n\t{choices}").format(choices=",\n\t".join(self.choices))
(self, param: 'Parameter') -> str
9,310
asyncclick.types
shell_complete
Complete choices that start with the incomplete value. :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"]: """Complete choices that start with the incomplete value. :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 str_choices = map(str, self.choices) if self.case_sensitive: matched = (c for c in str_choices if c.startswith(incomplete)) else: incomplete = incomplete.lower() matched = (c for c in str_choices if c.lower().startswith(incomplete)) return [CompletionItem(c) for c in matched]
(self, ctx: 'Context', param: 'Parameter', incomplete: str) -> List[ForwardRef('CompletionItem')]
9,311
asyncclick.types
split_envvar_value
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.
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)
(self, rv: str) -> Sequence[str]
9,313
asyncclick.exceptions
ClickException
An exception that Click can handle and show to the user.
class ClickException(Exception): """An exception that Click can handle and show to the user.""" #: The exit code for this exception. exit_code = 1 def __init__(self, message: str) -> None: super().__init__(message) self.message = message def format_message(self) -> str: return self.message def __str__(self) -> str: return self.message def show(self, file: t.Optional[t.IO[t.Any]] = None) -> None: if file is None: file = get_text_stderr() echo(_("Error: {message}").format(message=self.format_message()), file=file)
(message: str) -> None
9,314
asyncclick.exceptions
__init__
null
def __init__(self, message: str) -> None: super().__init__(message) self.message = message
(self, message: str) -> NoneType
9,317
asyncclick.exceptions
show
null
def show(self, file: t.Optional[t.IO[t.Any]] = None) -> None: if file is None: file = get_text_stderr() echo(_("Error: {message}").format(message=self.format_message()), file=file)
(self, file: Optional[IO[Any]] = None) -> NoneType
9,318
asyncclick.core
Command
Commands are the basic building block of command line interfaces in Click. A basic command handles command line parsing and might dispatch more parsing to commands nested below it. :param name: the name of the command to use unless a group overrides it. :param context_settings: an optional dictionary with defaults that are passed to the context object. :param callback: the callback to invoke. This is optional. :param params: the parameters to register with this command. This can be either :class:`Option` or :class:`Argument` objects. :param help: the help string to use for this command. :param epilog: like the help string but it's printed at the end of the help page after everything else. :param short_help: the short help to use for this command. This is shown on the command listing of the parent command. :param add_help_option: by default each command registers a ``--help`` option. This can be disabled by this parameter. :param no_args_is_help: this controls what happens if no arguments are provided. This option is disabled by default. If enabled this will add ``--help`` as argument if no arguments are passed :param hidden: hide this command from help outputs. :param deprecated: issues a message indicating that the command is deprecated. .. versionchanged:: 8.1 ``help``, ``epilog``, and ``short_help`` are stored unprocessed, all formatting is done when outputting help text, not at init, and is done even if not using the ``@command`` decorator. .. versionchanged:: 8.0 Added a ``repr`` showing the command name. .. versionchanged:: 7.1 Added the ``no_args_is_help`` parameter. .. versionchanged:: 2.0 Added the ``context_settings`` parameter.
class Command(BaseCommand): """Commands are the basic building block of command line interfaces in Click. A basic command handles command line parsing and might dispatch more parsing to commands nested below it. :param name: the name of the command to use unless a group overrides it. :param context_settings: an optional dictionary with defaults that are passed to the context object. :param callback: the callback to invoke. This is optional. :param params: the parameters to register with this command. This can be either :class:`Option` or :class:`Argument` objects. :param help: the help string to use for this command. :param epilog: like the help string but it's printed at the end of the help page after everything else. :param short_help: the short help to use for this command. This is shown on the command listing of the parent command. :param add_help_option: by default each command registers a ``--help`` option. This can be disabled by this parameter. :param no_args_is_help: this controls what happens if no arguments are provided. This option is disabled by default. If enabled this will add ``--help`` as argument if no arguments are passed :param hidden: hide this command from help outputs. :param deprecated: issues a message indicating that the command is deprecated. .. versionchanged:: 8.1 ``help``, ``epilog``, and ``short_help`` are stored unprocessed, all formatting is done when outputting help text, not at init, and is done even if not using the ``@command`` decorator. .. versionchanged:: 8.0 Added a ``repr`` showing the command name. .. versionchanged:: 7.1 Added the ``no_args_is_help`` parameter. .. versionchanged:: 2.0 Added the ``context_settings`` parameter. """ def __init__( self, name: t.Optional[str], context_settings: t.Optional[t.MutableMapping[str, t.Any]] = None, callback: t.Optional[t.Callable[..., t.Any]] = None, params: t.Optional[t.List["Parameter"]] = None, help: t.Optional[str] = None, epilog: t.Optional[str] = None, short_help: t.Optional[str] = None, options_metavar: t.Optional[str] = "[OPTIONS]", add_help_option: bool = True, no_args_is_help: bool = False, hidden: bool = False, deprecated: bool = False, ) -> None: super().__init__(name, context_settings) #: the callback to execute when the command fires. This might be #: `None` in which case nothing happens. self.callback = callback #: the list of parameters for this command in the order they #: should show up in the help page and execute. Eager parameters #: will automatically be handled before non eager ones. self.params: t.List["Parameter"] = params or [] self.help = help self.epilog = epilog self.options_metavar = options_metavar self.short_help = short_help self.add_help_option = add_help_option self.no_args_is_help = no_args_is_help self.hidden = hidden self.deprecated = deprecated async def to_info_dict(self, ctx: Context) -> t.Dict[str, t.Any]: info_dict = await super().to_info_dict(ctx) info_dict.update( params=[await param.to_info_dict() for param in self.get_params(ctx)], help=self.help, epilog=self.epilog, short_help=self.short_help, hidden=self.hidden, deprecated=self.deprecated, ) return info_dict def get_usage(self, ctx: Context) -> str: """Formats the usage line into a string and returns it. Calls :meth:`format_usage` internally. """ formatter = ctx.make_formatter() self.format_usage(ctx, formatter) return formatter.getvalue().rstrip("\n") def get_params(self, ctx: Context) -> t.List["Parameter"]: rv = self.params help_option = self.get_help_option(ctx) if help_option is not None: rv = [*rv, help_option] return rv def format_usage(self, ctx: Context, formatter: HelpFormatter) -> None: """Writes the usage line into the formatter. This is a low-level method called by :meth:`get_usage`. """ pieces = self.collect_usage_pieces(ctx) formatter.write_usage(ctx.command_path, " ".join(pieces)) def collect_usage_pieces(self, ctx: Context) -> t.List[str]: """Returns all the pieces that go into the usage line and returns it as a list of strings. """ rv = [self.options_metavar] if self.options_metavar else [] for param in self.get_params(ctx): rv.extend(param.get_usage_pieces(ctx)) return rv def get_help_option_names(self, ctx: Context) -> t.List[str]: """Returns the names for the help option.""" all_names = set(ctx.help_option_names) for param in self.params: all_names.difference_update(param.opts) all_names.difference_update(param.secondary_opts) return list(all_names) def get_help_option(self, ctx: Context) -> t.Optional["Option"]: """Returns the help option object.""" help_options = self.get_help_option_names(ctx) if not help_options or not self.add_help_option: return None def show_help(ctx: Context, param: "Parameter", value: str) -> None: if value and not ctx.resilient_parsing: echo(ctx.get_help(), color=ctx.color) ctx.exit() return Option( help_options, is_flag=True, is_eager=True, expose_value=False, callback=show_help, help=_("Show this message and exit."), ) def make_parser(self, ctx: Context) -> OptionParser: """Creates the underlying option parser for this command.""" parser = OptionParser(ctx) for param in self.get_params(ctx): param.add_to_parser(parser, ctx) return parser def get_help(self, ctx: Context) -> str: """Formats the help into a string and returns it. Calls :meth:`format_help` internally. """ formatter = ctx.make_formatter() self.format_help(ctx, formatter) return formatter.getvalue().rstrip("\n") def get_short_help_str(self, limit: int = 45) -> str: """Gets short help for the command or makes it by shortening the long help string. """ if self.short_help: text = inspect.cleandoc(self.short_help) elif self.help: text = make_default_short_help(self.help, limit) else: text = "" if self.deprecated: text = _("(Deprecated) {text}").format(text=text) return text.strip() def format_help(self, ctx: Context, formatter: HelpFormatter) -> None: """Writes the help into the formatter if it exists. This is a low-level method called by :meth:`get_help`. This calls the following methods: - :meth:`format_usage` - :meth:`format_help_text` - :meth:`format_options` - :meth:`format_epilog` """ self.format_usage(ctx, formatter) self.format_help_text(ctx, formatter) self.format_options(ctx, formatter) self.format_epilog(ctx, formatter) def format_help_text(self, ctx: Context, formatter: HelpFormatter) -> None: """Writes the help text to the formatter if it exists.""" if self.help is not None: # truncate the help text to the first form feed text = inspect.cleandoc(self.help).partition("\f")[0] else: text = "" if self.deprecated: text = _("(Deprecated) {text}").format(text=text) if text: formatter.write_paragraph() with formatter.indentation(): formatter.write_text(text) def format_options(self, ctx: Context, formatter: HelpFormatter) -> None: """Writes all the options into the formatter if they exist.""" opts = [] for param in self.get_params(ctx): rv = param.get_help_record(ctx) if rv is not None: opts.append(rv) if opts: with formatter.section(_("Options")): formatter.write_dl(opts) def format_epilog(self, ctx: Context, formatter: HelpFormatter) -> None: """Writes the epilog into the formatter if it exists.""" if self.epilog: epilog = inspect.cleandoc(self.epilog) formatter.write_paragraph() with formatter.indentation(): formatter.write_text(epilog) 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() parser = self.make_parser(ctx) opts, args, param_order = await parser.parse_args(args=args) for param in iter_params_for_processing(param_order, self.get_params(ctx)): value, args = await param.handle_parse_result(ctx, opts, args) if args and not ctx.allow_extra_args and not ctx.resilient_parsing: ctx.fail( ngettext( "Got unexpected extra argument ({args})", "Got unexpected extra arguments ({args})", len(args), ).format(args=" ".join(map(str, args))) ) ctx.args = args ctx._opt_prefixes.update(parser._opt_prefixes) return args async def invoke(self, ctx: Context) -> t.Any: """Given a context, this invokes the attached callback (if it exists) in the right way. """ if self.deprecated: message = _( "DeprecationWarning: The command {name!r} is deprecated." ).format(name=self.name) echo(style(message, fg="red"), err=True) if self.callback is not None: return await ctx.invoke(self.callback, **ctx.params) 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 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: t.List["CompletionItem"] = [] if incomplete and not incomplete[0].isalnum(): for param in self.get_params(ctx): if ( not isinstance(param, Option) or param.hidden or ( not param.multiple and ctx.get_parameter_source(param.name) # type: ignore is ParameterSource.COMMANDLINE ) ): continue results.extend( CompletionItem(name, help=param.help) for name in [*param.opts, *param.secondary_opts] if name.startswith(incomplete) ) results.extend(super().shell_complete(ctx, incomplete)) return results
(name: Optional[str], context_settings: Optional[MutableMapping[str, Any]] = None, callback: Optional[Callable[..., Any]] = None, params: Optional[List[ForwardRef('Parameter')]] = None, help: Optional[str] = None, epilog: Optional[str] = None, short_help: Optional[str] = None, options_metavar: Optional[str] = '[OPTIONS]', add_help_option: bool = True, no_args_is_help: bool = False, hidden: bool = False, deprecated: bool = False) -> None
9,320
asyncclick.core
__init__
null
def __init__( self, name: t.Optional[str], context_settings: t.Optional[t.MutableMapping[str, t.Any]] = None, callback: t.Optional[t.Callable[..., t.Any]] = None, params: t.Optional[t.List["Parameter"]] = None, help: t.Optional[str] = None, epilog: t.Optional[str] = None, short_help: t.Optional[str] = None, options_metavar: t.Optional[str] = "[OPTIONS]", add_help_option: bool = True, no_args_is_help: bool = False, hidden: bool = False, deprecated: bool = False, ) -> None: super().__init__(name, context_settings) #: the callback to execute when the command fires. This might be #: `None` in which case nothing happens. self.callback = callback #: the list of parameters for this command in the order they #: should show up in the help page and execute. Eager parameters #: will automatically be handled before non eager ones. self.params: t.List["Parameter"] = params or [] self.help = help self.epilog = epilog self.options_metavar = options_metavar self.short_help = short_help self.add_help_option = add_help_option self.no_args_is_help = no_args_is_help self.hidden = hidden self.deprecated = deprecated
(self, name: Optional[str], context_settings: Optional[MutableMapping[str, Any]] = None, callback: Optional[Callable[..., Any]] = None, params: Optional[List[asyncclick.core.Parameter]] = None, help: Optional[str] = None, epilog: Optional[str] = None, short_help: Optional[str] = None, options_metavar: Optional[str] = '[OPTIONS]', add_help_option: bool = True, no_args_is_help: bool = False, hidden: bool = False, deprecated: bool = False) -> NoneType
9,324
asyncclick.core
collect_usage_pieces
Returns all the pieces that go into the usage line and returns it as a list of strings.
def collect_usage_pieces(self, ctx: Context) -> t.List[str]: """Returns all the pieces that go into the usage line and returns it as a list of strings. """ rv = [self.options_metavar] if self.options_metavar else [] for param in self.get_params(ctx): rv.extend(param.get_usage_pieces(ctx)) return rv
(self, ctx: asyncclick.core.Context) -> List[str]
9,325
asyncclick.core
format_epilog
Writes the epilog into the formatter if it exists.
def format_epilog(self, ctx: Context, formatter: HelpFormatter) -> None: """Writes the epilog into the formatter if it exists.""" if self.epilog: epilog = inspect.cleandoc(self.epilog) formatter.write_paragraph() with formatter.indentation(): formatter.write_text(epilog)
(self, ctx: asyncclick.core.Context, formatter: asyncclick.formatting.HelpFormatter) -> NoneType
9,326
asyncclick.core
format_help
Writes the help into the formatter if it exists. This is a low-level method called by :meth:`get_help`. This calls the following methods: - :meth:`format_usage` - :meth:`format_help_text` - :meth:`format_options` - :meth:`format_epilog`
def format_help(self, ctx: Context, formatter: HelpFormatter) -> None: """Writes the help into the formatter if it exists. This is a low-level method called by :meth:`get_help`. This calls the following methods: - :meth:`format_usage` - :meth:`format_help_text` - :meth:`format_options` - :meth:`format_epilog` """ self.format_usage(ctx, formatter) self.format_help_text(ctx, formatter) self.format_options(ctx, formatter) self.format_epilog(ctx, formatter)
(self, ctx: asyncclick.core.Context, formatter: asyncclick.formatting.HelpFormatter) -> NoneType
9,327
asyncclick.core
format_help_text
Writes the help text to the formatter if it exists.
def format_help_text(self, ctx: Context, formatter: HelpFormatter) -> None: """Writes the help text to the formatter if it exists.""" if self.help is not None: # truncate the help text to the first form feed text = inspect.cleandoc(self.help).partition("\f")[0] else: text = "" if self.deprecated: text = _("(Deprecated) {text}").format(text=text) if text: formatter.write_paragraph() with formatter.indentation(): formatter.write_text(text)
(self, ctx: asyncclick.core.Context, formatter: asyncclick.formatting.HelpFormatter) -> NoneType
9,328
asyncclick.core
format_options
Writes all the options into the formatter if they exist.
def format_options(self, ctx: Context, formatter: HelpFormatter) -> None: """Writes all the options into the formatter if they exist.""" opts = [] for param in self.get_params(ctx): rv = param.get_help_record(ctx) if rv is not None: opts.append(rv) if opts: with formatter.section(_("Options")): formatter.write_dl(opts)
(self, ctx: asyncclick.core.Context, formatter: asyncclick.formatting.HelpFormatter) -> NoneType
9,329
asyncclick.core
format_usage
Writes the usage line into the formatter. This is a low-level method called by :meth:`get_usage`.
def format_usage(self, ctx: Context, formatter: HelpFormatter) -> None: """Writes the usage line into the formatter. This is a low-level method called by :meth:`get_usage`. """ pieces = self.collect_usage_pieces(ctx) formatter.write_usage(ctx.command_path, " ".join(pieces))
(self, ctx: asyncclick.core.Context, formatter: asyncclick.formatting.HelpFormatter) -> NoneType
9,330
asyncclick.core
get_help
Formats the help into a string and returns it. Calls :meth:`format_help` internally.
def get_help(self, ctx: Context) -> str: """Formats the help into a string and returns it. Calls :meth:`format_help` internally. """ formatter = ctx.make_formatter() self.format_help(ctx, formatter) return formatter.getvalue().rstrip("\n")
(self, ctx: asyncclick.core.Context) -> str
9,331
asyncclick.core
get_help_option
Returns the help option object.
def get_help_option(self, ctx: Context) -> t.Optional["Option"]: """Returns the help option object.""" help_options = self.get_help_option_names(ctx) if not help_options or not self.add_help_option: return None def show_help(ctx: Context, param: "Parameter", value: str) -> None: if value and not ctx.resilient_parsing: echo(ctx.get_help(), color=ctx.color) ctx.exit() return Option( help_options, is_flag=True, is_eager=True, expose_value=False, callback=show_help, help=_("Show this message and exit."), )
(self, ctx: asyncclick.core.Context) -> Optional[asyncclick.core.Option]
9,332
asyncclick.core
get_help_option_names
Returns the names for the help option.
def get_help_option_names(self, ctx: Context) -> t.List[str]: """Returns the names for the help option.""" all_names = set(ctx.help_option_names) for param in self.params: all_names.difference_update(param.opts) all_names.difference_update(param.secondary_opts) return list(all_names)
(self, ctx: asyncclick.core.Context) -> List[str]
9,333
asyncclick.core
get_params
null
def get_params(self, ctx: Context) -> t.List["Parameter"]: rv = self.params help_option = self.get_help_option(ctx) if help_option is not None: rv = [*rv, help_option] return rv
(self, ctx: asyncclick.core.Context) -> List[asyncclick.core.Parameter]
9,334
asyncclick.core
get_short_help_str
Gets short help for the command or makes it by shortening the long help string.
def get_short_help_str(self, limit: int = 45) -> str: """Gets short help for the command or makes it by shortening the long help string. """ if self.short_help: text = inspect.cleandoc(self.short_help) elif self.help: text = make_default_short_help(self.help, limit) else: text = "" if self.deprecated: text = _("(Deprecated) {text}").format(text=text) return text.strip()
(self, limit: int = 45) -> str
9,335
asyncclick.core
get_usage
Formats the usage line into a string and returns it. Calls :meth:`format_usage` internally.
def get_usage(self, ctx: Context) -> str: """Formats the usage line into a string and returns it. Calls :meth:`format_usage` internally. """ formatter = ctx.make_formatter() self.format_usage(ctx, formatter) return formatter.getvalue().rstrip("\n")
(self, ctx: asyncclick.core.Context) -> str
9,336
asyncclick.core
invoke
Given a context, this invokes the attached callback (if it exists) in the right way.
def format_epilog(self, ctx: Context, formatter: HelpFormatter) -> None: """Writes the epilog into the formatter if it exists.""" if self.epilog: epilog = inspect.cleandoc(self.epilog) formatter.write_paragraph() with formatter.indentation(): formatter.write_text(epilog)
(self, ctx: asyncclick.core.Context) -> Any
9,339
asyncclick.core
make_parser
Creates the underlying option parser for this command.
def make_parser(self, ctx: Context) -> OptionParser: """Creates the underlying option parser for this command.""" parser = OptionParser(ctx) for param in self.get_params(ctx): param.add_to_parser(parser, ctx) return parser
(self, ctx: asyncclick.core.Context) -> asyncclick.parser.OptionParser
9,340
asyncclick.core
parse_args
null
def format_epilog(self, ctx: Context, formatter: HelpFormatter) -> None: """Writes the epilog into the formatter if it exists.""" if self.epilog: epilog = inspect.cleandoc(self.epilog) formatter.write_paragraph() with formatter.indentation(): formatter.write_text(epilog)
(self, ctx: asyncclick.core.Context, args: List[str]) -> List[str]
9,341
asyncclick.core
shell_complete
Return a list of completions for the incomplete value. Looks at the names of options and chained multi-commands. :param ctx: Invocation context for this command. :param incomplete: Value being completed. May be empty. .. versionadded:: 8.0
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 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: t.List["CompletionItem"] = [] if incomplete and not incomplete[0].isalnum(): for param in self.get_params(ctx): if ( not isinstance(param, Option) or param.hidden or ( not param.multiple and ctx.get_parameter_source(param.name) # type: ignore is ParameterSource.COMMANDLINE ) ): continue results.extend( CompletionItem(name, help=param.help) for name in [*param.opts, *param.secondary_opts] if name.startswith(incomplete) ) results.extend(super().shell_complete(ctx, incomplete)) return results
(self, ctx: asyncclick.core.Context, incomplete: str) -> List[ForwardRef('CompletionItem')]
9,343
asyncclick.core
CommandCollection
A command collection is a multi command that merges multiple multi commands together into one. This is a straightforward implementation that accepts a list of different multi commands as sources and provides all the commands for each of them. See :class:`MultiCommand` and :class:`Command` for the description of ``name`` and ``attrs``.
class CommandCollection(MultiCommand): """A command collection is a multi command that merges multiple multi commands together into one. This is a straightforward implementation that accepts a list of different multi commands as sources and provides all the commands for each of them. See :class:`MultiCommand` and :class:`Command` for the description of ``name`` and ``attrs``. """ def __init__( self, name: t.Optional[str] = None, sources: t.Optional[t.List[MultiCommand]] = None, **attrs: t.Any, ) -> None: super().__init__(name, **attrs) #: The list of registered multi commands. self.sources: t.List[MultiCommand] = sources or [] def add_source(self, multi_cmd: MultiCommand) -> None: """Adds a new multi command to the chain dispatcher.""" self.sources.append(multi_cmd) def get_command(self, ctx: Context, cmd_name: str) -> t.Optional[Command]: for source in self.sources: rv = source.get_command(ctx, cmd_name) if rv is not None: if self.chain: _check_multicommand(self, cmd_name, rv) return rv return None def list_commands(self, ctx: Context) -> t.List[str]: rv: t.Set[str] = set() for source in self.sources: rv.update(source.list_commands(ctx)) return sorted(rv)
(name: Optional[str] = None, sources: Optional[List[asyncclick.core.MultiCommand]] = None, **attrs: Any) -> None
9,345
asyncclick.core
__init__
null
def __init__( self, name: t.Optional[str] = None, sources: t.Optional[t.List[MultiCommand]] = None, **attrs: t.Any, ) -> None: super().__init__(name, **attrs) #: The list of registered multi commands. self.sources: t.List[MultiCommand] = sources or []
(self, name: Optional[str] = None, sources: Optional[List[asyncclick.core.MultiCommand]] = None, **attrs: Any) -> NoneType
9,349
asyncclick.core
add_source
Adds a new multi command to the chain dispatcher.
def add_source(self, multi_cmd: MultiCommand) -> None: """Adds a new multi command to the chain dispatcher.""" self.sources.append(multi_cmd)
(self, multi_cmd: asyncclick.core.MultiCommand) -> NoneType
9,350
asyncclick.core
collect_usage_pieces
null
def collect_usage_pieces(self, ctx: Context) -> t.List[str]: rv = super().collect_usage_pieces(ctx) rv.append(self.subcommand_metavar) return rv
(self, ctx: asyncclick.core.Context) -> List[str]
9,351
asyncclick.core
format_commands
Extra format methods for multi methods that adds all the commands after the options.
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)
(self, ctx: asyncclick.core.Context, formatter: asyncclick.formatting.HelpFormatter) -> NoneType
9,355
asyncclick.core
format_options
null
def format_options(self, ctx: Context, formatter: HelpFormatter) -> None: super().format_options(ctx, formatter) self.format_commands(ctx, formatter)
(self, ctx: asyncclick.core.Context, formatter: asyncclick.formatting.HelpFormatter) -> NoneType
9,357
asyncclick.core
get_command
null
def get_command(self, ctx: Context, cmd_name: str) -> t.Optional[Command]: for source in self.sources: rv = source.get_command(ctx, cmd_name) if rv is not None: if self.chain: _check_multicommand(self, cmd_name, rv) return rv return None
(self, ctx: asyncclick.core.Context, cmd_name: str) -> Optional[asyncclick.core.Command]
9,364
asyncclick.core
invoke
null
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)
(self, ctx: asyncclick.core.Context) -> Any
9,365
asyncclick.core
list_commands
null
def list_commands(self, ctx: Context) -> t.List[str]: rv: t.Set[str] = set() for source in self.sources: rv.update(source.list_commands(ctx)) return sorted(rv)
(self, ctx: asyncclick.core.Context) -> List[str]
9,371
asyncclick.core
result_callback
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 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
(self, replace: bool = False) -> Callable[[~F], ~F]
9,372
asyncclick.core
shell_complete
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
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
(self, ctx: asyncclick.core.Context, incomplete: str) -> List[ForwardRef('CompletionItem')]
9,373
asyncclick.core
to_info_dict
null
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." )
(self, ctx: asyncclick.core.Context) -> Dict[str, Any]
9,374
asyncclick.core
Context
The context is a special internal object that holds state relevant for the script execution at every single level. It's normally invisible to commands unless they opt-in to getting access to it. The context is useful as it can pass internal objects around and can control special execution features such as reading data from environment variables. A context can be used as async context manager in which case it will close any managed contexts, and call :meth:`close` on teardown. :param command: the command class for this context. :param parent: the parent context. :param info_name: the info name for this invocation. Generally this is the most descriptive name for the script or command. For the toplevel script it is usually the name of the script, for commands below it it's the name of the script. :param obj: an arbitrary object of user data. :param auto_envvar_prefix: the prefix to use for automatic environment variables. If this is `None` then reading from environment variables is disabled. This does not affect manually set environment variables which are always read. :param default_map: a dictionary (like object) with default values for parameters. :param terminal_width: the width of the terminal. The default is inherit from parent context. If no context defines the terminal width then auto detection will be applied. :param max_content_width: the maximum width for content rendered by Click (this currently only affects help pages). This defaults to 80 characters if not overridden. In other words: even if the terminal is larger than that, Click will not format things wider than 80 characters by default. In addition to that, formatters might add some safety mapping on the right. :param resilient_parsing: if this flag is enabled then Click will parse without any interactivity or callback invocation. Default values will also be ignored. This is useful for implementing things such as completion support. :param allow_extra_args: if this is set to `True` then extra arguments at the end will not raise an error and will be kept on the context. The default is to inherit from the command. :param allow_interspersed_args: if this is set to `False` then options and arguments cannot be mixed. The default is to inherit from the command. :param ignore_unknown_options: instructs click to ignore options it does not know and keeps them for later processing. :param help_option_names: optionally a list of strings that define how the default help parameter is named. The default is ``['--help']``. :param token_normalize_func: an optional function that is used to normalize tokens (options, choices, etc.). This for instance can be used to implement case insensitive behavior. :param color: controls if the terminal supports ANSI colors or not. The default is autodetection. This is only needed if ANSI codes are used in texts that Click prints which is by default not the case. This for instance would affect help output. :param show_default: Show the default value for commands. If this value is not set, it defaults to the value from the parent context. ``Command.show_default`` overrides this default for the specific command. .. versionchanged:: 8.1 The ``show_default`` parameter is overridden by ``Command.show_default``, instead of the other way around. .. versionchanged:: 8.0 The ``show_default`` parameter defaults to the value from the parent context. .. versionchanged:: 7.1 Added the ``show_default`` parameter. .. versionchanged:: 4.0 Added the ``color``, ``ignore_unknown_options``, and ``max_content_width`` parameters. .. versionchanged:: 3.0 Added the ``allow_extra_args`` and ``allow_interspersed_args`` parameters. .. versionchanged:: 2.0 Added the ``resilient_parsing``, ``help_option_names``, and ``token_normalize_func`` parameters.
class Context: """The context is a special internal object that holds state relevant for the script execution at every single level. It's normally invisible to commands unless they opt-in to getting access to it. The context is useful as it can pass internal objects around and can control special execution features such as reading data from environment variables. A context can be used as async context manager in which case it will close any managed contexts, and call :meth:`close` on teardown. :param command: the command class for this context. :param parent: the parent context. :param info_name: the info name for this invocation. Generally this is the most descriptive name for the script or command. For the toplevel script it is usually the name of the script, for commands below it it's the name of the script. :param obj: an arbitrary object of user data. :param auto_envvar_prefix: the prefix to use for automatic environment variables. If this is `None` then reading from environment variables is disabled. This does not affect manually set environment variables which are always read. :param default_map: a dictionary (like object) with default values for parameters. :param terminal_width: the width of the terminal. The default is inherit from parent context. If no context defines the terminal width then auto detection will be applied. :param max_content_width: the maximum width for content rendered by Click (this currently only affects help pages). This defaults to 80 characters if not overridden. In other words: even if the terminal is larger than that, Click will not format things wider than 80 characters by default. In addition to that, formatters might add some safety mapping on the right. :param resilient_parsing: if this flag is enabled then Click will parse without any interactivity or callback invocation. Default values will also be ignored. This is useful for implementing things such as completion support. :param allow_extra_args: if this is set to `True` then extra arguments at the end will not raise an error and will be kept on the context. The default is to inherit from the command. :param allow_interspersed_args: if this is set to `False` then options and arguments cannot be mixed. The default is to inherit from the command. :param ignore_unknown_options: instructs click to ignore options it does not know and keeps them for later processing. :param help_option_names: optionally a list of strings that define how the default help parameter is named. The default is ``['--help']``. :param token_normalize_func: an optional function that is used to normalize tokens (options, choices, etc.). This for instance can be used to implement case insensitive behavior. :param color: controls if the terminal supports ANSI colors or not. The default is autodetection. This is only needed if ANSI codes are used in texts that Click prints which is by default not the case. This for instance would affect help output. :param show_default: Show the default value for commands. If this value is not set, it defaults to the value from the parent context. ``Command.show_default`` overrides this default for the specific command. .. versionchanged:: 8.1 The ``show_default`` parameter is overridden by ``Command.show_default``, instead of the other way around. .. versionchanged:: 8.0 The ``show_default`` parameter defaults to the value from the parent context. .. versionchanged:: 7.1 Added the ``show_default`` parameter. .. versionchanged:: 4.0 Added the ``color``, ``ignore_unknown_options``, and ``max_content_width`` parameters. .. versionchanged:: 3.0 Added the ``allow_extra_args`` and ``allow_interspersed_args`` parameters. .. versionchanged:: 2.0 Added the ``resilient_parsing``, ``help_option_names``, and ``token_normalize_func`` parameters. """ #: The formatter class to create with :meth:`make_formatter`. #: #: .. versionadded:: 8.0 formatter_class: t.Type["HelpFormatter"] = HelpFormatter _async_mgr: t.Optional[AsyncExitStack] = None 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() async def to_info_dict(self) -> t.Dict[str, t.Any]: """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 """ return { "command": await self.command.to_info_dict(self), "info_name": self.info_name, "allow_extra_args": self.allow_extra_args, "allow_interspersed_args": self.allow_interspersed_args, "ignore_unknown_options": self.ignore_unknown_options, "auto_envvar_prefix": self.auto_envvar_prefix, } async def __aenter__(self) -> "Context": if self._async_mgr is None: self._async_mgr = AsyncExitStack() self._ctx_mgr = await self._async_mgr.__aenter__() self._depth += 1 push_context(self) return self async def __aexit__( self, exc_type: t.Optional[t.Type[BaseException]], exc_value: t.Optional[BaseException], tb: t.Optional[TracebackType], ) -> None: self._depth -= 1 if self._depth == 0: await t.cast(t.AsyncContextManager[t.Any], self._async_mgr).__aexit__(exc_type, exc_value, tb) self.close() pop_context() @asynccontextmanager async def scope(self, cleanup: bool = True) -> t.AsyncIterator["Context"]: """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. """ if not cleanup: self._depth += 1 try: async with self as rv: yield rv finally: if not cleanup: self._depth -= 1 @property def meta(self) -> t.Dict[str, t.Any]: """This is a dictionary which is shared with all the contexts that are nested. It exists so that click utilities can store some state here if they need to. It is however the responsibility of that code to manage this dictionary well. The keys are supposed to be unique dotted strings. For instance module paths are a good choice for it. What is stored in there is irrelevant for the operation of click. However what is important is that code that places data here adheres to the general semantics of the system. Example usage:: LANG_KEY = f'{__name__}.lang' def set_language(value): ctx = get_current_context() ctx.meta[LANG_KEY] = value def get_language(): return get_current_context().meta.get(LANG_KEY, 'en_US') .. versionadded:: 5.0 """ return self._meta 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 ) 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) 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) 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) 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() @property def command_path(self) -> str: """The computed command path. This is used for the ``usage`` information on the help page. It's automatically created by combining the info names of the chain of contexts to the root. """ rv = "" if self.info_name is not None: rv = self.info_name if self.parent is not None: parent_command_path = [self.parent.command_path] if isinstance(self.parent.command, Command): for param in self.parent.command.get_params(self): parent_command_path.extend(param.get_usage_pieces(self)) rv = f"{' '.join(parent_command_path)} {rv}" return rv.lstrip() def find_root(self) -> "Context": """Finds the outermost context.""" node = self while node.parent is not None: node = node.parent return node 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 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 @t.overload def lookup_default( self, name: str, call: "te.Literal[True]" = True ) -> t.Optional[t.Any]: ... @t.overload def lookup_default( self, name: str, call: "te.Literal[False]" = ... ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]: ... 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 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) def abort(self) -> "te.NoReturn": """Aborts the script.""" raise Abort() def exit(self, code: int = 0) -> "te.NoReturn": """Exits the application with a given exit code.""" raise Exit(code) def get_usage(self) -> str: """Helper method to get formatted usage string for the current context and command. """ return self.command.get_usage(self) def get_help(self) -> str: """Helper method to get formatted help page for the current context and command. """ return self.command.get_help(self) def _make_sub_context(self, command: "Command") -> "Context": """Create a new context of the same type as this context, but for a new command. :meta private: """ return type(self)(command, info_name=command.name, parent=self) @t.overload async def invoke( __self, # noqa: B902 __callback: "t.Callable[..., V]", *args: t.Any, **kwargs: t.Any, ) -> V: ... @t.overload async def invoke( __self, # noqa: B902 __callback: "Command", *args: t.Any, **kwargs: t.Any, ) -> t.Any: ... async def invoke( __self, # noqa: B902 __callback: t.Union["Command", "t.Callable[..., V]"], *args: t.Any, **kwargs: t.Any, ) -> t.Union[t.Any, V]: """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. """ if isinstance(__callback, Command): other_cmd = __callback if other_cmd.callback is None: raise TypeError( "The given command does not have a callback that can be invoked." ) else: __callback = t.cast("t.Callable[..., V]", other_cmd.callback) ctx = __self._make_sub_context(other_cmd) for param in other_cmd.params: if param.name not in kwargs and param.expose_value: kwargs[param.name] = param.type_cast_value( # type: ignore ctx, param.get_default(ctx) ) # Track all kwargs as params, so that forward() will pass # them on in subsequent calls. ctx.params.update(kwargs) else: ctx = __self with augment_usage_errors(__self): async with ctx: rv = __callback(*args, **kwargs) if iscoroutine(rv): rv = await rv return rv async def forward( __self, __cmd: "Command", *args: t.Any, **kwargs: t.Any # noqa: B902 ) -> t.Any: """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. """ # Can only forward to other commands, not direct callbacks. if not isinstance(__cmd, Command): raise TypeError("Callback is not a command.") for param in __self.params: if param not in kwargs: kwargs[param] = __self.params[param] return await __self.invoke(__cmd, *args, **kwargs) 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 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)
(command: 'Command', parent: Optional[ForwardRef('Context')] = None, info_name: Optional[str] = None, obj: Optional[Any] = None, auto_envvar_prefix: Optional[str] = None, default_map: Optional[MutableMapping[str, Any]] = None, terminal_width: Optional[int] = None, max_content_width: Optional[int] = None, resilient_parsing: bool = False, allow_extra_args: Optional[bool] = None, allow_interspersed_args: Optional[bool] = None, ignore_unknown_options: Optional[bool] = None, help_option_names: Optional[List[str]] = None, token_normalize_func: Optional[Callable[[str], str]] = None, color: Optional[bool] = None, show_default: Optional[bool] = None) -> None
9,375
asyncclick.core
__aenter__
null
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) -> asyncclick.core.Context
9,378
asyncclick.core
_make_sub_context
Create a new context of the same type as this context, but for a new command. :meta private:
def _make_sub_context(self, command: "Command") -> "Context": """Create a new context of the same type as this context, but for a new command. :meta private: """ return type(self)(command, info_name=command.name, parent=self)
(self, command: asyncclick.core.Command) -> asyncclick.core.Context
9,379
asyncclick.core
abort
Aborts the script.
def abort(self) -> "te.NoReturn": """Aborts the script.""" raise Abort()
(self) -> 'te.NoReturn'