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
The walk stopped after 200 commits: lines older than 43d37ff point at it.
enable deferred evaluation of annotations (#2270)David Lordbefore adoption56db546
lines 1–3why, one step back1from __future__ import annotations23import collections.abc as cabcExpand `Choice` token normalization + make generic (#2796)Andreas Backxbefore adoption4ece17a
line 4why, one step back4import enumBump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 5–6why, one step back5import os6import statMerge branch '8.1.x'David Lordbefore adoptiond9af5cf
line 7why, one step back7import sysBump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 8–15why, one step back8import 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 BadParameterMerge branch '8.1.x'David Lordbefore adoptiond9af5cf
line 16why, one step back16from .utils import format_filenameBump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 17–21why, one step back17from .utils import LazyFile18from .utils import safecall1920if t.TYPE_CHECKING:21 import typing_extensions as teuse ruff lint and format (#2658)David Lordbefore adoption1a3baf7
line 22why, one step back22Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 23–26why, one step back23 from .core import Context24 from .core import Parameter25 from .shell_completion import CompletionItem26Expand `Choice` token normalization + make generic (#2796)Andreas Backxbefore adoption4ece17a
line 27why, one step back27ParamTypeValue = t.TypeVar("ParamTypeValue")Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
line 28why, one step back28Expand `Choice` token normalization + make generic (#2796)Andreas Backxbefore adoption4ece17a
line 29why, one step back29Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 30–59why, one step back30class 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).enable deferred evaluation of annotations (#2270)David Lordbefore adoption56db546
line 60why, one step back60 envvar_list_splitter: t.ClassVar[str | None] = NoneBump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
line 61why, one step back61enable deferred evaluation of annotations (#2270)David Lordbefore adoption56db546
line 62why, one step back62 def to_info_dict(self) -> dict[str, t.Any]:Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 63–85why, one step back63 """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,enable deferred evaluation of annotations (#2270)David Lordbefore adoption56db546
lines 86–87why, one step back86 param: Parameter | None = None,87 ctx: Context | None = None,Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 88–91why, one step back88 ) -> t.Any:89 if value is not None:90 return self.convert(value, param, ctx)91Expand `Choice` token normalization + make generic (#2796)Andreas Backxbefore adoption4ece17a
line 92why, one step back92 def get_metavar(self, param: Parameter, ctx: Context) -> str | None:Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 93–94why, one step back93 """Returns the metavar default for this param if it provides one."""94Expand `Choice` token normalization + make generic (#2796)Andreas Backxbefore adoption4ece17a
line 95why, one step back95 def get_missing_message(self, param: Parameter, ctx: Context | None) -> str | None:Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 96–102why, one step back96 """Optionally might return extra information about a missing97 parameter.9899 .. versionadded:: 2.0100 """101102 def convert(enable deferred evaluation of annotations (#2270)David Lordbefore adoption56db546
line 103why, one step back103 self, value: t.Any, param: Parameter | None, ctx: Context | NoneBump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 104–125why, one step back104 ) -> 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 value125enable deferred evaluation of annotations (#2270)David Lordbefore adoption56db546
line 126why, one step back126 def split_envvar_value(self, rv: str) -> cabc.Sequence[str]:Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 127–138why, one step back127 """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,enable deferred evaluation of annotations (#2270)David Lordbefore adoption56db546
lines 139–141why, one step back139 param: Parameter | None = None,140 ctx: Context | None = None,141 ) -> t.NoReturn:Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 142–145why, one step back142 """Helper method to fail with an invalid value message."""143 raise BadParameter(message, ctx=ctx, param=param)144145 def shell_complete(enable deferred evaluation of annotations (#2270)David Lordbefore adoption56db546
lines 146–147why, one step back146 self, ctx: Context, param: Parameter, incomplete: str147 ) -> list[CompletionItem]:Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 148–172why, one step back148 """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:Merge branch '8.1.x'David Lordbefore adoptiond9af5cf
line 173why, one step back173 self.name: str = func.__name__Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 174–175why, one step back174 self.func = func175enable deferred evaluation of annotations (#2270)David Lordbefore adoption56db546
line 176why, one step back176 def to_info_dict(self) -> dict[str, t.Any]:Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 177–181why, one step back177 info_dict = super().to_info_dict()178 info_dict["func"] = self.func179 return info_dict180181 def convert(enable deferred evaluation of annotations (#2270)David Lordbefore adoption56db546
line 182why, one step back182 self, value: t.Any, param: Parameter | None, ctx: Context | NoneBump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 183–198why, one step back183 ) -> 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(enable deferred evaluation of annotations (#2270)David Lordbefore adoption56db546
line 199why, one step back199 self, value: t.Any, param: Parameter | None, ctx: Context | NoneBump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 200–210why, one step back200 ) -> t.Any:201 return value202203 def __repr__(self) -> str:204 return "UNPROCESSED"205206207class StringParamType(ParamType):208 name = "text"209210 def convert(enable deferred evaluation of annotations (#2270)David Lordbefore adoption56db546
line 211why, one step back211 self, value: t.Any, param: Parameter | None, ctx: Context | NoneBump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 212–217why, one step back212 ) -> t.Any:213 if isinstance(value, bytes):214 enc = _get_argv_encoding()215 try:216 value = value.decode(enc)217 except UnicodeError:Merge branch '8.1.x'David Lordbefore adoptiond9af5cf
line 218why, one step back218 fs_enc = sys.getfilesystemencoding()Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 219–232why, one step back219 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"231232Expand `Choice` token normalization + make generic (#2796)Andreas Backxbefore adoption4ece17a
line 233why, one step back233class Choice(ParamType, t.Generic[ParamTypeValue]):Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
line 234why, one step back234 """The choice type allows a value to be checked against a fixed setExpand `Choice` token normalization + make generic (#2796)Andreas Backxbefore adoption4ece17a
line 235why, one step back235 of supported values.Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
line 236why, one step back236Expand `Choice` token normalization + make generic (#2796)Andreas Backxbefore adoption4ece17a
lines 237–238why, one step back237 You may pass any iterable value which will be converted to a tuple238 and thus will only be iterated once.Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
line 239why, one step back239Expand `Choice` token normalization + make generic (#2796)Andreas Backxbefore adoption4ece17a
lines 240–242why, one step back240 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.Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 243–245why, one step back243244 :param case_sensitive: Set to false to make choices case245 insensitive. Defaults to true.Expand `Choice` token normalization + make generic (#2796)Andreas Backxbefore adoption4ece17a
lines 246–253why, one step back246247 .. 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`.Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 254–257why, one step back254 """255256 name = "choice"257enable deferred evaluation of annotations (#2270)David Lordbefore adoption56db546
line 258why, one step back258 def __init__(Expand `Choice` token normalization + make generic (#2796)Andreas Backxbefore adoption4ece17a
line 259why, one step back259 self, choices: cabc.Iterable[ParamTypeValue], case_sensitive: bool = Trueenable deferred evaluation of annotations (#2270)David Lordbefore adoption56db546
line 260why, one step back260 ) -> None:Expand `Choice` token normalization + make generic (#2796)Andreas Backxbefore adoption4ece17a
line 261why, one step back261 self.choices: cabc.Sequence[ParamTypeValue] = tuple(choices)Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 262–263why, one step back262 self.case_sensitive = case_sensitive263enable deferred evaluation of annotations (#2270)David Lordbefore adoption56db546
line 264why, one step back264 def to_info_dict(self) -> dict[str, t.Any]:Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 265–269why, one step back265 info_dict = super().to_info_dict()266 info_dict["choices"] = self.choices267 info_dict["case_sensitive"] = self.case_sensitive268 return info_dict269Expand `Choice` token normalization + make generic (#2796)Andreas Backxbefore adoption4ece17a
lines 270–308why, one step back270 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:Fix metavar for Choice options when show_choices=False (#2365)mrmupsbefore adoption1a4d8c1
lines 309–314why, one step back309 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:Expand `Choice` token normalization + make generic (#2796)Andreas Backxbefore adoption4ece17a
lines 315–317why, one step back315 choices_str = "|".join(316 [str(i) for i in self._normalized_mapping(ctx=ctx).values()]317 )Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 318–325why, one step back318319 # 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}]"325Expand `Choice` token normalization + make generic (#2796)Andreas Backxbefore adoption4ece17a
lines 326–328why, one step back326 def get_missing_message(self, param: Parameter, ctx: Context | None) -> str:327 """328 Message shown when no choice is passed.Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
line 329why, one step back329Expand `Choice` token normalization + make generic (#2796)Andreas Backxbefore adoption4ece17a
lines 330–335why, one step back330 .. 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 )335Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
line 336why, one step back336 def convert(enable deferred evaluation of annotations (#2270)David Lordbefore adoption56db546
line 337why, one step back337 self, value: t.Any, param: Parameter | None, ctx: Context | NoneExpand `Choice` token normalization + make generic (#2796)Andreas Backxbefore adoption4ece17a
lines 338–345why, one step back338 ) -> 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)Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
line 346why, one step back346Expand `Choice` token normalization + make generic (#2796)Andreas Backxbefore adoption4ece17a
lines 347–358why, one step back347 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 )Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
line 359why, one step back359Expand `Choice` token normalization + make generic (#2796)Andreas Backxbefore adoption4ece17a
line 360why, one step back360 def get_invalid_choice_message(self, value: t.Any, ctx: Context | None) -> str:feat: new method for choice fail (#2622)antazoeybefore adoption4271fe2
lines 361–366why, one step back361 """Get the error message when the given choice is invalid.362363 :param value: The invalid value.364365 .. versionadded:: 8.2366 """Expand `Choice` token normalization + make generic (#2796)Andreas Backxbefore adoption4ece17a
line 367why, one step back367 choices_str = ", ".join(map(repr, self._normalized_mapping(ctx=ctx).values()))feat: new method for choice fail (#2622)antazoeybefore adoption4271fe2
lines 368–372why, one step back368 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)Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 373–377why, one step back373374 def __repr__(self) -> str:375 return f"Choice({list(self.choices)})"376377 def shell_complete(enable deferred evaluation of annotations (#2270)David Lordbefore adoption56db546
lines 378–379why, one step back378 self, ctx: Context, param: Parameter, incomplete: str379 ) -> list[CompletionItem]:Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 380–423why, one step back380 """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"423enable deferred evaluation of annotations (#2270)David Lordbefore adoption56db546
lines 424–425why, one step back424 def __init__(self, formats: cabc.Sequence[str] | None = None):425 self.formats: cabc.Sequence[str] = formats or [Merge branch '8.1.x'David Lordbefore adoptiond9af5cf
lines 426–429why, one step back426 "%Y-%m-%d",427 "%Y-%m-%dT%H:%M:%S",428 "%Y-%m-%d %H:%M:%S",429 ]Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
line 430why, one step back430enable deferred evaluation of annotations (#2270)David Lordbefore adoption56db546
line 431why, one step back431 def to_info_dict(self) -> dict[str, t.Any]:Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 432–435why, one step back432 info_dict = super().to_info_dict()433 info_dict["formats"] = self.formats434 return info_dict435Expand `Choice` token normalization + make generic (#2796)Andreas Backxbefore adoption4ece17a
line 436why, one step back436 def get_metavar(self, param: Parameter, ctx: Context) -> str | None:Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 437–438why, one step back437 return f"[{'|'.join(self.formats)}]"438enable deferred evaluation of annotations (#2270)David Lordbefore adoption56db546
line 439why, one step back439 def _try_to_convert_date(self, value: t.Any, format: str) -> datetime | None:Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 440–445why, one step back440 try:441 return datetime.strptime(value, format)442 except ValueError:443 return None444445 def convert(enable deferred evaluation of annotations (#2270)David Lordbefore adoption56db546
line 446why, one step back446 self, value: t.Any, param: Parameter | None, ctx: Context | NoneBump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 447–472why, one step back447 ) -> 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):enable deferred evaluation of annotations (#2270)David Lordbefore adoption56db546
line 473why, one step back473 _number_class: t.ClassVar[type[t.Any]]Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 474–475why, one step back474475 def convert(enable deferred evaluation of annotations (#2270)David Lordbefore adoption56db546
line 476why, one step back476 self, value: t.Any, param: Parameter | None, ctx: Context | NoneBump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 477–492why, one step back477 ) -> 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,enable deferred evaluation of annotations (#2270)David Lordbefore adoption56db546
lines 493–494why, one step back493 min: float | None = None,494 max: float | None = None,Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 495–504why, one step back495 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 = clamp504enable deferred evaluation of annotations (#2270)David Lordbefore adoption56db546
line 505why, one step back505 def to_info_dict(self) -> dict[str, t.Any]:Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 506–516why, one step back506 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(enable deferred evaluation of annotations (#2270)David Lordbefore adoption56db546
line 517why, one step back517 self, value: t.Any, param: Parameter | None, ctx: Context | NoneBump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 518–546why, one step back518 ) -> 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 rv546enable deferred evaluation of annotations (#2270)David Lordbefore adoption56db546
line 547why, one step back547 def _clamp(self, bound: float, dir: t.Literal[1, -1], open: bool) -> float:Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 548–601why, one step back548 """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: ignoreenable deferred evaluation of annotations (#2270)David Lordbefore adoption56db546
line 602why, one step back602 self, bound: int, dir: t.Literal[1, -1], open: boolBump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 603–637why, one step back603 ) -> 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,enable deferred evaluation of annotations (#2270)David Lordbefore adoption56db546
lines 638–639why, one step back638 min: float | None = None,639 max: float | None = None,Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 640–650why, one step back640 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.")650enable deferred evaluation of annotations (#2270)David Lordbefore adoption56db546
line 651why, one step back651 def _clamp(self, bound: float, dir: t.Literal[1, -1], open: bool) -> float:Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 652–654why, one step back652 if not open:653 return bound654drop end of life python versions (#2893)David Lordbefore adoption498f882
line 655why, one step back655 # Could use math.nextafter here, but clamping anBump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 656–663why, one step back656 # 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"663Fix reconciliation of envvar with `default`, `flag_value` and `type` parameters for flag options (#2956)Kevin Deldyckebefore adoption565f36d
lines 664–680why, one step back664 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.Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
line 681why, one step back681Fix reconciliation of envvar with `default`, `flag_value` and `type` parameters for flag options (#2956)Kevin Deldyckebefore adoption565f36d
lines 682–683why, one step back682 Mapping is inspired by :py:attr:`configparser.ConfigParser.BOOLEAN_STATES`683 and extends it.Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
line 684why, one step back684Fix reconciliation of envvar with `default`, `flag_value` and `type` parameters for flag options (#2956)Kevin Deldyckebefore adoption565f36d
lines 685–687why, one step back685 .. caution::686 String values are lower-cased, as the ``str_to_bool`` comparison function687 below is case-insensitive.Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
line 688why, one step back688Fix reconciliation of envvar with `default`, `flag_value` and `type` parameters for flag options (#2956)Kevin Deldyckebefore adoption565f36d
lines 689–691why, one step back689 .. 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.Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
line 692why, one step back692Fix reconciliation of envvar with `default`, `flag_value` and `type` parameters for flag options (#2956)Kevin Deldyckebefore adoption565f36d
lines 693–724why, one step back693 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 normalizedBump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 725–733why, one step back725726 def __repr__(self) -> str:727 return "BOOL"728729730class UUIDParameterType(ParamType):731 name = "uuid"732733 def convert(enable deferred evaluation of annotations (#2270)David Lordbefore adoption56db546
line 734why, one step back734 self, value: t.Any, param: Parameter | None, ctx: Context | NoneBump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 735–772why, one step back735 ) -> 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.772Merge `stable` into `main`; Release 8.2.0 (#2873)Rowlando13before adoptionb7c0ab4
lines 773–776why, one step back773 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.Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 777–778why, one step back777778 See :ref:`file-args` for more information.Merge `stable` into `main`; Release 8.2.0 (#2873)Rowlando13before adoptionb7c0ab4
lines 779–781why, one step back779780 .. versionchanged:: 2.0781 Added the ``atomic`` parameter.Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 782–784why, one step back782 """783784 name = "filename"Merge branch '8.1.x'David Lordbefore adoptiond9af5cf
line 785why, one step back785 envvar_list_splitter: t.ClassVar[str] = os.path.pathsepBump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 786–789why, one step back786787 def __init__(788 self,789 mode: str = "r",enable deferred evaluation of annotations (#2270)David Lordbefore adoption56db546
lines 790–792why, one step back790 encoding: str | None = None,791 errors: str | None = "strict",792 lazy: bool | None = None,Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 793–800why, one step back793 atomic: bool = False,794 ) -> None:795 self.mode = mode796 self.encoding = encoding797 self.errors = errors798 self.lazy = lazy799 self.atomic = atomic800enable deferred evaluation of annotations (#2270)David Lordbefore adoption56db546
line 801why, one step back801 def to_info_dict(self) -> dict[str, t.Any]:Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 802–805why, one step back802 info_dict = super().to_info_dict()803 info_dict.update(mode=self.mode, encoding=self.encoding)804 return info_dict805enable deferred evaluation of annotations (#2270)David Lordbefore adoption56db546
line 806why, one step back806 def resolve_lazy_flag(self, value: str | os.PathLike[str]) -> bool:Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 807–808why, one step back807 if self.lazy is not None:808 return self.lazyMerge branch '8.1.x'David Lordbefore adoptiond9af5cf
line 809why, one step back809 if os.fspath(value) == "-":Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 810–815why, one step back810 return False811 elif "w" in self.mode:812 return True813 return False814815 def convert(Merge branch '8.1.x'David Lordbefore adoptiond9af5cf
line 816why, one step back816 self,enable deferred evaluation of annotations (#2270)David Lordbefore adoption56db546
lines 817–819why, one step back817 value: str | os.PathLike[str] | t.IO[t.Any],818 param: Parameter | None,819 ctx: Context | None,Merge branch '8.1.x'David Lordbefore adoptiond9af5cf
lines 820–822why, one step back820 ) -> t.IO[t.Any]:821 if _is_file_like(value):822 return valueBump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
line 823why, one step back823enable deferred evaluation of annotations (#2270)David Lordbefore adoption56db546
line 824why, one step back824 value = t.cast("str | os.PathLike[str]", value)Merge branch '8.1.x'David Lordbefore adoptiond9af5cf
lines 825–826why, one step back825826 try:Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 827–836why, one step back827 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)836enable deferred evaluation of annotations (#2270)David Lordbefore adoption56db546
line 837why, one step back837 return t.cast("t.IO[t.Any]", lf)Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 838–854why, one step back838839 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 fuse ruff lint and format (#2658)David Lordbefore adoption1a3baf7
line 855why, one step back855 except OSError as e:Merge branch '8.1.x'David Lordbefore adoptiond9af5cf
line 856why, one step back856 self.fail(f"'{format_filename(value)}': {e.strerror}", param, ctx)Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 857–858why, one step back857858 def shell_complete(enable deferred evaluation of annotations (#2270)David Lordbefore adoption56db546
lines 859–860why, one step back859 self, ctx: Context, param: Parameter, incomplete: str860 ) -> list[CompletionItem]:Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 861–874why, one step back861 """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")]873874enable deferred evaluation of annotations (#2270)David Lordbefore adoption56db546
line 875why, one step back875def _is_file_like(value: t.Any) -> te.TypeGuard[t.IO[t.Any]]:Merge branch '8.1.x'David Lordbefore adoptiond9af5cf
lines 876–878why, one step back876 return hasattr(value, "read") or hasattr(value, "write")877878Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 879–911why, one step back879class 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 """911Merge branch '8.1.x'David Lordbefore adoptiond9af5cf
line 912why, one step back912 envvar_list_splitter: t.ClassVar[str] = os.path.pathsepBump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 913–922why, one step back913914 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,enable deferred evaluation of annotations (#2270)David Lordbefore adoption56db546
line 923why, one step back923 path_type: type[t.Any] | None = None,Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 924–936why, one step back924 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:Merge branch '8.1.x'David Lordbefore adoptiond9af5cf
line 937why, one step back937 self.name: str = _("file")Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 938–942why, one step back938 elif self.dir_okay and not self.file_okay:939 self.name = _("directory")940 else:941 self.name = _("path")942enable deferred evaluation of annotations (#2270)David Lordbefore adoption56db546
line 943why, one step back943 def to_info_dict(self) -> dict[str, t.Any]:Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 944–954why, one step back944 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_dict954Merge branch '8.1.x'David Lordbefore adoptiond9af5cf
line 955why, one step back955 def coerce_path_result(enable deferred evaluation of annotations (#2270)David Lordbefore adoption56db546
lines 956–957why, one step back956 self, value: str | os.PathLike[str]957 ) -> str | bytes | os.PathLike[str]:Merge branch '8.1.x'David Lordbefore adoptiond9af5cf
line 958why, one step back958 if self.type is not None and not isinstance(value, self.type):Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
line 959why, one step back959 if self.type is str:Merge branch '8.1.x'David Lordbefore adoptiond9af5cf
line 960why, one step back960 return os.fsdecode(value)Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
line 961why, one step back961 elif self.type is bytes:Merge branch '8.1.x'David Lordbefore adoptiond9af5cf
line 962why, one step back962 return os.fsencode(value)Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
line 963why, one step back963 else:Merge branch '8.1.x'David Lordbefore adoptiond9af5cf
line 964why, one step back964 return t.cast("os.PathLike[str]", self.type(value))Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
line 965why, one step back965Merge branch '8.1.x'David Lordbefore adoptiond9af5cf
line 966why, one step back966 return valueBump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 967–968why, one step back967968 def convert(Merge branch '8.1.x'David Lordbefore adoptiond9af5cf
line 969why, one step back969 self,enable deferred evaluation of annotations (#2270)David Lordbefore adoption56db546
lines 970–973why, one step back970 value: str | os.PathLike[str],971 param: Parameter | None,972 ctx: Context | None,973 ) -> str | bytes | os.PathLike[str]:Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 974–979why, one step back974 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:drop support for python 3.7 (#2588)David Lordbefore adoptionf5e47a6
line 980why, one step back980 rv = os.path.realpath(rv)Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 981–988why, one step back981982 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(Merge branch '8.1.x'David Lordbefore adoptiond9af5cf
line 989why, one step back989 name=self.name.title(), filename=format_filename(value)Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 990–997why, one step back990 ),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(Merge branch '8.1.x'David Lordbefore adoptiond9af5cf
line 998why, one step back998 name=self.name.title(), filename=format_filename(value)Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 999–1004why, one step back999 ),1000 param,1001 ctx,1002 )1003 if not self.dir_okay and stat.S_ISDIR(st.st_mode):1004 self.fail(Merge branch '8.1.x'David Lordbefore adoption99015e1
line 1005why, one step back1005 _("{name} {filename!r} is a directory.").format(Merge branch '8.1.x'David Lordbefore adoptiond9af5cf
line 1006why, one step back1006 name=self.name.title(), filename=format_filename(value)Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 1007–1014why, one step back1007 ),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(Merge branch '8.1.x'David Lordbefore adoptiond9af5cf
line 1015why, one step back1015 name=self.name.title(), filename=format_filename(value)Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 1016–1023why, one step back1016 ),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(Merge branch '8.1.x'David Lordbefore adoptiond9af5cf
line 1024why, one step back1024 name=self.name.title(), filename=format_filename(value)Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 1025–1032why, one step back1025 ),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(Merge branch '8.1.x'David Lordbefore adoptiond9af5cf
line 1033why, one step back1033 name=self.name.title(), filename=format_filename(value)Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 1034–1041why, one step back1034 ),1035 param,1036 ctx,1037 )10381039 return self.coerce_path_result(rv)10401041 def shell_complete(enable deferred evaluation of annotations (#2270)David Lordbefore adoption56db546
lines 1042–1043why, one step back1042 self, ctx: Context, param: Parameter, incomplete: str1043 ) -> list[CompletionItem]:Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 1044–1073why, one step back1044 """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 """1073enable deferred evaluation of annotations (#2270)David Lordbefore adoption56db546
lines 1074–1075why, one step back1074 def __init__(self, types: cabc.Sequence[type[t.Any] | ParamType]) -> None:1075 self.types: cabc.Sequence[ParamType] = [convert_type(ty) for ty in types]Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
line 1076why, one step back1076enable deferred evaluation of annotations (#2270)David Lordbefore adoption56db546
line 1077why, one step back1077 def to_info_dict(self) -> dict[str, t.Any]:Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 1078–1090why, one step back1078 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(enable deferred evaluation of annotations (#2270)David Lordbefore adoption56db546
line 1091why, one step back1091 self, value: t.Any, param: Parameter | None, ctx: Context | NoneBump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 1092–1106why, one step back1092 ) -> 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 )1106drop end of life python versions (#2893)David Lordbefore adoption498f882
lines 1107–1109why, one step back1107 return tuple(1108 ty(x, param, ctx) for ty, x in zip(self.types, value, strict=False)1109 )Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 1110–1111why, one step back11101111enable deferred evaluation of annotations (#2270)David Lordbefore adoption56db546
line 1112why, one step back1112def convert_type(ty: t.Any | None, default: t.Any | None = None) -> ParamType:Bump dessant/lock-threads from 4.0.0 to 4.0.1 (#2546)David Lordbefore adoption43d37ff
lines 1113–1202why, one step back1113 """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()Split generation of help extra items and rendering (#2517)Kevin Deldyckebefore adoption948d7a7
lines 1203–1209why, one step back120312041205class OptionHelpExtra(t.TypedDict, total=False):1206 envvars: tuple[str, ...]1207 default: str1208 range: str1209 required: str