utils.py 20 KB

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