utils.py 18 KB

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