utils.py 20 KB

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