types.py 36 KB

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