Debian Codegraph @

src/asyncclick/utils.py

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