types.py
This file
Path
src/click/types.py
1,209 lines · 39.0 KiB · Python
Last changed by
Fix reconciliation of envvar with `default`, `flag_value` and `type` parameters for flag options (#2956)Kevin Deldyckebefore adoption565f36d
History of this fileTake it
1from __future__ import annotations23import collections.abc as cabc4import enum5import os6import stat7import sys8import typing as t9from datetime import datetime10from gettext import gettext as _11from gettext import ngettext1213from ._compat import _get_argv_encoding14from ._compat import open_stream15from .exceptions import BadParameter16from .utils import format_filename17from .utils import LazyFile18from .utils import safecall1920if t.TYPE_CHECKING:21 import typing_extensions as te2223 from .core import Context24 from .core import Parameter25 from .shell_completion import CompletionItem2627ParamTypeValue = t.TypeVar("ParamTypeValue")282930class ParamType:31 """Represents the type of a parameter. Validates and converts values32 from the command line or Python into the correct type.3334 To implement a custom type, subclass and implement at least the35 following:3637 - The :attr:`name` class attribute must be set.38 - Calling an instance of the type with ``None`` must return39 ``None``. This is already implemented by default.40 - :meth:`convert` must convert string values to the correct type.41 - :meth:`convert` must accept values that are already the correct42 type.43 - It must be able to convert a value if the ``ctx`` and ``param``44 arguments are ``None``. This can occur when converting prompt45 input.46 """4748 is_composite: t.ClassVar[bool] = False49 arity: t.ClassVar[int] = 15051 #: the descriptive name of this type52 name: str5354 #: if a list of this type is expected and the value is pulled from a55 #: string environment variable, this is what splits it up. `None`56 #: means any whitespace. For all parameters the general rule is that57 #: whitespace splits them up. The exception are paths and files which58 #: are split by ``os.path.pathsep`` by default (":" on Unix and ";" on59 #: Windows).60 envvar_list_splitter: t.ClassVar[str | None] = None6162 def to_info_dict(self) -> dict[str, t.Any]:63 """Gather information that could be useful for a tool generating64 user-facing documentation.6566 Use :meth:`click.Context.to_info_dict` to traverse the entire67 CLI structure.6869 .. versionadded:: 8.070 """71 # The class name without the "ParamType" suffix.72 param_type = type(self).__name__.partition("ParamType")[0]73 param_type = param_type.partition("ParameterType")[0]7475 # Custom subclasses might not remember to set a name.76 if hasattr(self, "name"):77 name = self.name78 else:79 name = param_type8081 return {"param_type": param_type, "name": name}8283 def __call__(84 self,85 value: t.Any,86 param: Parameter | None = None,87 ctx: Context | None = None,88 ) -> t.Any:89 if value is not None:90 return self.convert(value, param, ctx)9192 def get_metavar(self, param: Parameter, ctx: Context) -> str | None:93 """Returns the metavar default for this param if it provides one."""9495 def get_missing_message(self, param: Parameter, ctx: Context | None) -> str | None:96 """Optionally might return extra information about a missing97 parameter.9899 .. versionadded:: 2.0100 """101102 def convert(103 self, value: t.Any, param: Parameter | None, ctx: Context | None104 ) -> t.Any:105 """Convert the value to the correct type. This is not called if106 the value is ``None`` (the missing value).107108 This must accept string values from the command line, as well as109 values that are already the correct type. It may also convert110 other compatible types.111112 The ``param`` and ``ctx`` arguments may be ``None`` in certain113 situations, such as when converting prompt input.114115 If the value cannot be converted, call :meth:`fail` with a116 descriptive message.117118 :param value: The value to convert.119 :param param: The parameter that is using this type to convert120 its value. May be ``None``.121 :param ctx: The current context that arrived at this value. May122 be ``None``.123 """124 return value125126 def split_envvar_value(self, rv: str) -> cabc.Sequence[str]:127 """Given a value from an environment variable this splits it up128 into small chunks depending on the defined envvar list splitter.129130 If the splitter is set to `None`, which means that whitespace splits,131 then leading and trailing whitespace is ignored. Otherwise, leading132 and trailing splitters usually lead to empty items being included.133 """134 return (rv or "").split(self.envvar_list_splitter)135136 def fail(137 self,138 message: str,139 param: Parameter | None = None,140 ctx: Context | None = None,141 ) -> t.NoReturn:142 """Helper method to fail with an invalid value message."""143 raise BadParameter(message, ctx=ctx, param=param)144145 def shell_complete(146 self, ctx: Context, param: Parameter, incomplete: str147 ) -> list[CompletionItem]:148 """Return a list of149 :class:`~click.shell_completion.CompletionItem` objects for the150 incomplete value. Most types do not provide completions, but151 some do, and this allows custom types to provide custom152 completions as well.153154 :param ctx: Invocation context for this command.155 :param param: The parameter that is requesting completion.156 :param incomplete: Value being completed. May be empty.157158 .. versionadded:: 8.0159 """160 return []161162163class CompositeParamType(ParamType):164 is_composite = True165166 @property167 def arity(self) -> int: # type: ignore168 raise NotImplementedError()169170171class FuncParamType(ParamType):172 def __init__(self, func: t.Callable[[t.Any], t.Any]) -> None:173 self.name: str = func.__name__174 self.func = func175176 def to_info_dict(self) -> dict[str, t.Any]:177 info_dict = super().to_info_dict()178 info_dict["func"] = self.func179 return info_dict180181 def convert(182 self, value: t.Any, param: Parameter | None, ctx: Context | None183 ) -> t.Any:184 try:185 return self.func(value)186 except ValueError:187 try:188 value = str(value)189 except UnicodeError:190 value = value.decode("utf-8", "replace")191192 self.fail(value, param, ctx)193194195class UnprocessedParamType(ParamType):196 name = "text"197198 def convert(199 self, value: t.Any, param: Parameter | None, ctx: Context | None200 ) -> t.Any:201 return value202203 def __repr__(self) -> str:204 return "UNPROCESSED"205206207class StringParamType(ParamType):208 name = "text"209210 def convert(211 self, value: t.Any, param: Parameter | None, ctx: Context | None212 ) -> t.Any:213 if isinstance(value, bytes):214 enc = _get_argv_encoding()215 try:216 value = value.decode(enc)217 except UnicodeError:218 fs_enc = sys.getfilesystemencoding()219 if fs_enc != enc:220 try:221 value = value.decode(fs_enc)222 except UnicodeError:223 value = value.decode("utf-8", "replace")224 else:225 value = value.decode("utf-8", "replace")226 return value227 return str(value)228229 def __repr__(self) -> str:230 return "STRING"231232233class Choice(ParamType, t.Generic[ParamTypeValue]):234 """The choice type allows a value to be checked against a fixed set235 of supported values.236237 You may pass any iterable value which will be converted to a tuple238 and thus will only be iterated once.239240 The resulting value will always be one of the originally passed choices.241 See :meth:`normalize_choice` for more info on the mapping of strings242 to choices. See :ref:`choice-opts` for an example.243244 :param case_sensitive: Set to false to make choices case245 insensitive. Defaults to true.246247 .. versionchanged:: 8.2.0248 Non-``str`` ``choices`` are now supported. It can additionally be any249 iterable. Before you were not recommended to pass anything but a list or250 tuple.251252 .. versionadded:: 8.2.0253 Choice normalization can be overridden via :meth:`normalize_choice`.254 """255256 name = "choice"257258 def __init__(259 self, choices: cabc.Iterable[ParamTypeValue], case_sensitive: bool = True260 ) -> None:261 self.choices: cabc.Sequence[ParamTypeValue] = tuple(choices)262 self.case_sensitive = case_sensitive263264 def to_info_dict(self) -> dict[str, t.Any]:265 info_dict = super().to_info_dict()266 info_dict["choices"] = self.choices267 info_dict["case_sensitive"] = self.case_sensitive268 return info_dict269270 def _normalized_mapping(271 self, ctx: Context | None = None272 ) -> cabc.Mapping[ParamTypeValue, str]:273 """274 Returns mapping where keys are the original choices and the values are275 the normalized values that are accepted via the command line.276277 This is a simple wrapper around :meth:`normalize_choice`, use that278 instead which is supported.279 """280 return {281 choice: self.normalize_choice(282 choice=choice,283 ctx=ctx,284 )285 for choice in self.choices286 }287288 def normalize_choice(self, choice: ParamTypeValue, ctx: Context | None) -> str:289 """290 Normalize a choice value, used to map a passed string to a choice.291 Each choice must have a unique normalized value.292293 By default uses :meth:`Context.token_normalize_func` and if not case294 sensitive, convert it to a casefolded value.295296 .. versionadded:: 8.2.0297 """298 normed_value = choice.name if isinstance(choice, enum.Enum) else str(choice)299300 if ctx is not None and ctx.token_normalize_func is not None:301 normed_value = ctx.token_normalize_func(normed_value)302303 if not self.case_sensitive:304 normed_value = normed_value.casefold()305306 return normed_value307308 def get_metavar(self, param: Parameter, ctx: Context) -> str | None:309 if param.param_type_name == "option" and not param.show_choices: # type: ignore310 choice_metavars = [311 convert_type(type(choice)).name.upper() for choice in self.choices312 ]313 choices_str = "|".join([*dict.fromkeys(choice_metavars)])314 else:315 choices_str = "|".join(316 [str(i) for i in self._normalized_mapping(ctx=ctx).values()]317 )318319 # Use curly braces to indicate a required argument.320 if param.required and param.param_type_name == "argument":321 return f"{{{choices_str}}}"322323 # Use square braces to indicate an option or optional argument.324 return f"[{choices_str}]"325326 def get_missing_message(self, param: Parameter, ctx: Context | None) -> str:327 """328 Message shown when no choice is passed.329330 .. versionchanged:: 8.2.0 Added ``ctx`` argument.331 """332 return _("Choose from:\n\t{choices}").format(333 choices=",\n\t".join(self._normalized_mapping(ctx=ctx).values())334 )335336 def convert(337 self, value: t.Any, param: Parameter | None, ctx: Context | None338 ) -> ParamTypeValue:339 """340 For a given value from the parser, normalize it and find its341 matching normalized value in the list of choices. Then return the342 matched "original" choice.343 """344 normed_value = self.normalize_choice(choice=value, ctx=ctx)345 normalized_mapping = self._normalized_mapping(ctx=ctx)346347 try:348 return next(349 original350 for original, normalized in normalized_mapping.items()351 if normalized == normed_value352 )353 except StopIteration:354 self.fail(355 self.get_invalid_choice_message(value=value, ctx=ctx),356 param=param,357 ctx=ctx,358 )359360 def get_invalid_choice_message(self, value: t.Any, ctx: Context | None) -> str:361 """Get the error message when the given choice is invalid.362363 :param value: The invalid value.364365 .. versionadded:: 8.2366 """367 choices_str = ", ".join(map(repr, self._normalized_mapping(ctx=ctx).values()))368 return ngettext(369 "{value!r} is not {choice}.",370 "{value!r} is not one of {choices}.",371 len(self.choices),372 ).format(value=value, choice=choices_str, choices=choices_str)373374 def __repr__(self) -> str:375 return f"Choice({list(self.choices)})"376377 def shell_complete(378 self, ctx: Context, param: Parameter, incomplete: str379 ) -> list[CompletionItem]:380 """Complete choices that start with the incomplete value.381382 :param ctx: Invocation context for this command.383 :param param: The parameter that is requesting completion.384 :param incomplete: Value being completed. May be empty.385386 .. versionadded:: 8.0387 """388 from click.shell_completion import CompletionItem389390 str_choices = map(str, self.choices)391392 if self.case_sensitive:393 matched = (c for c in str_choices if c.startswith(incomplete))394 else:395 incomplete = incomplete.lower()396 matched = (c for c in str_choices if c.lower().startswith(incomplete))397398 return [CompletionItem(c) for c in matched]399400401class DateTime(ParamType):402 """The DateTime type converts date strings into `datetime` objects.403404 The format strings which are checked are configurable, but default to some405 common (non-timezone aware) ISO 8601 formats.406407 When specifying *DateTime* formats, you should only pass a list or a tuple.408 Other iterables, like generators, may lead to surprising results.409410 The format strings are processed using ``datetime.strptime``, and this411 consequently defines the format strings which are allowed.412413 Parsing is tried using each format, in order, and the first format which414 parses successfully is used.415416 :param formats: A list or tuple of date format strings, in the order in417 which they should be tried. Defaults to418 ``'%Y-%m-%d'``, ``'%Y-%m-%dT%H:%M:%S'``,419 ``'%Y-%m-%d %H:%M:%S'``.420 """421422 name = "datetime"423424 def __init__(self, formats: cabc.Sequence[str] | None = None):425 self.formats: cabc.Sequence[str] = formats or [426 "%Y-%m-%d",427 "%Y-%m-%dT%H:%M:%S",428 "%Y-%m-%d %H:%M:%S",429 ]430431 def to_info_dict(self) -> dict[str, t.Any]:432 info_dict = super().to_info_dict()433 info_dict["formats"] = self.formats434 return info_dict435436 def get_metavar(self, param: Parameter, ctx: Context) -> str | None:437 return f"[{'|'.join(self.formats)}]"438439 def _try_to_convert_date(self, value: t.Any, format: str) -> datetime | None:440 try:441 return datetime.strptime(value, format)442 except ValueError:443 return None444445 def convert(446 self, value: t.Any, param: Parameter | None, ctx: Context | None447 ) -> t.Any:448 if isinstance(value, datetime):449 return value450451 for format in self.formats:452 converted = self._try_to_convert_date(value, format)453454 if converted is not None:455 return converted456457 formats_str = ", ".join(map(repr, self.formats))458 self.fail(459 ngettext(460 "{value!r} does not match the format {format}.",461 "{value!r} does not match the formats {formats}.",462 len(self.formats),463 ).format(value=value, format=formats_str, formats=formats_str),464 param,465 ctx,466 )467468 def __repr__(self) -> str:469 return "DateTime"470471472class _NumberParamTypeBase(ParamType):473 _number_class: t.ClassVar[type[t.Any]]474475 def convert(476 self, value: t.Any, param: Parameter | None, ctx: Context | None477 ) -> t.Any:478 try:479 return self._number_class(value)480 except ValueError:481 self.fail(482 _("{value!r} is not a valid {number_type}.").format(483 value=value, number_type=self.name484 ),485 param,486 ctx,487 )488489490class _NumberRangeBase(_NumberParamTypeBase):491 def __init__(492 self,493 min: float | None = None,494 max: float | None = None,495 min_open: bool = False,496 max_open: bool = False,497 clamp: bool = False,498 ) -> None:499 self.min = min500 self.max = max501 self.min_open = min_open502 self.max_open = max_open503 self.clamp = clamp504505 def to_info_dict(self) -> dict[str, t.Any]:506 info_dict = super().to_info_dict()507 info_dict.update(508 min=self.min,509 max=self.max,510 min_open=self.min_open,511 max_open=self.max_open,512 clamp=self.clamp,513 )514 return info_dict515516 def convert(517 self, value: t.Any, param: Parameter | None, ctx: Context | None518 ) -> t.Any:519 import operator520521 rv = super().convert(value, param, ctx)522 lt_min: bool = self.min is not None and (523 operator.le if self.min_open else operator.lt524 )(rv, self.min)525 gt_max: bool = self.max is not None and (526 operator.ge if self.max_open else operator.gt527 )(rv, self.max)528529 if self.clamp:530 if lt_min:531 return self._clamp(self.min, 1, self.min_open) # type: ignore532533 if gt_max:534 return self._clamp(self.max, -1, self.max_open) # type: ignore535536 if lt_min or gt_max:537 self.fail(538 _("{value} is not in the range {range}.").format(539 value=rv, range=self._describe_range()540 ),541 param,542 ctx,543 )544545 return rv546547 def _clamp(self, bound: float, dir: t.Literal[1, -1], open: bool) -> float:548 """Find the valid value to clamp to bound in the given549 direction.550551 :param bound: The boundary value.552 :param dir: 1 or -1 indicating the direction to move.553 :param open: If true, the range does not include the bound.554 """555 raise NotImplementedError556557 def _describe_range(self) -> str:558 """Describe the range for use in help text."""559 if self.min is None:560 op = "<" if self.max_open else "<="561 return f"x{op}{self.max}"562563 if self.max is None:564 op = ">" if self.min_open else ">="565 return f"x{op}{self.min}"566567 lop = "<" if self.min_open else "<="568 rop = "<" if self.max_open else "<="569 return f"{self.min}{lop}x{rop}{self.max}"570571 def __repr__(self) -> str:572 clamp = " clamped" if self.clamp else ""573 return f"<{type(self).__name__} {self._describe_range()}{clamp}>"574575576class IntParamType(_NumberParamTypeBase):577 name = "integer"578 _number_class = int579580 def __repr__(self) -> str:581 return "INT"582583584class IntRange(_NumberRangeBase, IntParamType):585 """Restrict an :data:`click.INT` value to a range of accepted586 values. See :ref:`ranges`.587588 If ``min`` or ``max`` are not passed, any value is accepted in that589 direction. If ``min_open`` or ``max_open`` are enabled, the590 corresponding boundary is not included in the range.591592 If ``clamp`` is enabled, a value outside the range is clamped to the593 boundary instead of failing.594595 .. versionchanged:: 8.0596 Added the ``min_open`` and ``max_open`` parameters.597 """598599 name = "integer range"600601 def _clamp( # type: ignore602 self, bound: int, dir: t.Literal[1, -1], open: bool603 ) -> int:604 if not open:605 return bound606607 return bound + dir608609610class FloatParamType(_NumberParamTypeBase):611 name = "float"612 _number_class = float613614 def __repr__(self) -> str:615 return "FLOAT"616617618class FloatRange(_NumberRangeBase, FloatParamType):619 """Restrict a :data:`click.FLOAT` value to a range of accepted620 values. See :ref:`ranges`.621622 If ``min`` or ``max`` are not passed, any value is accepted in that623 direction. If ``min_open`` or ``max_open`` are enabled, the624 corresponding boundary is not included in the range.625626 If ``clamp`` is enabled, a value outside the range is clamped to the627 boundary instead of failing. This is not supported if either628 boundary is marked ``open``.629630 .. versionchanged:: 8.0631 Added the ``min_open`` and ``max_open`` parameters.632 """633634 name = "float range"635636 def __init__(637 self,638 min: float | None = None,639 max: float | None = None,640 min_open: bool = False,641 max_open: bool = False,642 clamp: bool = False,643 ) -> None:644 super().__init__(645 min=min, max=max, min_open=min_open, max_open=max_open, clamp=clamp646 )647648 if (min_open or max_open) and clamp:649 raise TypeError("Clamping is not supported for open bounds.")650651 def _clamp(self, bound: float, dir: t.Literal[1, -1], open: bool) -> float:652 if not open:653 return bound654655 # Could use math.nextafter here, but clamping an656 # open float range doesn't seem to be particularly useful. It's657 # left up to the user to write a callback to do it if needed.658 raise RuntimeError("Clamping is not supported for open bounds.")659660661class BoolParamType(ParamType):662 name = "boolean"663664 bool_states: dict[str, bool] = {665 "1": True,666 "0": False,667 "yes": True,668 "no": False,669 "true": True,670 "false": False,671 "on": True,672 "off": False,673 "t": True,674 "f": False,675 "y": True,676 "n": False,677 # Absence of value is considered False.678 "": False,679 }680 """A mapping of string values to boolean states.681682 Mapping is inspired by :py:attr:`configparser.ConfigParser.BOOLEAN_STATES`683 and extends it.684685 .. caution::686 String values are lower-cased, as the ``str_to_bool`` comparison function687 below is case-insensitive.688689 .. warning::690 The mapping is not exhaustive, and does not cover all possible boolean strings691 representations. It will remains as it is to avoid endless bikeshedding.692693 Future work my be considered to make this mapping user-configurable from public694 API.695 """696697 @staticmethod698 def str_to_bool(value: str | bool) -> bool | None:699 """Convert a string to a boolean value.700701 If the value is already a boolean, it is returned as-is. If the value is a702 string, it is stripped of whitespaces and lower-cased, then checked against703 the known boolean states pre-defined in the `BoolParamType.bool_states` mapping704 above.705706 Returns `None` if the value does not match any known boolean state.707 """708 if isinstance(value, bool):709 return value710 return BoolParamType.bool_states.get(value.strip().lower())711712 def convert(713 self, value: t.Any, param: Parameter | None, ctx: Context | None714 ) -> bool:715 normalized = self.str_to_bool(value)716 if normalized is None:717 self.fail(718 _(719 "{value!r} is not a valid boolean. Recognized values: {states}"720 ).format(value=value, states=", ".join(sorted(self.bool_states))),721 param,722 ctx,723 )724 return normalized725726 def __repr__(self) -> str:727 return "BOOL"728729730class UUIDParameterType(ParamType):731 name = "uuid"732733 def convert(734 self, value: t.Any, param: Parameter | None, ctx: Context | None735 ) -> t.Any:736 import uuid737738 if isinstance(value, uuid.UUID):739 return value740741 value = value.strip()742743 try:744 return uuid.UUID(value)745 except ValueError:746 self.fail(747 _("{value!r} is not a valid UUID.").format(value=value), param, ctx748 )749750 def __repr__(self) -> str:751 return "UUID"752753754class File(ParamType):755 """Declares a parameter to be a file for reading or writing. The file756 is automatically closed once the context tears down (after the command757 finished working).758759 Files can be opened for reading or writing. The special value ``-``760 indicates stdin or stdout depending on the mode.761762 By default, the file is opened for reading text data, but it can also be763 opened in binary mode or for writing. The encoding parameter can be used764 to force a specific encoding.765766 The `lazy` flag controls if the file should be opened immediately or upon767 first IO. The default is to be non-lazy for standard input and output768 streams as well as files opened for reading, `lazy` otherwise. When opening a769 file lazily for reading, it is still opened temporarily for validation, but770 will not be held open until first IO. lazy is mainly useful when opening771 for writing to avoid creating the file until it is needed.772773 Files can also be opened atomically in which case all writes go into a774 separate file in the same folder and upon completion the file will775 be moved over to the original location. This is useful if a file776 regularly read by other users is modified.777778 See :ref:`file-args` for more information.779780 .. versionchanged:: 2.0781 Added the ``atomic`` parameter.782 """783784 name = "filename"785 envvar_list_splitter: t.ClassVar[str] = os.path.pathsep786787 def __init__(788 self,789 mode: str = "r",790 encoding: str | None = None,791 errors: str | None = "strict",792 lazy: bool | None = None,793 atomic: bool = False,794 ) -> None:795 self.mode = mode796 self.encoding = encoding797 self.errors = errors798 self.lazy = lazy799 self.atomic = atomic800801 def to_info_dict(self) -> dict[str, t.Any]:802 info_dict = super().to_info_dict()803 info_dict.update(mode=self.mode, encoding=self.encoding)804 return info_dict805806 def resolve_lazy_flag(self, value: str | os.PathLike[str]) -> bool:807 if self.lazy is not None:808 return self.lazy809 if os.fspath(value) == "-":810 return False811 elif "w" in self.mode:812 return True813 return False814815 def convert(816 self,817 value: str | os.PathLike[str] | t.IO[t.Any],818 param: Parameter | None,819 ctx: Context | None,820 ) -> t.IO[t.Any]:821 if _is_file_like(value):822 return value823824 value = t.cast("str | os.PathLike[str]", value)825826 try:827 lazy = self.resolve_lazy_flag(value)828829 if lazy:830 lf = LazyFile(831 value, self.mode, self.encoding, self.errors, atomic=self.atomic832 )833834 if ctx is not None:835 ctx.call_on_close(lf.close_intelligently)836837 return t.cast("t.IO[t.Any]", lf)838839 f, should_close = open_stream(840 value, self.mode, self.encoding, self.errors, atomic=self.atomic841 )842843 # If a context is provided, we automatically close the file844 # at the end of the context execution (or flush out). If a845 # context does not exist, it's the caller's responsibility to846 # properly close the file. This for instance happens when the847 # type is used with prompts.848 if ctx is not None:849 if should_close:850 ctx.call_on_close(safecall(f.close))851 else:852 ctx.call_on_close(safecall(f.flush))853854 return f855 except OSError as e:856 self.fail(f"'{format_filename(value)}': {e.strerror}", param, ctx)857858 def shell_complete(859 self, ctx: Context, param: Parameter, incomplete: str860 ) -> list[CompletionItem]:861 """Return a special completion marker that tells the completion862 system to use the shell to provide file path completions.863864 :param ctx: Invocation context for this command.865 :param param: The parameter that is requesting completion.866 :param incomplete: Value being completed. May be empty.867868 .. versionadded:: 8.0869 """870 from click.shell_completion import CompletionItem871872 return [CompletionItem(incomplete, type="file")]873874875def _is_file_like(value: t.Any) -> te.TypeGuard[t.IO[t.Any]]:876 return hasattr(value, "read") or hasattr(value, "write")877878879class Path(ParamType):880 """The ``Path`` type is similar to the :class:`File` type, but881 returns the filename instead of an open file. Various checks can be882 enabled to validate the type of file and permissions.883884 :param exists: The file or directory needs to exist for the value to885 be valid. If this is not set to ``True``, and the file does not886 exist, then all further checks are silently skipped.887 :param file_okay: Allow a file as a value.888 :param dir_okay: Allow a directory as a value.889 :param readable: if true, a readable check is performed.890 :param writable: if true, a writable check is performed.891 :param executable: if true, an executable check is performed.892 :param resolve_path: Make the value absolute and resolve any893 symlinks. A ``~`` is not expanded, as this is supposed to be894 done by the shell only.895 :param allow_dash: Allow a single dash as a value, which indicates896 a standard stream (but does not open it). Use897 :func:`~click.open_file` to handle opening this value.898 :param path_type: Convert the incoming path value to this type. If899 ``None``, keep Python's default, which is ``str``. Useful to900 convert to :class:`pathlib.Path`.901902 .. versionchanged:: 8.1903 Added the ``executable`` parameter.904905 .. versionchanged:: 8.0906 Allow passing ``path_type=pathlib.Path``.907908 .. versionchanged:: 6.0909 Added the ``allow_dash`` parameter.910 """911912 envvar_list_splitter: t.ClassVar[str] = os.path.pathsep913914 def __init__(915 self,916 exists: bool = False,917 file_okay: bool = True,918 dir_okay: bool = True,919 writable: bool = False,920 readable: bool = True,921 resolve_path: bool = False,922 allow_dash: bool = False,923 path_type: type[t.Any] | None = None,924 executable: bool = False,925 ):926 self.exists = exists927 self.file_okay = file_okay928 self.dir_okay = dir_okay929 self.readable = readable930 self.writable = writable931 self.executable = executable932 self.resolve_path = resolve_path933 self.allow_dash = allow_dash934 self.type = path_type935936 if self.file_okay and not self.dir_okay:937 self.name: str = _("file")938 elif self.dir_okay and not self.file_okay:939 self.name = _("directory")940 else:941 self.name = _("path")942943 def to_info_dict(self) -> dict[str, t.Any]:944 info_dict = super().to_info_dict()945 info_dict.update(946 exists=self.exists,947 file_okay=self.file_okay,948 dir_okay=self.dir_okay,949 writable=self.writable,950 readable=self.readable,951 allow_dash=self.allow_dash,952 )953 return info_dict954955 def coerce_path_result(956 self, value: str | os.PathLike[str]957 ) -> str | bytes | os.PathLike[str]:958 if self.type is not None and not isinstance(value, self.type):959 if self.type is str:960 return os.fsdecode(value)961 elif self.type is bytes:962 return os.fsencode(value)963 else:964 return t.cast("os.PathLike[str]", self.type(value))965966 return value967968 def convert(969 self,970 value: str | os.PathLike[str],971 param: Parameter | None,972 ctx: Context | None,973 ) -> str | bytes | os.PathLike[str]:974 rv = value975976 is_dash = self.file_okay and self.allow_dash and rv in (b"-", "-")977978 if not is_dash:979 if self.resolve_path:980 rv = os.path.realpath(rv)981982 try:983 st = os.stat(rv)984 except OSError:985 if not self.exists:986 return self.coerce_path_result(rv)987 self.fail(988 _("{name} {filename!r} does not exist.").format(989 name=self.name.title(), filename=format_filename(value)990 ),991 param,992 ctx,993 )994995 if not self.file_okay and stat.S_ISREG(st.st_mode):996 self.fail(997 _("{name} {filename!r} is a file.").format(998 name=self.name.title(), filename=format_filename(value)999 ),1000 param,1001 ctx,1002 )1003 if not self.dir_okay and stat.S_ISDIR(st.st_mode):1004 self.fail(1005 _("{name} {filename!r} is a directory.").format(1006 name=self.name.title(), filename=format_filename(value)1007 ),1008 param,1009 ctx,1010 )10111012 if self.readable and not os.access(rv, os.R_OK):1013 self.fail(1014 _("{name} {filename!r} is not readable.").format(1015 name=self.name.title(), filename=format_filename(value)1016 ),1017 param,1018 ctx,1019 )10201021 if self.writable and not os.access(rv, os.W_OK):1022 self.fail(1023 _("{name} {filename!r} is not writable.").format(1024 name=self.name.title(), filename=format_filename(value)1025 ),1026 param,1027 ctx,1028 )10291030 if self.executable and not os.access(value, os.X_OK):1031 self.fail(1032 _("{name} {filename!r} is not executable.").format(1033 name=self.name.title(), filename=format_filename(value)1034 ),1035 param,1036 ctx,1037 )10381039 return self.coerce_path_result(rv)10401041 def shell_complete(1042 self, ctx: Context, param: Parameter, incomplete: str1043 ) -> list[CompletionItem]:1044 """Return a special completion marker that tells the completion1045 system to use the shell to provide path completions for only1046 directories or any paths.10471048 :param ctx: Invocation context for this command.1049 :param param: The parameter that is requesting completion.1050 :param incomplete: Value being completed. May be empty.10511052 .. versionadded:: 8.01053 """1054 from click.shell_completion import CompletionItem10551056 type = "dir" if self.dir_okay and not self.file_okay else "file"1057 return [CompletionItem(incomplete, type=type)]105810591060class Tuple(CompositeParamType):1061 """The default behavior of Click is to apply a type on a value directly.1062 This works well in most cases, except for when `nargs` is set to a fixed1063 count and different types should be used for different items. In this1064 case the :class:`Tuple` type can be used. This type can only be used1065 if `nargs` is set to a fixed number.10661067 For more information see :ref:`tuple-type`.10681069 This can be selected by using a Python tuple literal as a type.10701071 :param types: a list of types that should be used for the tuple items.1072 """10731074 def __init__(self, types: cabc.Sequence[type[t.Any] | ParamType]) -> None:1075 self.types: cabc.Sequence[ParamType] = [convert_type(ty) for ty in types]10761077 def to_info_dict(self) -> dict[str, t.Any]:1078 info_dict = super().to_info_dict()1079 info_dict["types"] = [t.to_info_dict() for t in self.types]1080 return info_dict10811082 @property1083 def name(self) -> str: # type: ignore1084 return f"<{' '.join(ty.name for ty in self.types)}>"10851086 @property1087 def arity(self) -> int: # type: ignore1088 return len(self.types)10891090 def convert(1091 self, value: t.Any, param: Parameter | None, ctx: Context | None1092 ) -> t.Any:1093 len_type = len(self.types)1094 len_value = len(value)10951096 if len_value != len_type:1097 self.fail(1098 ngettext(1099 "{len_type} values are required, but {len_value} was given.",1100 "{len_type} values are required, but {len_value} were given.",1101 len_value,1102 ).format(len_type=len_type, len_value=len_value),1103 param=param,1104 ctx=ctx,1105 )11061107 return tuple(1108 ty(x, param, ctx) for ty, x in zip(self.types, value, strict=False)1109 )111011111112def convert_type(ty: t.Any | None, default: t.Any | None = None) -> ParamType:1113 """Find the most appropriate :class:`ParamType` for the given Python1114 type. If the type isn't provided, it can be inferred from a default1115 value.1116 """1117 guessed_type = False11181119 if ty is None and default is not None:1120 if isinstance(default, (tuple, list)):1121 # If the default is empty, ty will remain None and will1122 # return STRING.1123 if default:1124 item = default[0]11251126 # A tuple of tuples needs to detect the inner types.1127 # Can't call convert recursively because that would1128 # incorrectly unwind the tuple to a single type.1129 if isinstance(item, (tuple, list)):1130 ty = tuple(map(type, item))1131 else:1132 ty = type(item)1133 else:1134 ty = type(default)11351136 guessed_type = True11371138 if isinstance(ty, tuple):1139 return Tuple(ty)11401141 if isinstance(ty, ParamType):1142 return ty11431144 if ty is str or ty is None:1145 return STRING11461147 if ty is int:1148 return INT11491150 if ty is float:1151 return FLOAT11521153 if ty is bool:1154 return BOOL11551156 if guessed_type:1157 return STRING11581159 if __debug__:1160 try:1161 if issubclass(ty, ParamType):1162 raise AssertionError(1163 f"Attempted to use an uninstantiated parameter type ({ty})."1164 )1165 except TypeError:1166 # ty is an instance (correct), so issubclass fails.1167 pass11681169 return FuncParamType(ty)117011711172#: A dummy parameter type that just does nothing. From a user's1173#: perspective this appears to just be the same as `STRING` but1174#: internally no string conversion takes place if the input was bytes.1175#: This is usually useful when working with file paths as they can1176#: appear in bytes and unicode.1177#:1178#: For path related uses the :class:`Path` type is a better choice but1179#: there are situations where an unprocessed type is useful which is why1180#: it is is provided.1181#:1182#: .. versionadded:: 4.01183UNPROCESSED = UnprocessedParamType()11841185#: A unicode string parameter type which is the implicit default. This1186#: can also be selected by using ``str`` as type.1187STRING = StringParamType()11881189#: An integer parameter. This can also be selected by using ``int`` as1190#: type.1191INT = IntParamType()11921193#: A floating point value parameter. This can also be selected by using1194#: ``float`` as type.1195FLOAT = FloatParamType()11961197#: A boolean parameter. This is the default for boolean flags. This can1198#: also be selected by using ``bool`` as a type.1199BOOL = BoolParamType()12001201#: A UUID parameter.1202UUID = UUIDParameterType()120312041205class OptionHelpExtra(t.TypedDict, total=False):1206 envvars: tuple[str, ...]1207 default: str1208 range: str1209 required: str