utils.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688
  1. from __future__ import annotations
  2. import collections.abc as cabc
  3. import os
  4. import re
  5. import sys
  6. import typing as t
  7. from functools import update_wrapper
  8. from gettext import gettext as _
  9. from types import ModuleType
  10. from types import TracebackType
  11. from ._compat import _default_text_stderr
  12. from ._compat import _default_text_stdout
  13. from ._compat import _find_binary_writer
  14. from ._compat import binary_streams
  15. from ._compat import open_stream
  16. from ._compat import should_strip_ansi
  17. from ._compat import strip_ansi
  18. from ._compat import text_streams
  19. from ._compat import WIN
  20. from .globals import resolve_color_default
  21. if t.TYPE_CHECKING:
  22. import typing_extensions as te
  23. P = te.ParamSpec("P")
  24. R = t.TypeVar("R")
  25. def _posixify(name: str) -> str:
  26. return "-".join(name.split()).lower()
  27. def _safecall(func: t.Callable[P, R]) -> t.Callable[P, R | None]:
  28. """Wraps a function so that it swallows exceptions.
  29. :meta private:
  30. """
  31. def wrapper(*args: P.args, **kwargs: P.kwargs) -> R | None:
  32. try:
  33. return func(*args, **kwargs)
  34. except Exception:
  35. pass
  36. return None
  37. return update_wrapper(wrapper, func)
  38. def make_str(value: t.Any) -> str:
  39. """Converts a value into a valid string."""
  40. if isinstance(value, bytes):
  41. try:
  42. return value.decode(sys.getfilesystemencoding())
  43. except UnicodeError:
  44. return value.decode("utf-8", "replace")
  45. return str(value)
  46. def _make_default_short_help(help: str, max_length: int = 45) -> str:
  47. """Returns a condensed version of help string.
  48. :meta private:
  49. """
  50. # Consider only the first paragraph.
  51. paragraph_end = help.find("\n\n")
  52. if paragraph_end != -1:
  53. help = help[:paragraph_end]
  54. # Collapse newlines, tabs, and spaces.
  55. words = help.split()
  56. if not words:
  57. return ""
  58. # The first paragraph started with a "no rewrap" marker, ignore it.
  59. if words[0] == "\b":
  60. words = words[1:]
  61. total_length = 0
  62. last_index = len(words) - 1
  63. for i, word in enumerate(words):
  64. total_length += len(word) + (i > 0)
  65. if total_length > max_length: # too long, truncate
  66. break
  67. if word[-1] == ".": # sentence end, truncate without "..."
  68. return " ".join(words[: i + 1])
  69. if total_length == max_length and i != last_index:
  70. break # not at sentence end, truncate with "..."
  71. else:
  72. return " ".join(words) # no truncation needed
  73. # Account for the length of the suffix.
  74. total_length += len("...")
  75. # remove words until the length is short enough
  76. while i > 0:
  77. total_length -= len(words[i]) + (i > 0)
  78. if total_length <= max_length:
  79. break
  80. i -= 1
  81. return " ".join(words[:i]) + "..."
  82. class _LazyFile:
  83. """A lazy file works like a regular file but it does not fully open
  84. the file but it does perform some basic checks early to see if the
  85. filename parameter does make sense. This is useful for safely opening
  86. files for writing.
  87. :meta private:
  88. """
  89. name: str
  90. mode: str
  91. encoding: str | None
  92. errors: str | None
  93. atomic: bool
  94. _f: t.IO[t.Any] | None
  95. should_close: bool
  96. def __init__(
  97. self,
  98. filename: str | os.PathLike[str],
  99. mode: str = "r",
  100. encoding: str | None = None,
  101. errors: str | None = "strict",
  102. atomic: bool = False,
  103. ) -> None:
  104. self.name = os.fspath(filename)
  105. self.mode = mode
  106. self.encoding = encoding
  107. self.errors = errors
  108. self.atomic = atomic
  109. if self.name == "-":
  110. self._f, self.should_close = open_stream(filename, mode, encoding, errors)
  111. else:
  112. if "r" in mode:
  113. # Open and close the file in case we're opening it for
  114. # reading so that we can catch at least some errors in
  115. # some cases early.
  116. open(filename, mode).close()
  117. self._f = None
  118. self.should_close = True
  119. def __getattr__(self, name: str) -> t.Any:
  120. return getattr(self.open(), name)
  121. def __repr__(self) -> str:
  122. if self._f is not None:
  123. return repr(self._f)
  124. return f"<unopened file '{format_filename(self.name)}' {self.mode}>"
  125. def open(self) -> t.IO[t.Any]:
  126. """Opens the file if it's not yet open. This call might fail with
  127. a :exc:`FileError`. Not handling this error will produce an error
  128. that Click shows.
  129. """
  130. if self._f is not None:
  131. return self._f
  132. try:
  133. rv, self.should_close = open_stream(
  134. self.name, self.mode, self.encoding, self.errors, atomic=self.atomic
  135. )
  136. except OSError as e:
  137. from .exceptions import FileError
  138. raise FileError(self.name, hint=e.strerror) from e
  139. self._f = rv
  140. return rv
  141. def close(self) -> None:
  142. """Closes the underlying file, no matter what."""
  143. if self._f is not None:
  144. self._f.close()
  145. def close_intelligently(self) -> None:
  146. """This function only closes the file if it was opened by the lazy
  147. file wrapper. For instance this will never close stdin.
  148. """
  149. if self.should_close:
  150. self.close()
  151. def __enter__(self) -> _LazyFile:
  152. return self
  153. def __exit__(
  154. self,
  155. exc_type: type[BaseException] | None,
  156. exc_value: BaseException | None,
  157. tb: TracebackType | None,
  158. ) -> None:
  159. self.close_intelligently()
  160. def __iter__(self) -> cabc.Iterator[t.AnyStr]:
  161. self.open()
  162. return iter(self._f) # type: ignore
  163. class _KeepOpenFile:
  164. """Proxy a file object but keep it open across a ``with`` block.
  165. Wraps a borrowed file (such as ``sys.stdin`` or ``sys.stdout``) so that
  166. leaving a ``with`` block does not close it, as used by :func:`open_file`
  167. for the ``-`` filename. The caller stays responsible for the file: an
  168. explicit :meth:`close` still passes through to the wrapped object.
  169. Dunder methods are proxied explicitly: implicit special-method lookups
  170. bypass :meth:`__getattr__`, because Python resolves them on the type rather
  171. than the instance.
  172. :meta private:
  173. """
  174. _file: t.IO[t.Any]
  175. def __init__(self, file: t.IO[t.Any]) -> None:
  176. self._file = file
  177. def __getattr__(self, name: str) -> t.Any:
  178. return getattr(self._file, name)
  179. def __enter__(self) -> _KeepOpenFile:
  180. return self
  181. def __exit__(
  182. self,
  183. exc_type: type[BaseException] | None,
  184. exc_value: BaseException | None,
  185. tb: TracebackType | None,
  186. ) -> None:
  187. pass
  188. def __repr__(self) -> str:
  189. return repr(self._file)
  190. def __iter__(self) -> cabc.Iterator[t.AnyStr]:
  191. return iter(self._file)
  192. def echo(
  193. message: object = None,
  194. file: t.IO[t.Any] | None = None,
  195. nl: bool = True,
  196. err: bool = False,
  197. color: bool | None = None,
  198. ) -> None:
  199. """Print a message and newline to stdout or a file. This should be
  200. used instead of :func:`print` because it provides better support
  201. for different data, files, and environments.
  202. Compared to :func:`print`, this does the following:
  203. - Ensures that the output encoding is not misconfigured on Linux.
  204. - Supports Unicode in the Windows console.
  205. - Supports writing to binary outputs, and supports writing bytes
  206. to text outputs.
  207. - Removes ANSI color and style codes if the output does not look
  208. like an interactive terminal.
  209. - Always flushes the output.
  210. :param message: The string or bytes to output. Other objects are
  211. converted to strings.
  212. :param file: The file to write to. Defaults to ``stdout``.
  213. :param err: Write to ``stderr`` instead of ``stdout``.
  214. :param nl: Print a newline after the message. Enabled by default.
  215. :param color: Force showing or hiding colors and other styles. By
  216. default Click will remove color if the output does not look like
  217. an interactive terminal.
  218. .. versionchanged:: 8.5.0
  219. Colorama is no longer used for color on Windows.
  220. .. versionchanged:: 6.0
  221. Support Unicode output on the Windows console. Click does not
  222. modify ``sys.stdout``, so ``sys.stdout.write()`` and ``print()``
  223. will still not support Unicode.
  224. .. versionchanged:: 4.0
  225. Added the ``color`` parameter.
  226. .. versionadded:: 3.0
  227. Added the ``err`` parameter.
  228. .. versionchanged:: 2.0
  229. Support colors on Windows if colorama is installed.
  230. """
  231. if file is None:
  232. if err:
  233. file = _default_text_stderr()
  234. else:
  235. file = _default_text_stdout()
  236. # There are no standard streams attached to write to. For example,
  237. # pythonw on Windows.
  238. if file is None:
  239. return
  240. match message:
  241. case str() | bytes() | bytearray():
  242. out = message
  243. case None:
  244. out = ""
  245. case _:
  246. out = str(message)
  247. if nl:
  248. if isinstance(out, str):
  249. out += "\n"
  250. else:
  251. out += b"\n"
  252. if not out:
  253. file.flush()
  254. return
  255. # If there is a message and the value looks like bytes, we manually
  256. # need to find the binary stream and write the message in there.
  257. # This is done separately so that most stream types will work as you
  258. # would expect. Eg: you can write to StringIO for other cases.
  259. if isinstance(out, (bytes, bytearray)):
  260. binary_file = _find_binary_writer(file)
  261. if binary_file is not None:
  262. file.flush()
  263. binary_file.write(out)
  264. binary_file.flush()
  265. return
  266. # ANSI style code support. For no message or bytes, nothing happens.
  267. # When outputting to a file instead of a terminal, strip codes.
  268. elif should_strip_ansi(file, resolve_color_default(color)):
  269. out = strip_ansi(out)
  270. file.write(out) # type: ignore
  271. file.flush()
  272. def _get_binary_stream(name: t.Literal["stdin", "stdout", "stderr"]) -> t.BinaryIO:
  273. """Returns a system stream for byte processing.
  274. .. deprecated:: 8.5.0
  275. Will be removed in Click 9.0.
  276. :param name: the name of the stream to open. Valid names are ``'stdin'``,
  277. ``'stdout'`` and ``'stderr'``
  278. :meta private:
  279. """
  280. opener = binary_streams.get(name)
  281. if opener is None:
  282. raise TypeError(_("Unknown standard stream '{name}'").format(name=name))
  283. return opener()
  284. def _get_text_stream(
  285. name: t.Literal["stdin", "stdout", "stderr"],
  286. encoding: str | None = None,
  287. errors: str | None = "strict",
  288. ) -> t.TextIO:
  289. """Returns a system stream for text processing.
  290. .. deprecated:: 8.5.0
  291. Will be removed in Click 9.0.
  292. This usually returns a wrapped stream around a binary stream returned from
  293. :func:`get_binary_stream` but it also can take shortcuts for already
  294. correctly configured streams.
  295. :param name: the name of the stream to open. Valid names are ``'stdin'``,
  296. ``'stdout'`` and ``'stderr'``
  297. :param encoding: overrides the detected default encoding.
  298. :param errors: overrides the default error mode.
  299. :meta private:
  300. """
  301. opener = text_streams.get(name)
  302. if opener is None:
  303. raise TypeError(_("Unknown standard stream '{name}'").format(name=name))
  304. return opener(encoding, errors)
  305. def open_file(
  306. filename: str | os.PathLike[str],
  307. mode: str = "r",
  308. encoding: str | None = None,
  309. errors: str | None = "strict",
  310. lazy: bool = False,
  311. atomic: bool = False,
  312. ) -> t.IO[t.Any]:
  313. """Open a file, with extra behavior to handle ``'-'`` to indicate
  314. a standard stream, lazy open on write, and atomic write. Similar to
  315. the behavior of the :class:`~click.File` param type.
  316. If ``'-'`` is given to open ``stdout`` or ``stdin``, the stream is
  317. wrapped so that using it in a context manager will not close it.
  318. This makes it possible to use the function without accidentally
  319. closing a standard stream:
  320. .. code-block:: python
  321. with open_file(filename) as f:
  322. ...
  323. :param filename: The name or Path of the file to open, or ``'-'`` for
  324. ``stdin``/``stdout``.
  325. :param mode: The mode in which to open the file.
  326. :param encoding: The encoding to decode or encode a file opened in
  327. text mode.
  328. :param errors: The error handling mode.
  329. :param lazy: Wait to open the file until it is accessed. For read
  330. mode, the file is temporarily opened to raise access errors
  331. early, then closed until it is read again.
  332. :param atomic: Write to a temporary file and replace the given file
  333. on close.
  334. .. versionadded:: 3.0
  335. """
  336. if lazy:
  337. return t.cast(
  338. "t.IO[t.Any]", _LazyFile(filename, mode, encoding, errors, atomic=atomic)
  339. )
  340. f, should_close = open_stream(filename, mode, encoding, errors, atomic=atomic)
  341. if not should_close:
  342. f = t.cast("t.IO[t.Any]", _KeepOpenFile(f))
  343. return f
  344. def format_filename(
  345. filename: str | bytes | os.PathLike[str] | os.PathLike[bytes],
  346. shorten: bool = False,
  347. ) -> str:
  348. """Format a filename as a string for display. Ensures the filename can be
  349. displayed by replacing any invalid bytes or surrogate escapes in the name
  350. with the replacement character ``�``.
  351. Invalid bytes or surrogate escapes will raise an error when written to a
  352. stream with ``errors="strict"``. This will typically happen with ``stdout``
  353. when the locale is something like ``en_GB.UTF-8``.
  354. Many scenarios *are* safe to write surrogates though, due to PEP 538 and
  355. PEP 540, including:
  356. - Writing to ``stderr``, which uses ``errors="backslashreplace"``.
  357. - The system has ``LANG=C.UTF-8``, ``C``, or ``POSIX``. Python opens
  358. stdout and stderr with ``errors="surrogateescape"``.
  359. - None of ``LANG/LC_*`` are set. Python assumes ``LANG=C.UTF-8``.
  360. - Python is started in UTF-8 mode with ``PYTHONUTF8=1`` or ``-X utf8``.
  361. Python opens stdout and stderr with ``errors="surrogateescape"``.
  362. :param filename: formats a filename for UI display. This will also convert
  363. the filename into unicode without failing.
  364. :param shorten: this optionally shortens the filename to strip of the
  365. path that leads up to it.
  366. """
  367. if shorten:
  368. filename = os.path.basename(filename)
  369. else:
  370. filename = os.fspath(filename)
  371. if isinstance(filename, bytes):
  372. filename = filename.decode(sys.getfilesystemencoding(), "replace")
  373. else:
  374. filename = filename.encode("utf-8", "surrogateescape").decode(
  375. "utf-8", "replace"
  376. )
  377. return filename
  378. def get_app_dir(app_name: str, roaming: bool = True, force_posix: bool = False) -> str:
  379. r"""Returns the config folder for the application. The default behavior
  380. is to return whatever is most appropriate for the operating system.
  381. To give you an idea, for an app called ``"Foo Bar"``, something like
  382. the following folders could be returned:
  383. Mac OS X:
  384. ``~/Library/Application Support/Foo Bar``
  385. Mac OS X (POSIX):
  386. ``~/.foo-bar``
  387. Unix:
  388. ``~/.config/foo-bar``
  389. Unix (POSIX):
  390. ``~/.foo-bar``
  391. Windows (roaming):
  392. ``C:\Users\<user>\AppData\Roaming\Foo Bar``
  393. Windows (not roaming):
  394. ``C:\Users\<user>\AppData\Local\Foo Bar``
  395. .. versionadded:: 2.0
  396. :param app_name: the application name. This should be properly capitalized
  397. and can contain whitespace.
  398. :param roaming: controls if the folder should be roaming or not on Windows.
  399. Has no effect otherwise.
  400. :param force_posix: if this is set to `True` then on any POSIX system the
  401. folder will be stored in the home folder with a leading
  402. dot instead of the XDG config home or darwin's
  403. application support folder.
  404. """
  405. if WIN:
  406. key = "APPDATA" if roaming else "LOCALAPPDATA"
  407. folder = os.environ.get(key)
  408. if folder is None:
  409. folder = os.path.expanduser("~")
  410. return os.path.join(folder, app_name)
  411. if force_posix:
  412. return os.path.join(os.path.expanduser(f"~/.{_posixify(app_name)}"))
  413. if sys.platform == "darwin":
  414. return os.path.join(
  415. os.path.expanduser("~/Library/Application Support"), app_name
  416. )
  417. return os.path.join(
  418. os.environ.get("XDG_CONFIG_HOME", os.path.expanduser("~/.config")),
  419. _posixify(app_name),
  420. )
  421. class _PacifyFlushWrapper:
  422. """This wrapper is used to catch and suppress BrokenPipeErrors resulting
  423. from ``.flush()`` being called on broken pipe during the shutdown/final-GC
  424. of the Python interpreter. Notably ``.flush()`` is always called on
  425. ``sys.stdout`` and ``sys.stderr``. So as to have minimal impact on any
  426. other cleanup code, and the case where the underlying file is not a broken
  427. pipe, all calls and attributes are proxied.
  428. :meta private:
  429. """
  430. wrapped: t.IO[t.Any]
  431. def __init__(self, wrapped: t.IO[t.Any]) -> None:
  432. self.wrapped = wrapped
  433. def flush(self) -> None:
  434. try:
  435. self.wrapped.flush()
  436. except OSError as e:
  437. import errno
  438. if e.errno != errno.EPIPE:
  439. raise
  440. def __getattr__(self, attr: str) -> t.Any:
  441. return getattr(self.wrapped, attr)
  442. def _detect_program_name(
  443. path: str | None = None, _main: ModuleType | None = None
  444. ) -> str:
  445. """Determine the command used to run the program, for use in help
  446. text. If a file or entry point was executed, the file name is
  447. returned. If ``python -m`` was used to execute a module or package,
  448. ``python -m name`` is returned.
  449. This doesn't try to be too precise, the goal is to give a concise
  450. name for help text. Files are only shown as their name without the
  451. path. ``python`` is only shown for modules, and the full path to
  452. ``sys.executable`` is not shown.
  453. :param path: The Python file being executed. Python puts this in
  454. ``sys.argv[0]``, which is used by default.
  455. :param _main: The ``__main__`` module. This should only be passed
  456. during internal testing.
  457. .. versionadded:: 8.0
  458. Based on command args detection in the Werkzeug reloader.
  459. :meta private:
  460. """
  461. if _main is None:
  462. _main = sys.modules["__main__"]
  463. if not path:
  464. path = sys.argv[0]
  465. # The value of __package__ indicates how Python was called. It may
  466. # not exist if a setuptools script is installed as an egg. It may be
  467. # set incorrectly for entry points created with pip on Windows.
  468. # It is set to "" inside a Shiv or PEX zipapp.
  469. if getattr(_main, "__package__", None) in {None, ""} or (
  470. os.name == "nt"
  471. and _main.__package__ == ""
  472. and not os.path.exists(path)
  473. and os.path.exists(f"{path}.exe")
  474. ):
  475. # Executed a file, like "python app.py".
  476. return os.path.basename(path)
  477. # Executed a module, like "python -m example".
  478. # Rewritten by Python from "-m script" to "/path/to/script.py".
  479. # Need to look at main module to determine how it was executed.
  480. py_module = t.cast(str, _main.__package__)
  481. name = os.path.splitext(os.path.basename(path))[0]
  482. # A submodule like "example.cli".
  483. if name != "__main__":
  484. py_module = f"{py_module}.{name}"
  485. return f"python -m {py_module.lstrip('.')}"
  486. def _expand_args(
  487. args: cabc.Iterable[str],
  488. *,
  489. user: bool = True,
  490. env: bool = True,
  491. glob_recursive: bool = True,
  492. ) -> list[str]:
  493. """Simulate Unix shell expansion with Python functions.
  494. See :func:`glob.glob`, :func:`os.path.expanduser`, and
  495. :func:`os.path.expandvars`.
  496. This is intended for use on Windows, where the shell does not do any
  497. expansion. It may not exactly match what a Unix shell would do.
  498. :param args: List of command line arguments to expand.
  499. :param user: Expand user home directory.
  500. :param env: Expand environment variables.
  501. :param glob_recursive: ``**`` matches directories recursively.
  502. .. versionchanged:: 8.1
  503. Invalid glob patterns are treated as empty expansions rather
  504. than raising an error.
  505. .. versionadded:: 8.0
  506. :meta private:
  507. """
  508. from glob import glob
  509. out = []
  510. for arg in args:
  511. if user:
  512. arg = os.path.expanduser(arg)
  513. if env:
  514. arg = os.path.expandvars(arg)
  515. try:
  516. matches = glob(arg, recursive=glob_recursive)
  517. except re.error:
  518. matches = []
  519. if not matches:
  520. out.append(arg)
  521. else:
  522. out.extend(matches)
  523. return out
  524. def __getattr__(name: str) -> object:
  525. import warnings
  526. if name in {
  527. "LazyFile",
  528. "KeepOpenFile",
  529. "make_default_short_help",
  530. "PacifyFlushWrapper",
  531. "safecall",
  532. "get_text_stream",
  533. "get_binary_stream",
  534. }:
  535. warnings.warn(
  536. f"'click.utils.{name}' is deprecated and will be removed in Click 9.0.",
  537. DeprecationWarning,
  538. stacklevel=2,
  539. )
  540. return globals()[f"_{name}"]
  541. raise AttributeError(name)