utils.py 20 KB

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