types.py 35 KB

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