You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

580 lines
18KB

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