You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1053 lines
35KB

  1. import os
  2. import stat
  3. import typing as t
  4. from datetime import datetime
  5. from gettext import gettext as _
  6. from gettext import ngettext
  7. from ._compat import _get_argv_encoding
  8. from ._compat import get_filesystem_encoding
  9. from ._compat import open_stream
  10. from .exceptions import BadParameter
  11. from .utils import LazyFile
  12. from .utils import safecall
  13. if t.TYPE_CHECKING:
  14. import typing_extensions as te
  15. from .core import Context
  16. from .core import Parameter
  17. from .shell_completion import CompletionItem
  18. class ParamType:
  19. """Represents the type of a parameter. Validates and converts values
  20. from the command line or Python into the correct type.
  21. To implement a custom type, subclass and implement at least the
  22. following:
  23. - The :attr:`name` class attribute must be set.
  24. - Calling an instance of the type with ``None`` must return
  25. ``None``. This is already implemented by default.
  26. - :meth:`convert` must convert string values to the correct type.
  27. - :meth:`convert` must accept values that are already the correct
  28. type.
  29. - It must be able to convert a value if the ``ctx`` and ``param``
  30. arguments are ``None``. This can occur when converting prompt
  31. input.
  32. """
  33. is_composite: t.ClassVar[bool] = False
  34. arity: t.ClassVar[int] = 1
  35. #: the descriptive name of this type
  36. name: str
  37. #: if a list of this type is expected and the value is pulled from a
  38. #: string environment variable, this is what splits it up. `None`
  39. #: means any whitespace. For all parameters the general rule is that
  40. #: whitespace splits them up. The exception are paths and files which
  41. #: are split by ``os.path.pathsep`` by default (":" on Unix and ";" on
  42. #: Windows).
  43. envvar_list_splitter: t.ClassVar[t.Optional[str]] = None
  44. def to_info_dict(self) -> t.Dict[str, t.Any]:
  45. """Gather information that could be useful for a tool generating
  46. user-facing documentation.
  47. Use :meth:`click.Context.to_info_dict` to traverse the entire
  48. CLI structure.
  49. .. versionadded:: 8.0
  50. """
  51. # The class name without the "ParamType" suffix.
  52. param_type = type(self).__name__.partition("ParamType")[0]
  53. param_type = param_type.partition("ParameterType")[0]
  54. return {"param_type": param_type, "name": self.name}
  55. def __call__(
  56. self,
  57. value: t.Any,
  58. param: t.Optional["Parameter"] = None,
  59. ctx: t.Optional["Context"] = None,
  60. ) -> t.Any:
  61. if value is not None:
  62. return self.convert(value, param, ctx)
  63. def get_metavar(self, param: "Parameter") -> t.Optional[str]:
  64. """Returns the metavar default for this param if it provides one."""
  65. def get_missing_message(self, param: "Parameter") -> t.Optional[str]:
  66. """Optionally might return extra information about a missing
  67. parameter.
  68. .. versionadded:: 2.0
  69. """
  70. def convert(
  71. self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]
  72. ) -> t.Any:
  73. """Convert the value to the correct type. This is not called if
  74. the value is ``None`` (the missing value).
  75. This must accept string values from the command line, as well as
  76. values that are already the correct type. It may also convert
  77. other compatible types.
  78. The ``param`` and ``ctx`` arguments may be ``None`` in certain
  79. situations, such as when converting prompt input.
  80. If the value cannot be converted, call :meth:`fail` with a
  81. descriptive message.
  82. :param value: The value to convert.
  83. :param param: The parameter that is using this type to convert
  84. its value. May be ``None``.
  85. :param ctx: The current context that arrived at this value. May
  86. be ``None``.
  87. """
  88. return value
  89. def split_envvar_value(self, rv: str) -> t.Sequence[str]:
  90. """Given a value from an environment variable this splits it up
  91. into small chunks depending on the defined envvar list splitter.
  92. If the splitter is set to `None`, which means that whitespace splits,
  93. then leading and trailing whitespace is ignored. Otherwise, leading
  94. and trailing splitters usually lead to empty items being included.
  95. """
  96. return (rv or "").split(self.envvar_list_splitter)
  97. def fail(
  98. self,
  99. message: str,
  100. param: t.Optional["Parameter"] = None,
  101. ctx: t.Optional["Context"] = None,
  102. ) -> "t.NoReturn":
  103. """Helper method to fail with an invalid value message."""
  104. raise BadParameter(message, ctx=ctx, param=param)
  105. def shell_complete(
  106. self, ctx: "Context", param: "Parameter", incomplete: str
  107. ) -> t.List["CompletionItem"]:
  108. """Return a list of
  109. :class:`~click.shell_completion.CompletionItem` objects for the
  110. incomplete value. Most types do not provide completions, but
  111. some do, and this allows custom types to provide custom
  112. completions as well.
  113. :param ctx: Invocation context for this command.
  114. :param param: The parameter that is requesting completion.
  115. :param incomplete: Value being completed. May be empty.
  116. .. versionadded:: 8.0
  117. """
  118. return []
  119. class CompositeParamType(ParamType):
  120. is_composite = True
  121. @property
  122. def arity(self) -> int: # type: ignore
  123. raise NotImplementedError()
  124. class FuncParamType(ParamType):
  125. def __init__(self, func: t.Callable[[t.Any], t.Any]) -> None:
  126. self.name = func.__name__
  127. self.func = func
  128. def to_info_dict(self) -> t.Dict[str, t.Any]:
  129. info_dict = super().to_info_dict()
  130. info_dict["func"] = self.func
  131. return info_dict
  132. def convert(
  133. self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]
  134. ) -> t.Any:
  135. try:
  136. return self.func(value)
  137. except ValueError:
  138. try:
  139. value = str(value)
  140. except UnicodeError:
  141. value = value.decode("utf-8", "replace")
  142. self.fail(value, param, ctx)
  143. class UnprocessedParamType(ParamType):
  144. name = "text"
  145. def convert(
  146. self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]
  147. ) -> t.Any:
  148. return value
  149. def __repr__(self) -> str:
  150. return "UNPROCESSED"
  151. class StringParamType(ParamType):
  152. name = "text"
  153. def convert(
  154. self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]
  155. ) -> t.Any:
  156. if isinstance(value, bytes):
  157. enc = _get_argv_encoding()
  158. try:
  159. value = value.decode(enc)
  160. except UnicodeError:
  161. fs_enc = get_filesystem_encoding()
  162. if fs_enc != enc:
  163. try:
  164. value = value.decode(fs_enc)
  165. except UnicodeError:
  166. value = value.decode("utf-8", "replace")
  167. else:
  168. value = value.decode("utf-8", "replace")
  169. return value
  170. return str(value)
  171. def __repr__(self) -> str:
  172. return "STRING"
  173. class Choice(ParamType):
  174. """The choice type allows a value to be checked against a fixed set
  175. of supported values. All of these values have to be strings.
  176. You should only pass a list or tuple of choices. Other iterables
  177. (like generators) may lead to surprising results.
  178. The resulting value will always be one of the originally passed choices
  179. regardless of ``case_sensitive`` or any ``ctx.token_normalize_func``
  180. being specified.
  181. See :ref:`choice-opts` for an example.
  182. :param case_sensitive: Set to false to make choices case
  183. insensitive. Defaults to true.
  184. """
  185. name = "choice"
  186. def __init__(self, choices: t.Sequence[str], case_sensitive: bool = True) -> None:
  187. self.choices = choices
  188. self.case_sensitive = case_sensitive
  189. def to_info_dict(self) -> t.Dict[str, t.Any]:
  190. info_dict = super().to_info_dict()
  191. info_dict["choices"] = self.choices
  192. info_dict["case_sensitive"] = self.case_sensitive
  193. return info_dict
  194. def get_metavar(self, param: "Parameter") -> str:
  195. choices_str = "|".join(self.choices)
  196. # Use curly braces to indicate a required argument.
  197. if param.required and param.param_type_name == "argument":
  198. return f"{{{choices_str}}}"
  199. # Use square braces to indicate an option or optional argument.
  200. return f"[{choices_str}]"
  201. def get_missing_message(self, param: "Parameter") -> str:
  202. return _("Choose from:\n\t{choices}").format(choices=",\n\t".join(self.choices))
  203. def convert(
  204. self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]
  205. ) -> t.Any:
  206. # Match through normalization and case sensitivity
  207. # first do token_normalize_func, then lowercase
  208. # preserve original `value` to produce an accurate message in
  209. # `self.fail`
  210. normed_value = value
  211. normed_choices = {choice: choice for choice in self.choices}
  212. if ctx is not None and ctx.token_normalize_func is not None:
  213. normed_value = ctx.token_normalize_func(value)
  214. normed_choices = {
  215. ctx.token_normalize_func(normed_choice): original
  216. for normed_choice, original in normed_choices.items()
  217. }
  218. if not self.case_sensitive:
  219. normed_value = normed_value.casefold()
  220. normed_choices = {
  221. normed_choice.casefold(): original
  222. for normed_choice, original in normed_choices.items()
  223. }
  224. if normed_value in normed_choices:
  225. return normed_choices[normed_value]
  226. choices_str = ", ".join(map(repr, self.choices))
  227. self.fail(
  228. ngettext(
  229. "{value!r} is not {choice}.",
  230. "{value!r} is not one of {choices}.",
  231. len(self.choices),
  232. ).format(value=value, choice=choices_str, choices=choices_str),
  233. param,
  234. ctx,
  235. )
  236. def __repr__(self) -> str:
  237. return f"Choice({list(self.choices)})"
  238. def shell_complete(
  239. self, ctx: "Context", param: "Parameter", incomplete: str
  240. ) -> t.List["CompletionItem"]:
  241. """Complete choices that start with the incomplete value.
  242. :param ctx: Invocation context for this command.
  243. :param param: The parameter that is requesting completion.
  244. :param incomplete: Value being completed. May be empty.
  245. .. versionadded:: 8.0
  246. """
  247. from click.shell_completion import CompletionItem
  248. str_choices = map(str, self.choices)
  249. if self.case_sensitive:
  250. matched = (c for c in str_choices if c.startswith(incomplete))
  251. else:
  252. incomplete = incomplete.lower()
  253. matched = (c for c in str_choices if c.lower().startswith(incomplete))
  254. return [CompletionItem(c) for c in matched]
  255. class DateTime(ParamType):
  256. """The DateTime type converts date strings into `datetime` objects.
  257. The format strings which are checked are configurable, but default to some
  258. common (non-timezone aware) ISO 8601 formats.
  259. When specifying *DateTime* formats, you should only pass a list or a tuple.
  260. Other iterables, like generators, may lead to surprising results.
  261. The format strings are processed using ``datetime.strptime``, and this
  262. consequently defines the format strings which are allowed.
  263. Parsing is tried using each format, in order, and the first format which
  264. parses successfully is used.
  265. :param formats: A list or tuple of date format strings, in the order in
  266. which they should be tried. Defaults to
  267. ``'%Y-%m-%d'``, ``'%Y-%m-%dT%H:%M:%S'``,
  268. ``'%Y-%m-%d %H:%M:%S'``.
  269. """
  270. name = "datetime"
  271. def __init__(self, formats: t.Optional[t.Sequence[str]] = None):
  272. self.formats = formats or ["%Y-%m-%d", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d %H:%M:%S"]
  273. def to_info_dict(self) -> t.Dict[str, t.Any]:
  274. info_dict = super().to_info_dict()
  275. info_dict["formats"] = self.formats
  276. return info_dict
  277. def get_metavar(self, param: "Parameter") -> str:
  278. return f"[{'|'.join(self.formats)}]"
  279. def _try_to_convert_date(self, value: t.Any, format: str) -> t.Optional[datetime]:
  280. try:
  281. return datetime.strptime(value, format)
  282. except ValueError:
  283. return None
  284. def convert(
  285. self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]
  286. ) -> t.Any:
  287. if isinstance(value, datetime):
  288. return value
  289. for format in self.formats:
  290. converted = self._try_to_convert_date(value, format)
  291. if converted is not None:
  292. return converted
  293. formats_str = ", ".join(map(repr, self.formats))
  294. self.fail(
  295. ngettext(
  296. "{value!r} does not match the format {format}.",
  297. "{value!r} does not match the formats {formats}.",
  298. len(self.formats),
  299. ).format(value=value, format=formats_str, formats=formats_str),
  300. param,
  301. ctx,
  302. )
  303. def __repr__(self) -> str:
  304. return "DateTime"
  305. class _NumberParamTypeBase(ParamType):
  306. _number_class: t.ClassVar[t.Type]
  307. def convert(
  308. self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]
  309. ) -> t.Any:
  310. try:
  311. return self._number_class(value)
  312. except ValueError:
  313. self.fail(
  314. _("{value!r} is not a valid {number_type}.").format(
  315. value=value, number_type=self.name
  316. ),
  317. param,
  318. ctx,
  319. )
  320. class _NumberRangeBase(_NumberParamTypeBase):
  321. def __init__(
  322. self,
  323. min: t.Optional[float] = None,
  324. max: t.Optional[float] = None,
  325. min_open: bool = False,
  326. max_open: bool = False,
  327. clamp: bool = False,
  328. ) -> None:
  329. self.min = min
  330. self.max = max
  331. self.min_open = min_open
  332. self.max_open = max_open
  333. self.clamp = clamp
  334. def to_info_dict(self) -> t.Dict[str, t.Any]:
  335. info_dict = super().to_info_dict()
  336. info_dict.update(
  337. min=self.min,
  338. max=self.max,
  339. min_open=self.min_open,
  340. max_open=self.max_open,
  341. clamp=self.clamp,
  342. )
  343. return info_dict
  344. def convert(
  345. self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]
  346. ) -> t.Any:
  347. import operator
  348. rv = super().convert(value, param, ctx)
  349. lt_min: bool = self.min is not None and (
  350. operator.le if self.min_open else operator.lt
  351. )(rv, self.min)
  352. gt_max: bool = self.max is not None and (
  353. operator.ge if self.max_open else operator.gt
  354. )(rv, self.max)
  355. if self.clamp:
  356. if lt_min:
  357. return self._clamp(self.min, 1, self.min_open) # type: ignore
  358. if gt_max:
  359. return self._clamp(self.max, -1, self.max_open) # type: ignore
  360. if lt_min or gt_max:
  361. self.fail(
  362. _("{value} is not in the range {range}.").format(
  363. value=rv, range=self._describe_range()
  364. ),
  365. param,
  366. ctx,
  367. )
  368. return rv
  369. def _clamp(self, bound: float, dir: "te.Literal[1, -1]", open: bool) -> float:
  370. """Find the valid value to clamp to bound in the given
  371. direction.
  372. :param bound: The boundary value.
  373. :param dir: 1 or -1 indicating the direction to move.
  374. :param open: If true, the range does not include the bound.
  375. """
  376. raise NotImplementedError
  377. def _describe_range(self) -> str:
  378. """Describe the range for use in help text."""
  379. if self.min is None:
  380. op = "<" if self.max_open else "<="
  381. return f"x{op}{self.max}"
  382. if self.max is None:
  383. op = ">" if self.min_open else ">="
  384. return f"x{op}{self.min}"
  385. lop = "<" if self.min_open else "<="
  386. rop = "<" if self.max_open else "<="
  387. return f"{self.min}{lop}x{rop}{self.max}"
  388. def __repr__(self) -> str:
  389. clamp = " clamped" if self.clamp else ""
  390. return f"<{type(self).__name__} {self._describe_range()}{clamp}>"
  391. class IntParamType(_NumberParamTypeBase):
  392. name = "integer"
  393. _number_class = int
  394. def __repr__(self) -> str:
  395. return "INT"
  396. class IntRange(_NumberRangeBase, IntParamType):
  397. """Restrict an :data:`click.INT` value to a range of accepted
  398. values. See :ref:`ranges`.
  399. If ``min`` or ``max`` are not passed, any value is accepted in that
  400. direction. If ``min_open`` or ``max_open`` are enabled, the
  401. corresponding boundary is not included in the range.
  402. If ``clamp`` is enabled, a value outside the range is clamped to the
  403. boundary instead of failing.
  404. .. versionchanged:: 8.0
  405. Added the ``min_open`` and ``max_open`` parameters.
  406. """
  407. name = "integer range"
  408. def _clamp( # type: ignore
  409. self, bound: int, dir: "te.Literal[1, -1]", open: bool
  410. ) -> int:
  411. if not open:
  412. return bound
  413. return bound + dir
  414. class FloatParamType(_NumberParamTypeBase):
  415. name = "float"
  416. _number_class = float
  417. def __repr__(self) -> str:
  418. return "FLOAT"
  419. class FloatRange(_NumberRangeBase, FloatParamType):
  420. """Restrict a :data:`click.FLOAT` value to a range of accepted
  421. values. See :ref:`ranges`.
  422. If ``min`` or ``max`` are not passed, any value is accepted in that
  423. direction. If ``min_open`` or ``max_open`` are enabled, the
  424. corresponding boundary is not included in the range.
  425. If ``clamp`` is enabled, a value outside the range is clamped to the
  426. boundary instead of failing. This is not supported if either
  427. boundary is marked ``open``.
  428. .. versionchanged:: 8.0
  429. Added the ``min_open`` and ``max_open`` parameters.
  430. """
  431. name = "float range"
  432. def __init__(
  433. self,
  434. min: t.Optional[float] = None,
  435. max: t.Optional[float] = None,
  436. min_open: bool = False,
  437. max_open: bool = False,
  438. clamp: bool = False,
  439. ) -> None:
  440. super().__init__(
  441. min=min, max=max, min_open=min_open, max_open=max_open, clamp=clamp
  442. )
  443. if (min_open or max_open) and clamp:
  444. raise TypeError("Clamping is not supported for open bounds.")
  445. def _clamp(self, bound: float, dir: "te.Literal[1, -1]", open: bool) -> float:
  446. if not open:
  447. return bound
  448. # Could use Python 3.9's math.nextafter here, but clamping an
  449. # open float range doesn't seem to be particularly useful. It's
  450. # left up to the user to write a callback to do it if needed.
  451. raise RuntimeError("Clamping is not supported for open bounds.")
  452. class BoolParamType(ParamType):
  453. name = "boolean"
  454. def convert(
  455. self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]
  456. ) -> t.Any:
  457. if value in {False, True}:
  458. return bool(value)
  459. norm = value.strip().lower()
  460. if norm in {"1", "true", "t", "yes", "y", "on"}:
  461. return True
  462. if norm in {"0", "false", "f", "no", "n", "off"}:
  463. return False
  464. self.fail(
  465. _("{value!r} is not a valid boolean.").format(value=value), param, ctx
  466. )
  467. def __repr__(self) -> str:
  468. return "BOOL"
  469. class UUIDParameterType(ParamType):
  470. name = "uuid"
  471. def convert(
  472. self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]
  473. ) -> t.Any:
  474. import uuid
  475. if isinstance(value, uuid.UUID):
  476. return value
  477. value = value.strip()
  478. try:
  479. return uuid.UUID(value)
  480. except ValueError:
  481. self.fail(
  482. _("{value!r} is not a valid UUID.").format(value=value), param, ctx
  483. )
  484. def __repr__(self) -> str:
  485. return "UUID"
  486. class File(ParamType):
  487. """Declares a parameter to be a file for reading or writing. The file
  488. is automatically closed once the context tears down (after the command
  489. finished working).
  490. Files can be opened for reading or writing. The special value ``-``
  491. indicates stdin or stdout depending on the mode.
  492. By default, the file is opened for reading text data, but it can also be
  493. opened in binary mode or for writing. The encoding parameter can be used
  494. to force a specific encoding.
  495. The `lazy` flag controls if the file should be opened immediately or upon
  496. first IO. The default is to be non-lazy for standard input and output
  497. streams as well as files opened for reading, `lazy` otherwise. When opening a
  498. file lazily for reading, it is still opened temporarily for validation, but
  499. will not be held open until first IO. lazy is mainly useful when opening
  500. for writing to avoid creating the file until it is needed.
  501. Starting with Click 2.0, files can also be opened atomically in which
  502. case all writes go into a separate file in the same folder and upon
  503. completion the file will be moved over to the original location. This
  504. is useful if a file regularly read by other users is modified.
  505. See :ref:`file-args` for more information.
  506. """
  507. name = "filename"
  508. envvar_list_splitter = os.path.pathsep
  509. def __init__(
  510. self,
  511. mode: str = "r",
  512. encoding: t.Optional[str] = None,
  513. errors: t.Optional[str] = "strict",
  514. lazy: t.Optional[bool] = None,
  515. atomic: bool = False,
  516. ) -> None:
  517. self.mode = mode
  518. self.encoding = encoding
  519. self.errors = errors
  520. self.lazy = lazy
  521. self.atomic = atomic
  522. def to_info_dict(self) -> t.Dict[str, t.Any]:
  523. info_dict = super().to_info_dict()
  524. info_dict.update(mode=self.mode, encoding=self.encoding)
  525. return info_dict
  526. def resolve_lazy_flag(self, value: t.Any) -> bool:
  527. if self.lazy is not None:
  528. return self.lazy
  529. if value == "-":
  530. return False
  531. elif "w" in self.mode:
  532. return True
  533. return False
  534. def convert(
  535. self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]
  536. ) -> t.Any:
  537. try:
  538. if hasattr(value, "read") or hasattr(value, "write"):
  539. return value
  540. lazy = self.resolve_lazy_flag(value)
  541. if lazy:
  542. f: t.IO = t.cast(
  543. t.IO,
  544. LazyFile(
  545. value, self.mode, self.encoding, self.errors, atomic=self.atomic
  546. ),
  547. )
  548. if ctx is not None:
  549. ctx.call_on_close(f.close_intelligently) # type: ignore
  550. return f
  551. f, should_close = open_stream(
  552. value, self.mode, self.encoding, self.errors, atomic=self.atomic
  553. )
  554. # If a context is provided, we automatically close the file
  555. # at the end of the context execution (or flush out). If a
  556. # context does not exist, it's the caller's responsibility to
  557. # properly close the file. This for instance happens when the
  558. # type is used with prompts.
  559. if ctx is not None:
  560. if should_close:
  561. ctx.call_on_close(safecall(f.close))
  562. else:
  563. ctx.call_on_close(safecall(f.flush))
  564. return f
  565. except OSError as e: # noqa: B014
  566. self.fail(f"{os.fsdecode(value)!r}: {e.strerror}", param, ctx)
  567. def shell_complete(
  568. self, ctx: "Context", param: "Parameter", incomplete: str
  569. ) -> t.List["CompletionItem"]:
  570. """Return a special completion marker that tells the completion
  571. system to use the shell to provide file path completions.
  572. :param ctx: Invocation context for this command.
  573. :param param: The parameter that is requesting completion.
  574. :param incomplete: Value being completed. May be empty.
  575. .. versionadded:: 8.0
  576. """
  577. from click.shell_completion import CompletionItem
  578. return [CompletionItem(incomplete, type="file")]
  579. class Path(ParamType):
  580. """The path type is similar to the :class:`File` type but it performs
  581. different checks. First of all, instead of returning an open file
  582. handle it returns just the filename. Secondly, it can perform various
  583. basic checks about what the file or directory should be.
  584. :param exists: if set to true, the file or directory needs to exist for
  585. this value to be valid. If this is not required and a
  586. file does indeed not exist, then all further checks are
  587. silently skipped.
  588. :param file_okay: controls if a file is a possible value.
  589. :param dir_okay: controls if a directory is a possible value.
  590. :param writable: if true, a writable check is performed.
  591. :param readable: if true, a readable check is performed.
  592. :param resolve_path: if this is true, then the path is fully resolved
  593. before the value is passed onwards. This means
  594. that it's absolute and symlinks are resolved. It
  595. will not expand a tilde-prefix, as this is
  596. supposed to be done by the shell only.
  597. :param allow_dash: If this is set to `True`, a single dash to indicate
  598. standard streams is permitted.
  599. :param path_type: Convert the incoming path value to this type. If
  600. ``None``, keep Python's default, which is ``str``. Useful to
  601. convert to :class:`pathlib.Path`.
  602. .. versionchanged:: 8.0
  603. Allow passing ``type=pathlib.Path``.
  604. .. versionchanged:: 6.0
  605. Added the ``allow_dash`` parameter.
  606. """
  607. envvar_list_splitter = os.path.pathsep
  608. def __init__(
  609. self,
  610. exists: bool = False,
  611. file_okay: bool = True,
  612. dir_okay: bool = True,
  613. writable: bool = False,
  614. readable: bool = True,
  615. resolve_path: bool = False,
  616. allow_dash: bool = False,
  617. path_type: t.Optional[t.Type] = None,
  618. ):
  619. self.exists = exists
  620. self.file_okay = file_okay
  621. self.dir_okay = dir_okay
  622. self.writable = writable
  623. self.readable = readable
  624. self.resolve_path = resolve_path
  625. self.allow_dash = allow_dash
  626. self.type = path_type
  627. if self.file_okay and not self.dir_okay:
  628. self.name = _("file")
  629. elif self.dir_okay and not self.file_okay:
  630. self.name = _("directory")
  631. else:
  632. self.name = _("path")
  633. def to_info_dict(self) -> t.Dict[str, t.Any]:
  634. info_dict = super().to_info_dict()
  635. info_dict.update(
  636. exists=self.exists,
  637. file_okay=self.file_okay,
  638. dir_okay=self.dir_okay,
  639. writable=self.writable,
  640. readable=self.readable,
  641. allow_dash=self.allow_dash,
  642. )
  643. return info_dict
  644. def coerce_path_result(self, rv: t.Any) -> t.Any:
  645. if self.type is not None and not isinstance(rv, self.type):
  646. if self.type is str:
  647. rv = os.fsdecode(rv)
  648. elif self.type is bytes:
  649. rv = os.fsencode(rv)
  650. else:
  651. rv = self.type(rv)
  652. return rv
  653. def convert(
  654. self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]
  655. ) -> t.Any:
  656. rv = value
  657. is_dash = self.file_okay and self.allow_dash and rv in (b"-", "-")
  658. if not is_dash:
  659. if self.resolve_path:
  660. # realpath on Windows Python < 3.8 doesn't resolve symlinks
  661. if os.path.islink(rv):
  662. rv = os.readlink(rv)
  663. rv = os.path.realpath(rv)
  664. try:
  665. st = os.stat(rv)
  666. except OSError:
  667. if not self.exists:
  668. return self.coerce_path_result(rv)
  669. self.fail(
  670. _("{name} {filename!r} does not exist.").format(
  671. name=self.name.title(), filename=os.fsdecode(value)
  672. ),
  673. param,
  674. ctx,
  675. )
  676. if not self.file_okay and stat.S_ISREG(st.st_mode):
  677. self.fail(
  678. _("{name} {filename!r} is a file.").format(
  679. name=self.name.title(), filename=os.fsdecode(value)
  680. ),
  681. param,
  682. ctx,
  683. )
  684. if not self.dir_okay and stat.S_ISDIR(st.st_mode):
  685. self.fail(
  686. _("{name} {filename!r} is a directory.").format(
  687. name=self.name.title(), filename=os.fsdecode(value)
  688. ),
  689. param,
  690. ctx,
  691. )
  692. if self.writable and not os.access(value, os.W_OK):
  693. self.fail(
  694. _("{name} {filename!r} is not writable.").format(
  695. name=self.name.title(), filename=os.fsdecode(value)
  696. ),
  697. param,
  698. ctx,
  699. )
  700. if self.readable and not os.access(value, os.R_OK):
  701. self.fail(
  702. _("{name} {filename!r} is not readable.").format(
  703. name=self.name.title(), filename=os.fsdecode(value)
  704. ),
  705. param,
  706. ctx,
  707. )
  708. return self.coerce_path_result(rv)
  709. def shell_complete(
  710. self, ctx: "Context", param: "Parameter", incomplete: str
  711. ) -> t.List["CompletionItem"]:
  712. """Return a special completion marker that tells the completion
  713. system to use the shell to provide path completions for only
  714. directories or any paths.
  715. :param ctx: Invocation context for this command.
  716. :param param: The parameter that is requesting completion.
  717. :param incomplete: Value being completed. May be empty.
  718. .. versionadded:: 8.0
  719. """
  720. from click.shell_completion import CompletionItem
  721. type = "dir" if self.dir_okay and not self.file_okay else "file"
  722. return [CompletionItem(incomplete, type=type)]
  723. class Tuple(CompositeParamType):
  724. """The default behavior of Click is to apply a type on a value directly.
  725. This works well in most cases, except for when `nargs` is set to a fixed
  726. count and different types should be used for different items. In this
  727. case the :class:`Tuple` type can be used. This type can only be used
  728. if `nargs` is set to a fixed number.
  729. For more information see :ref:`tuple-type`.
  730. This can be selected by using a Python tuple literal as a type.
  731. :param types: a list of types that should be used for the tuple items.
  732. """
  733. def __init__(self, types: t.Sequence[t.Union[t.Type, ParamType]]) -> None:
  734. self.types = [convert_type(ty) for ty in types]
  735. def to_info_dict(self) -> t.Dict[str, t.Any]:
  736. info_dict = super().to_info_dict()
  737. info_dict["types"] = [t.to_info_dict() for t in self.types]
  738. return info_dict
  739. @property
  740. def name(self) -> str: # type: ignore
  741. return f"<{' '.join(ty.name for ty in self.types)}>"
  742. @property
  743. def arity(self) -> int: # type: ignore
  744. return len(self.types)
  745. def convert(
  746. self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]
  747. ) -> t.Any:
  748. len_type = len(self.types)
  749. len_value = len(value)
  750. if len_value != len_type:
  751. self.fail(
  752. ngettext(
  753. "{len_type} values are required, but {len_value} was given.",
  754. "{len_type} values are required, but {len_value} were given.",
  755. len_value,
  756. ).format(len_type=len_type, len_value=len_value),
  757. param=param,
  758. ctx=ctx,
  759. )
  760. return tuple(ty(x, param, ctx) for ty, x in zip(self.types, value))
  761. def convert_type(ty: t.Optional[t.Any], default: t.Optional[t.Any] = None) -> ParamType:
  762. """Find the most appropriate :class:`ParamType` for the given Python
  763. type. If the type isn't provided, it can be inferred from a default
  764. value.
  765. """
  766. guessed_type = False
  767. if ty is None and default is not None:
  768. if isinstance(default, (tuple, list)):
  769. # If the default is empty, ty will remain None and will
  770. # return STRING.
  771. if default:
  772. item = default[0]
  773. # A tuple of tuples needs to detect the inner types.
  774. # Can't call convert recursively because that would
  775. # incorrectly unwind the tuple to a single type.
  776. if isinstance(item, (tuple, list)):
  777. ty = tuple(map(type, item))
  778. else:
  779. ty = type(item)
  780. else:
  781. ty = type(default)
  782. guessed_type = True
  783. if isinstance(ty, tuple):
  784. return Tuple(ty)
  785. if isinstance(ty, ParamType):
  786. return ty
  787. if ty is str or ty is None:
  788. return STRING
  789. if ty is int:
  790. return INT
  791. if ty is float:
  792. return FLOAT
  793. if ty is bool:
  794. return BOOL
  795. if guessed_type:
  796. return STRING
  797. if __debug__:
  798. try:
  799. if issubclass(ty, ParamType):
  800. raise AssertionError(
  801. f"Attempted to use an uninstantiated parameter type ({ty})."
  802. )
  803. except TypeError:
  804. # ty is an instance (correct), so issubclass fails.
  805. pass
  806. return FuncParamType(ty)
  807. #: A dummy parameter type that just does nothing. From a user's
  808. #: perspective this appears to just be the same as `STRING` but
  809. #: internally no string conversion takes place if the input was bytes.
  810. #: This is usually useful when working with file paths as they can
  811. #: appear in bytes and unicode.
  812. #:
  813. #: For path related uses the :class:`Path` type is a better choice but
  814. #: there are situations where an unprocessed type is useful which is why
  815. #: it is is provided.
  816. #:
  817. #: .. versionadded:: 4.0
  818. UNPROCESSED = UnprocessedParamType()
  819. #: A unicode string parameter type which is the implicit default. This
  820. #: can also be selected by using ``str`` as type.
  821. STRING = StringParamType()
  822. #: An integer parameter. This can also be selected by using ``int`` as
  823. #: type.
  824. INT = IntParamType()
  825. #: A floating point value parameter. This can also be selected by using
  826. #: ``float`` as type.
  827. FLOAT = FloatParamType()
  828. #: A boolean parameter. This is the default for boolean flags. This can
  829. #: also be selected by using ``bool`` as a type.
  830. BOOL = BoolParamType()
  831. #: A UUID parameter.
  832. UUID = UUIDParameterType()