| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import collections.abc as cabc |
| 4 |
import enum |
| 5 |
import os |
| 6 |
import stat |
| 7 |
import sys |
| 8 |
import typing as t |
| 9 |
from datetime import datetime |
| 10 |
from gettext import gettext as _ |
| 11 |
from gettext import ngettext |
| 12 |
|
| 13 |
from ._compat import _get_argv_encoding |
| 14 |
from ._compat import open_stream |
| 15 |
from .exceptions import BadParameter |
| 16 |
from .utils import format_filename |
| 17 |
from .utils import LazyFile |
| 18 |
from .utils import safecall |
| 19 |
|
| 20 |
if t.TYPE_CHECKING: |
| 21 |
import typing_extensions as te |
| 22 |
|
| 23 |
from .core import Context |
| 24 |
from .core import Parameter |
| 25 |
from .shell_completion import CompletionItem |
| 26 |
|
| 27 |
ParamTypeValue = t.TypeVar("ParamTypeValue") |
| 28 |
|
| 29 |
|
| 30 |
class ParamType: |
| 31 |
"""Represents the type of a parameter. Validates and converts values |
| 32 |
from the command line or Python into the correct type. |
| 33 |
|
| 34 |
To implement a custom type, subclass and implement at least the |
| 35 |
following: |
| 36 |
|
| 37 |
- The :attr:`name` class attribute must be set. |
| 38 |
- Calling an instance of the type with ``None`` must return |
| 39 |
``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 correct |
| 42 |
type. |
| 43 |
- It must be able to convert a value if the ``ctx`` and ``param`` |
| 44 |
arguments are ``None``. This can occur when converting prompt |
| 45 |
input. |
| 46 |
""" |
| 47 |
|
| 48 |
is_composite: t.ClassVar[bool] = False |
| 49 |
arity: t.ClassVar[int] = 1 |
| 50 |
|
| 51 |
#: the descriptive name of this type |
| 52 |
name: str |
| 53 |
|
| 54 |
#: if a list of this type is expected and the value is pulled from a |
| 55 |
#: string environment variable, this is what splits it up. `None` |
| 56 |
#: means any whitespace. For all parameters the general rule is that |
| 57 |
#: whitespace splits them up. The exception are paths and files which |
| 58 |
#: are split by ``os.path.pathsep`` by default (":" on Unix and ";" on |
| 59 |
#: Windows). |
| 60 |
envvar_list_splitter: t.ClassVar[str | None] = None |
| 61 |
|
| 62 |
async def to_info_dict(self) -> dict[str, t.Any]: |
| 63 |
"""Gather information that could be useful for a tool generating |
| 64 |
user-facing documentation. |
| 65 |
|
| 66 |
Use :meth:`click.Context.to_info_dict` to traverse the entire |
| 67 |
CLI structure. |
| 68 |
|
| 69 |
.. versionadded:: 8.0 |
| 70 |
""" |
| 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] |
| 74 |
|
| 75 |
# Custom subclasses might not remember to set a name. |
| 76 |
if hasattr(self, "name"): |
| 77 |
name = self.name |
| 78 |
else: |
| 79 |
name = param_type |
| 80 |
|
| 81 |
return {"param_type": param_type, "name": name} |
| 82 |
|
| 83 |
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) |
| 91 |
|
| 92 |
def get_metavar(self, param: Parameter, ctx: Context) -> str | None: |
| 93 |
"""Returns the metavar default for this param if it provides one.""" |
| 94 |
|
| 95 |
def get_missing_message(self, param: Parameter, ctx: Context | None) -> str | None: |
| 96 |
"""Optionally might return extra information about a missing |
| 97 |
parameter. |
| 98 |
|
| 99 |
.. versionadded:: 2.0 |
| 100 |
""" |
| 101 |
|
| 102 |
def convert( |
| 103 |
self, value: t.Any, param: Parameter | None, ctx: Context | None |
| 104 |
) -> t.Any: |
| 105 |
"""Convert the value to the correct type. This is not called if |
| 106 |
the value is ``None`` (the missing value). |
| 107 |
|
| 108 |
This must accept string values from the command line, as well as |
| 109 |
values that are already the correct type. It may also convert |
| 110 |
other compatible types. |
| 111 |
|
| 112 |
The ``param`` and ``ctx`` arguments may be ``None`` in certain |
| 113 |
situations, such as when converting prompt input. |
| 114 |
|
| 115 |
If the value cannot be converted, call :meth:`fail` with a |
| 116 |
descriptive message. |
| 117 |
|
| 118 |
:param value: The value to convert. |
| 119 |
:param param: The parameter that is using this type to convert |
| 120 |
its value. May be ``None``. |
| 121 |
:param ctx: The current context that arrived at this value. May |
| 122 |
be ``None``. |
| 123 |
""" |
| 124 |
return value |
| 125 |
|
| 126 |
def split_envvar_value(self, rv: str) -> cabc.Sequence[str]: |
| 127 |
"""Given a value from an environment variable this splits it up |
| 128 |
into small chunks depending on the defined envvar list splitter. |
| 129 |
|
| 130 |
If the splitter is set to `None`, which means that whitespace splits, |
| 131 |
then leading and trailing whitespace is ignored. Otherwise, leading |
| 132 |
and trailing splitters usually lead to empty items being included. |
| 133 |
""" |
| 134 |
return (rv or "").split(self.envvar_list_splitter) |
| 135 |
|
| 136 |
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) |
| 144 |
|
| 145 |
def shell_complete( |
| 146 |
self, ctx: Context, param: Parameter, incomplete: str |
| 147 |
) -> list[CompletionItem]: |
| 148 |
"""Return a list of |
| 149 |
:class:`~click.shell_completion.CompletionItem` objects for the |
| 150 |
incomplete value. Most types do not provide completions, but |
| 151 |
some do, and this allows custom types to provide custom |
| 152 |
completions as well. |
| 153 |
|
| 154 |
: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. |
| 157 |
|
| 158 |
.. versionadded:: 8.0 |
| 159 |
""" |
| 160 |
return [] |
| 161 |
|
| 162 |
|
| 163 |
class CompositeParamType(ParamType): |
| 164 |
is_composite = True |
| 165 |
|
| 166 |
@property |
| 167 |
def arity(self) -> int: # type: ignore |
| 168 |
raise NotImplementedError() |
| 169 |
|
| 170 |
|
| 171 |
class FuncParamType(ParamType): |
| 172 |
def __init__(self, func: t.Callable[[t.Any], t.Any]) -> None: |
| 173 |
self.name: str = func.__name__ |
| 174 |
self.func = func |
| 175 |
|
| 176 |
async def to_info_dict(self) -> dict[str, t.Any]: |
| 177 |
info_dict = await super().to_info_dict() |
| 178 |
info_dict["func"] = self.func |
| 179 |
return info_dict |
| 180 |
|
| 181 |
def convert( |
| 182 |
self, value: t.Any, param: Parameter | None, ctx: Context | None |
| 183 |
) -> 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") |
| 191 |
|
| 192 |
self.fail(value, param, ctx) |
| 193 |
|
| 194 |
|
| 195 |
class UnprocessedParamType(ParamType): |
| 196 |
name = "text" |
| 197 |
|
| 198 |
def convert( |
| 199 |
self, value: t.Any, param: Parameter | None, ctx: Context | None |
| 200 |
) -> t.Any: |
| 201 |
return value |
| 202 |
|
| 203 |
def __repr__(self) -> str: |
| 204 |
return "UNPROCESSED" |
| 205 |
|
| 206 |
|
| 207 |
class StringParamType(ParamType): |
| 208 |
name = "text" |
| 209 |
|
| 210 |
def convert( |
| 211 |
self, value: t.Any, param: Parameter | None, ctx: Context | None |
| 212 |
) -> 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 value |
| 227 |
return str(value) |
| 228 |
|
| 229 |
def __repr__(self) -> str: |
| 230 |
return "STRING" |
| 231 |
|
| 232 |
|
| 233 |
class Choice(ParamType, t.Generic[ParamTypeValue]): |
| 234 |
"""The choice type allows a value to be checked against a fixed set |
| 235 |
of supported values. |
| 236 |
|
| 237 |
You may pass any iterable value which will be converted to a tuple |
| 238 |
and thus will only be iterated once. |
| 239 |
|
| 240 |
The resulting value will always be one of the originally passed choices. |
| 241 |
See :meth:`normalize_choice` for more info on the mapping of strings |
| 242 |
to choices. See :ref:`choice-opts` for an example. |
| 243 |
|
| 244 |
:param case_sensitive: Set to false to make choices case |
| 245 |
insensitive. Defaults to true. |
| 246 |
|
| 247 |
.. versionchanged:: 8.2.0 |
| 248 |
Non-``str`` ``choices`` are now supported. It can additionally be any |
| 249 |
iterable. Before you were not recommended to pass anything but a list or |
| 250 |
tuple. |
| 251 |
|
| 252 |
.. versionadded:: 8.2.0 |
| 253 |
Choice normalization can be overridden via :meth:`normalize_choice`. |
| 254 |
""" |
| 255 |
|
| 256 |
name = "choice" |
| 257 |
|
| 258 |
def __init__( |
| 259 |
self, choices: cabc.Iterable[ParamTypeValue], case_sensitive: bool = True |
| 260 |
) -> None: |
| 261 |
self.choices: cabc.Sequence[ParamTypeValue] = tuple(choices) |
| 262 |
self.case_sensitive = case_sensitive |
| 263 |
|
| 264 |
async def to_info_dict(self) -> dict[str, t.Any]: |
| 265 |
info_dict = await super().to_info_dict() |
| 266 |
info_dict["choices"] = self.choices |
| 267 |
info_dict["case_sensitive"] = self.case_sensitive |
| 268 |
return info_dict |
| 269 |
|
| 270 |
def _normalized_mapping( |
| 271 |
self, ctx: Context | None = None |
| 272 |
) -> cabc.Mapping[ParamTypeValue, str]: |
| 273 |
""" |
| 274 |
Returns mapping where keys are the original choices and the values are |
| 275 |
the normalized values that are accepted via the command line. |
| 276 |
|
| 277 |
This is a simple wrapper around :meth:`normalize_choice`, use that |
| 278 |
instead which is supported. |
| 279 |
""" |
| 280 |
return { |
| 281 |
choice: self.normalize_choice( |
| 282 |
choice=choice, |
| 283 |
ctx=ctx, |
| 284 |
) |
| 285 |
for choice in self.choices |
| 286 |
} |
| 287 |
|
| 288 |
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. |
| 292 |
|
| 293 |
By default uses :meth:`Context.token_normalize_func` and if not case |
| 294 |
sensitive, convert it to a casefolded value. |
| 295 |
|
| 296 |
.. versionadded:: 8.2.0 |
| 297 |
""" |
| 298 |
normed_value = choice.name if isinstance(choice, enum.Enum) else str(choice) |
| 299 |
|
| 300 |
if ctx is not None and ctx.token_normalize_func is not None: |
| 301 |
normed_value = ctx.token_normalize_func(normed_value) |
| 302 |
|
| 303 |
if not self.case_sensitive: |
| 304 |
normed_value = normed_value.casefold() |
| 305 |
|
| 306 |
return normed_value |
| 307 |
|
| 308 |
def get_metavar(self, param: Parameter, ctx: Context) -> str | None: |
| 309 |
if param.param_type_name == "option" and not param.show_choices: # type: ignore |
| 310 |
choice_metavars = [ |
| 311 |
convert_type(type(choice)).name.upper() for choice in self.choices |
| 312 |
] |
| 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 |
) |
| 318 |
|
| 319 |
# Use curly braces to indicate a required argument. |
| 320 |
if param.required and param.param_type_name == "argument": |
| 321 |
return f"{{{choices_str}}}" |
| 322 |
|
| 323 |
# Use square braces to indicate an option or optional argument. |
| 324 |
return f"[{choices_str}]" |
| 325 |
|
| 326 |
def get_missing_message(self, param: Parameter, ctx: Context | None) -> str: |
| 327 |
""" |
| 328 |
Message shown when no choice is passed. |
| 329 |
|
| 330 |
.. 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 |
) |
| 335 |
|
| 336 |
def convert( |
| 337 |
self, value: t.Any, param: Parameter | None, ctx: Context | None |
| 338 |
) -> ParamTypeValue: |
| 339 |
""" |
| 340 |
For a given value from the parser, normalize it and find its |
| 341 |
matching normalized value in the list of choices. Then return the |
| 342 |
matched "original" choice. |
| 343 |
""" |
| 344 |
normed_value = self.normalize_choice(choice=value, ctx=ctx) |
| 345 |
normalized_mapping = self._normalized_mapping(ctx=ctx) |
| 346 |
|
| 347 |
try: |
| 348 |
return next( |
| 349 |
original |
| 350 |
for original, normalized in normalized_mapping.items() |
| 351 |
if normalized == normed_value |
| 352 |
) |
| 353 |
except StopIteration: |
| 354 |
self.fail( |
| 355 |
self.get_invalid_choice_message(value=value, ctx=ctx), |
| 356 |
param=param, |
| 357 |
ctx=ctx, |
| 358 |
) |
| 359 |
|
| 360 |
def get_invalid_choice_message(self, value: t.Any, ctx: Context | None) -> str: |
| 361 |
"""Get the error message when the given choice is invalid. |
| 362 |
|
| 363 |
:param value: The invalid value. |
| 364 |
|
| 365 |
.. versionadded:: 8.2 |
| 366 |
""" |
| 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) |
| 373 |
|
| 374 |
def __repr__(self) -> str: |
| 375 |
return f"Choice({list(self.choices)})" |
| 376 |
|
| 377 |
def shell_complete( |
| 378 |
self, ctx: Context, param: Parameter, incomplete: str |
| 379 |
) -> list[CompletionItem]: |
| 380 |
"""Complete choices that start with the incomplete value. |
| 381 |
|
| 382 |
: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. |
| 385 |
|
| 386 |
.. versionadded:: 8.0 |
| 387 |
""" |
| 388 |
from .shell_completion import CompletionItem |
| 389 |
|
| 390 |
str_choices = map(str, self.choices) |
| 391 |
|
| 392 |
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)) |
| 397 |
|
| 398 |
return [CompletionItem(c) for c in matched] |
| 399 |
|
| 400 |
|
| 401 |
class DateTime(ParamType): |
| 402 |
"""The DateTime type converts date strings into `datetime` objects. |
| 403 |
|
| 404 |
The format strings which are checked are configurable, but default to some |
| 405 |
common (non-timezone aware) ISO 8601 formats. |
| 406 |
|
| 407 |
When specifying *DateTime* formats, you should only pass a list or a tuple. |
| 408 |
Other iterables, like generators, may lead to surprising results. |
| 409 |
|
| 410 |
The format strings are processed using ``datetime.strptime``, and this |
| 411 |
consequently defines the format strings which are allowed. |
| 412 |
|
| 413 |
Parsing is tried using each format, in order, and the first format which |
| 414 |
parses successfully is used. |
| 415 |
|
| 416 |
:param formats: A list or tuple of date format strings, in the order in |
| 417 |
which they should be tried. Defaults to |
| 418 |
``'%Y-%m-%d'``, ``'%Y-%m-%dT%H:%M:%S'``, |
| 419 |
``'%Y-%m-%d %H:%M:%S'``. |
| 420 |
""" |
| 421 |
|
| 422 |
name = "datetime" |
| 423 |
|
| 424 |
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 |
] |
| 430 |
|
| 431 |
async def to_info_dict(self) -> dict[str, t.Any]: |
| 432 |
info_dict = await super().to_info_dict() |
| 433 |
info_dict["formats"] = self.formats |
| 434 |
return info_dict |
| 435 |
|
| 436 |
def get_metavar(self, param: Parameter, ctx: Context) -> str | None: |
| 437 |
return f"[{'|'.join(self.formats)}]" |
| 438 |
|
| 439 |
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 None |
| 444 |
|
| 445 |
def convert( |
| 446 |
self, value: t.Any, param: Parameter | None, ctx: Context | None |
| 447 |
) -> t.Any: |
| 448 |
if isinstance(value, datetime): |
| 449 |
return value |
| 450 |
|
| 451 |
for format in self.formats: |
| 452 |
converted = self._try_to_convert_date(value, format) |
| 453 |
|
| 454 |
if converted is not None: |
| 455 |
return converted |
| 456 |
|
| 457 |
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 |
) |
| 467 |
|
| 468 |
def __repr__(self) -> str: |
| 469 |
return "DateTime" |
| 470 |
|
| 471 |
|
| 472 |
class _NumberParamTypeBase(ParamType): |
| 473 |
_number_class: t.ClassVar[type[t.Any]] |
| 474 |
|
| 475 |
def convert( |
| 476 |
self, value: t.Any, param: Parameter | None, ctx: Context | None |
| 477 |
) -> 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.name |
| 484 |
), |
| 485 |
param, |
| 486 |
ctx, |
| 487 |
) |
| 488 |
|
| 489 |
|
| 490 |
class _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 = min |
| 500 |
self.max = max |
| 501 |
self.min_open = min_open |
| 502 |
self.max_open = max_open |
| 503 |
self.clamp = clamp |
| 504 |
|
| 505 |
async def to_info_dict(self) -> dict[str, t.Any]: |
| 506 |
info_dict = await 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_dict |
| 515 |
|
| 516 |
def convert( |
| 517 |
self, value: t.Any, param: Parameter | None, ctx: Context | None |
| 518 |
) -> t.Any: |
| 519 |
import operator |
| 520 |
|
| 521 |
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.lt |
| 524 |
)(rv, self.min) |
| 525 |
gt_max: bool = self.max is not None and ( |
| 526 |
operator.ge if self.max_open else operator.gt |
| 527 |
)(rv, self.max) |
| 528 |
|
| 529 |
if self.clamp: |
| 530 |
if lt_min: |
| 531 |
return self._clamp(self.min, 1, self.min_open) # type: ignore |
| 532 |
|
| 533 |
if gt_max: |
| 534 |
return self._clamp(self.max, -1, self.max_open) # type: ignore |
| 535 |
|
| 536 |
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 |
) |
| 544 |
|
| 545 |
return rv |
| 546 |
|
| 547 |
def _clamp(self, bound: float, dir: t.Literal[1, -1], open: bool) -> float: |
| 548 |
"""Find the valid value to clamp to bound in the given |
| 549 |
direction. |
| 550 |
|
| 551 |
: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 NotImplementedError |
| 556 |
|
| 557 |
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}" |
| 562 |
|
| 563 |
if self.max is None: |
| 564 |
op = ">" if self.min_open else ">=" |
| 565 |
return f"x{op}{self.min}" |
| 566 |
|
| 567 |
lop = "<" if self.min_open else "<=" |
| 568 |
rop = "<" if self.max_open else "<=" |
| 569 |
return f"{self.min}{lop}x{rop}{self.max}" |
| 570 |
|
| 571 |
def __repr__(self) -> str: |
| 572 |
clamp = " clamped" if self.clamp else "" |
| 573 |
return f"<{type(self).__name__} {self._describe_range()}{clamp}>" |
| 574 |
|
| 575 |
|
| 576 |
class IntParamType(_NumberParamTypeBase): |
| 577 |
name = "integer" |
| 578 |
_number_class = int |
| 579 |
|
| 580 |
def __repr__(self) -> str: |
| 581 |
return "INT" |
| 582 |
|
| 583 |
|
| 584 |
class IntRange(_NumberRangeBase, IntParamType): |
| 585 |
"""Restrict an :data:`click.INT` value to a range of accepted |
| 586 |
values. See :ref:`ranges`. |
| 587 |
|
| 588 |
If ``min`` or ``max`` are not passed, any value is accepted in that |
| 589 |
direction. If ``min_open`` or ``max_open`` are enabled, the |
| 590 |
corresponding boundary is not included in the range. |
| 591 |
|
| 592 |
If ``clamp`` is enabled, a value outside the range is clamped to the |
| 593 |
boundary instead of failing. |
| 594 |
|
| 595 |
.. versionchanged:: 8.0 |
| 596 |
Added the ``min_open`` and ``max_open`` parameters. |
| 597 |
""" |
| 598 |
|
| 599 |
name = "integer range" |
| 600 |
|
| 601 |
def _clamp( # type: ignore |
| 602 |
self, bound: int, dir: t.Literal[1, -1], open: bool |
| 603 |
) -> int: |
| 604 |
if not open: |
| 605 |
return bound |
| 606 |
|
| 607 |
return bound + dir |
| 608 |
|
| 609 |
|
| 610 |
class FloatParamType(_NumberParamTypeBase): |
| 611 |
name = "float" |
| 612 |
_number_class = float |
| 613 |
|
| 614 |
def __repr__(self) -> str: |
| 615 |
return "FLOAT" |
| 616 |
|
| 617 |
|
| 618 |
class FloatRange(_NumberRangeBase, FloatParamType): |
| 619 |
"""Restrict a :data:`click.FLOAT` value to a range of accepted |
| 620 |
values. See :ref:`ranges`. |
| 621 |
|
| 622 |
If ``min`` or ``max`` are not passed, any value is accepted in that |
| 623 |
direction. If ``min_open`` or ``max_open`` are enabled, the |
| 624 |
corresponding boundary is not included in the range. |
| 625 |
|
| 626 |
If ``clamp`` is enabled, a value outside the range is clamped to the |
| 627 |
boundary instead of failing. This is not supported if either |
| 628 |
boundary is marked ``open``. |
| 629 |
|
| 630 |
.. versionchanged:: 8.0 |
| 631 |
Added the ``min_open`` and ``max_open`` parameters. |
| 632 |
""" |
| 633 |
|
| 634 |
name = "float range" |
| 635 |
|
| 636 |
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=clamp |
| 646 |
) |
| 647 |
|
| 648 |
if (min_open or max_open) and clamp: |
| 649 |
raise TypeError("Clamping is not supported for open bounds.") |
| 650 |
|
| 651 |
def _clamp(self, bound: float, dir: t.Literal[1, -1], open: bool) -> float: |
| 652 |
if not open: |
| 653 |
return bound |
| 654 |
|
| 655 |
# Could use math.nextafter here, but clamping an |
| 656 |
# open float range doesn't seem to be particularly useful. It's |
| 657 |
# left up to the user to write a callback to do it if needed. |
| 658 |
raise RuntimeError("Clamping is not supported for open bounds.") |
| 659 |
|
| 660 |
|
| 661 |
class BoolParamType(ParamType): |
| 662 |
name = "boolean" |
| 663 |
|
| 664 |
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. |
| 681 |
|
| 682 |
Mapping is inspired by :py:attr:`configparser.ConfigParser.BOOLEAN_STATES` |
| 683 |
and extends it. |
| 684 |
|
| 685 |
.. caution:: |
| 686 |
String values are lower-cased, as the ``str_to_bool`` comparison function |
| 687 |
below is case-insensitive. |
| 688 |
|
| 689 |
.. warning:: |
| 690 |
The mapping is not exhaustive, and does not cover all possible boolean strings |
| 691 |
representations. It will remains as it is to avoid endless bikeshedding. |
| 692 |
|
| 693 |
Future work my be considered to make this mapping user-configurable from public |
| 694 |
API. |
| 695 |
""" |
| 696 |
|
| 697 |
@staticmethod |
| 698 |
def str_to_bool(value: str | bool) -> bool | None: |
| 699 |
"""Convert a string to a boolean value. |
| 700 |
|
| 701 |
If the value is already a boolean, it is returned as-is. If the value is a |
| 702 |
string, it is stripped of whitespaces and lower-cased, then checked against |
| 703 |
the known boolean states pre-defined in the `BoolParamType.bool_states` mapping |
| 704 |
above. |
| 705 |
|
| 706 |
Returns `None` if the value does not match any known boolean state. |
| 707 |
""" |
| 708 |
if isinstance(value, bool): |
| 709 |
return value |
| 710 |
return BoolParamType.bool_states.get(value.strip().lower()) |
| 711 |
|
| 712 |
def convert( |
| 713 |
self, value: t.Any, param: Parameter | None, ctx: Context | None |
| 714 |
) -> 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 normalized |
| 725 |
|
| 726 |
def __repr__(self) -> str: |
| 727 |
return "BOOL" |
| 728 |
|
| 729 |
|
| 730 |
class UUIDParameterType(ParamType): |
| 731 |
name = "uuid" |
| 732 |
|
| 733 |
def convert( |
| 734 |
self, value: t.Any, param: Parameter | None, ctx: Context | None |
| 735 |
) -> t.Any: |
| 736 |
import uuid |
| 737 |
|
| 738 |
if isinstance(value, uuid.UUID): |
| 739 |
return value |
| 740 |
|
| 741 |
value = value.strip() |
| 742 |
|
| 743 |
try: |
| 744 |
return uuid.UUID(value) |
| 745 |
except ValueError: |
| 746 |
self.fail( |
| 747 |
_("{value!r} is not a valid UUID.").format(value=value), param, ctx |
| 748 |
) |
| 749 |
|
| 750 |
def __repr__(self) -> str: |
| 751 |
return "UUID" |
| 752 |
|
| 753 |
|
| 754 |
class File(ParamType): |
| 755 |
"""Declares a parameter to be a file for reading or writing. The file |
| 756 |
is automatically closed once the context tears down (after the command |
| 757 |
finished working). |
| 758 |
|
| 759 |
Files can be opened for reading or writing. The special value ``-`` |
| 760 |
indicates stdin or stdout depending on the mode. |
| 761 |
|
| 762 |
By default, the file is opened for reading text data, but it can also be |
| 763 |
opened in binary mode or for writing. The encoding parameter can be used |
| 764 |
to force a specific encoding. |
| 765 |
|
| 766 |
The `lazy` flag controls if the file should be opened immediately or upon |
| 767 |
first IO. The default is to be non-lazy for standard input and output |
| 768 |
streams as well as files opened for reading, `lazy` otherwise. When opening a |
| 769 |
file lazily for reading, it is still opened temporarily for validation, but |
| 770 |
will not be held open until first IO. lazy is mainly useful when opening |
| 771 |
for writing to avoid creating the file until it is needed. |
| 772 |
|
| 773 |
Files can also be opened atomically in which case all writes go into a |
| 774 |
separate file in the same folder and upon completion the file will |
| 775 |
be moved over to the original location. This is useful if a file |
| 776 |
regularly read by other users is modified. |
| 777 |
|
| 778 |
See :ref:`file-args` for more information. |
| 779 |
|
| 780 |
.. versionchanged:: 2.0 |
| 781 |
Added the ``atomic`` parameter. |
| 782 |
""" |
| 783 |
|
| 784 |
name = "filename" |
| 785 |
envvar_list_splitter: t.ClassVar[str] = os.path.pathsep |
| 786 |
|
| 787 |
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 = mode |
| 796 |
self.encoding = encoding |
| 797 |
self.errors = errors |
| 798 |
self.lazy = lazy |
| 799 |
self.atomic = atomic |
| 800 |
|
| 801 |
async def to_info_dict(self) -> dict[str, t.Any]: |
| 802 |
info_dict = await super().to_info_dict() |
| 803 |
info_dict.update(mode=self.mode, encoding=self.encoding) |
| 804 |
return info_dict |
| 805 |
|
| 806 |
def resolve_lazy_flag(self, value: str | os.PathLike[str]) -> bool: |
| 807 |
if self.lazy is not None: |
| 808 |
return self.lazy |
| 809 |
if os.fspath(value) == "-": |
| 810 |
return False |
| 811 |
elif "w" in self.mode: |
| 812 |
return True |
| 813 |
return False |
| 814 |
|
| 815 |
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 value |
| 823 |
|
| 824 |
value = t.cast("str | os.PathLike[str]", value) |
| 825 |
|
| 826 |
try: |
| 827 |
lazy = self.resolve_lazy_flag(value) |
| 828 |
|
| 829 |
if lazy: |
| 830 |
lf = LazyFile( |
| 831 |
value, self.mode, self.encoding, self.errors, atomic=self.atomic |
| 832 |
) |
| 833 |
|
| 834 |
if ctx is not None: |
| 835 |
ctx.call_on_close(lf.close_intelligently) |
| 836 |
|
| 837 |
return t.cast("t.IO[t.Any]", lf) |
| 838 |
|
| 839 |
f, should_close = open_stream( |
| 840 |
value, self.mode, self.encoding, self.errors, atomic=self.atomic |
| 841 |
) |
| 842 |
|
| 843 |
# If a context is provided, we automatically close the file |
| 844 |
# at the end of the context execution (or flush out). If a |
| 845 |
# context does not exist, it's the caller's responsibility to |
| 846 |
# properly close the file. This for instance happens when the |
| 847 |
# 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)) |
| 853 |
|
| 854 |
return f |
| 855 |
except OSError as e: |
| 856 |
self.fail(f"'{format_filename(value)}': {e.strerror}", param, ctx) |
| 857 |
|
| 858 |
def shell_complete( |
| 859 |
self, ctx: Context, param: Parameter, incomplete: str |
| 860 |
) -> list[CompletionItem]: |
| 861 |
"""Return a special completion marker that tells the completion |
| 862 |
system to use the shell to provide file path completions. |
| 863 |
|
| 864 |
: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. |
| 867 |
|
| 868 |
.. versionadded:: 8.0 |
| 869 |
""" |
| 870 |
from .shell_completion import CompletionItem |
| 871 |
|
| 872 |
return [CompletionItem(incomplete, type="file")] |
| 873 |
|
| 874 |
|
| 875 |
def _is_file_like(value: t.Any) -> te.TypeGuard[t.IO[t.Any]]: |
| 876 |
return hasattr(value, "read") or hasattr(value, "write") |
| 877 |
|
| 878 |
|
| 879 |
class Path(ParamType): |
| 880 |
"""The ``Path`` type is similar to the :class:`File` type, but |
| 881 |
returns the filename instead of an open file. Various checks can be |
| 882 |
enabled to validate the type of file and permissions. |
| 883 |
|
| 884 |
:param exists: The file or directory needs to exist for the value to |
| 885 |
be valid. If this is not set to ``True``, and the file does not |
| 886 |
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 any |
| 893 |
symlinks. A ``~`` is not expanded, as this is supposed to be |
| 894 |
done by the shell only. |
| 895 |
:param allow_dash: Allow a single dash as a value, which indicates |
| 896 |
a standard stream (but does not open it). Use |
| 897 |
:func:`~click.open_file` to handle opening this value. |
| 898 |
:param path_type: Convert the incoming path value to this type. If |
| 899 |
``None``, keep Python's default, which is ``str``. Useful to |
| 900 |
convert to :class:`pathlib.Path`. |
| 901 |
|
| 902 |
.. versionchanged:: 8.1 |
| 903 |
Added the ``executable`` parameter. |
| 904 |
|
| 905 |
.. versionchanged:: 8.0 |
| 906 |
Allow passing ``path_type=pathlib.Path``. |
| 907 |
|
| 908 |
.. versionchanged:: 6.0 |
| 909 |
Added the ``allow_dash`` parameter. |
| 910 |
""" |
| 911 |
|
| 912 |
envvar_list_splitter: t.ClassVar[str] = os.path.pathsep |
| 913 |
|
| 914 |
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 = exists |
| 927 |
self.file_okay = file_okay |
| 928 |
self.dir_okay = dir_okay |
| 929 |
self.readable = readable |
| 930 |
self.writable = writable |
| 931 |
self.executable = executable |
| 932 |
self.resolve_path = resolve_path |
| 933 |
self.allow_dash = allow_dash |
| 934 |
self.type = path_type |
| 935 |
|
| 936 |
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") |
| 942 |
|
| 943 |
async def to_info_dict(self) -> dict[str, t.Any]: |
| 944 |
info_dict = await 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_dict |
| 954 |
|
| 955 |
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)) |
| 965 |
|
| 966 |
return value |
| 967 |
|
| 968 |
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 = value |
| 975 |
|
| 976 |
is_dash = self.file_okay and self.allow_dash and rv in (b"-", "-") |
| 977 |
|
| 978 |
if not is_dash: |
| 979 |
if self.resolve_path: |
| 980 |
rv = os.path.realpath(rv) |
| 981 |
|
| 982 |
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 |
) |
| 994 |
|
| 995 |
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 |
) |
| 1011 |
|
| 1012 |
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 |
) |
| 1020 |
|
| 1021 |
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 |
) |
| 1029 |
|
| 1030 |
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 |
) |
| 1038 |
|
| 1039 |
return self.coerce_path_result(rv) |
| 1040 |
|
| 1041 |
def shell_complete( |
| 1042 |
self, ctx: Context, param: Parameter, incomplete: str |
| 1043 |
) -> list[CompletionItem]: |
| 1044 |
"""Return a special completion marker that tells the completion |
| 1045 |
system to use the shell to provide path completions for only |
| 1046 |
directories or any paths. |
| 1047 |
|
| 1048 |
: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. |
| 1051 |
|
| 1052 |
.. versionadded:: 8.0 |
| 1053 |
""" |
| 1054 |
from .shell_completion import CompletionItem |
| 1055 |
|
| 1056 |
type = "dir" if self.dir_okay and not self.file_okay else "file" |
| 1057 |
return [CompletionItem(incomplete, type=type)] |
| 1058 |
|
| 1059 |
|
| 1060 |
class 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 fixed |
| 1063 |
count and different types should be used for different items. In this |
| 1064 |
case the :class:`Tuple` type can be used. This type can only be used |
| 1065 |
if `nargs` is set to a fixed number. |
| 1066 |
|
| 1067 |
For more information see :ref:`tuple-type`. |
| 1068 |
|
| 1069 |
This can be selected by using a Python tuple literal as a type. |
| 1070 |
|
| 1071 |
:param types: a list of types that should be used for the tuple items. |
| 1072 |
""" |
| 1073 |
|
| 1074 |
def __init__(self, types: cabc.Sequence[type[t.Any] | ParamType]) -> None: |
| 1075 |
self.types: cabc.Sequence[ParamType] = [convert_type(ty) for ty in types] |
| 1076 |
|
| 1077 |
async def to_info_dict(self) -> dict[str, t.Any]: |
| 1078 |
info_dict = await super().to_info_dict() |
| 1079 |
info_dict["types"] = [await t.to_info_dict() for t in self.types] |
| 1080 |
return info_dict |
| 1081 |
|
| 1082 |
@property |
| 1083 |
def name(self) -> str: # type: ignore |
| 1084 |
return f"<{' '.join(ty.name for ty in self.types)}>" |
| 1085 |
|
| 1086 |
@property |
| 1087 |
def arity(self) -> int: # type: ignore |
| 1088 |
return len(self.types) |
| 1089 |
|
| 1090 |
def convert( |
| 1091 |
self, value: t.Any, param: Parameter | None, ctx: Context | None |
| 1092 |
) -> t.Any: |
| 1093 |
len_type = len(self.types) |
| 1094 |
len_value = len(value) |
| 1095 |
|
| 1096 |
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 |
) |
| 1106 |
|
| 1107 |
return tuple( |
| 1108 |
ty(x, param, ctx) for ty, x in zip(self.types, value, strict=False) |
| 1109 |
) |
| 1110 |
|
| 1111 |
|
| 1112 |
def convert_type(ty: t.Any | None, default: t.Any | None = None) -> ParamType: |
| 1113 |
"""Find the most appropriate :class:`ParamType` for the given Python |
| 1114 |
type. If the type isn't provided, it can be inferred from a default |
| 1115 |
value. |
| 1116 |
""" |
| 1117 |
guessed_type = False |
| 1118 |
|
| 1119 |
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 will |
| 1122 |
# return STRING. |
| 1123 |
if default: |
| 1124 |
item = default[0] |
| 1125 |
|
| 1126 |
# A tuple of tuples needs to detect the inner types. |
| 1127 |
# Can't call convert recursively because that would |
| 1128 |
# 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) |
| 1135 |
|
| 1136 |
guessed_type = True |
| 1137 |
|
| 1138 |
if isinstance(ty, tuple): |
| 1139 |
return Tuple(ty) |
| 1140 |
|
| 1141 |
if isinstance(ty, ParamType): |
| 1142 |
return ty |
| 1143 |
|
| 1144 |
if ty is str or ty is None: |
| 1145 |
return STRING |
| 1146 |
|
| 1147 |
if ty is int: |
| 1148 |
return INT |
| 1149 |
|
| 1150 |
if ty is float: |
| 1151 |
return FLOAT |
| 1152 |
|
| 1153 |
if ty is bool: |
| 1154 |
return BOOL |
| 1155 |
|
| 1156 |
if guessed_type: |
| 1157 |
return STRING |
| 1158 |
|
| 1159 |
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 |
pass |
| 1168 |
|
| 1169 |
return FuncParamType(ty) |
| 1170 |
|
| 1171 |
|
| 1172 |
#: A dummy parameter type that just does nothing. From a user's |
| 1173 |
#: perspective this appears to just be the same as `STRING` but |
| 1174 |
#: internally no string conversion takes place if the input was bytes. |
| 1175 |
#: This is usually useful when working with file paths as they can |
| 1176 |
#: appear in bytes and unicode. |
| 1177 |
#: |
| 1178 |
#: For path related uses the :class:`Path` type is a better choice but |
| 1179 |
#: there are situations where an unprocessed type is useful which is why |
| 1180 |
#: it is is provided. |
| 1181 |
#: |
| 1182 |
#: .. versionadded:: 4.0 |
| 1183 |
UNPROCESSED = UnprocessedParamType() |
| 1184 |
|
| 1185 |
#: A unicode string parameter type which is the implicit default. This |
| 1186 |
#: can also be selected by using ``str`` as type. |
| 1187 |
STRING = StringParamType() |
| 1188 |
|
| 1189 |
#: An integer parameter. This can also be selected by using ``int`` as |
| 1190 |
#: type. |
| 1191 |
INT = IntParamType() |
| 1192 |
|
| 1193 |
#: A floating point value parameter. This can also be selected by using |
| 1194 |
#: ``float`` as type. |
| 1195 |
FLOAT = FloatParamType() |
| 1196 |
|
| 1197 |
#: A boolean parameter. This is the default for boolean flags. This can |
| 1198 |
#: also be selected by using ``bool`` as a type. |
| 1199 |
BOOL = BoolParamType() |
| 1200 |
|
| 1201 |
#: A UUID parameter. |
| 1202 |
UUID = UUIDParameterType() |
| 1203 |
|
| 1204 |
|
| 1205 |
class OptionHelpExtra(t.TypedDict, total=False): |
| 1206 |
envvars: tuple[str, ...] |
| 1207 |
default: str |
| 1208 |
range: str |
| 1209 |
required: str |