Skip to content
Myr

utils.py

This file

Path

src/click/utils.py

627 lines · 19.7 KiB · Python

Last changed by

enable deferred evaluation of annotations (#2270)David Lordbefore adoption56db546

History of this file

Take it

1from __future__ import annotations23import collections.abc as cabc4import os5import re6import sys7import typing as t8from functools import update_wrapper9from types import ModuleType10from types import TracebackType1112from ._compat import _default_text_stderr13from ._compat import _default_text_stdout14from ._compat import _find_binary_writer15from ._compat import auto_wrap_for_ansi16from ._compat import binary_streams17from ._compat import open_stream18from ._compat import should_strip_ansi19from ._compat import strip_ansi20from ._compat import text_streams21from ._compat import WIN22from .globals import resolve_color_default2324if t.TYPE_CHECKING:25    import typing_extensions as te2627    P = te.ParamSpec("P")2829R = t.TypeVar("R")303132def _posixify(name: str) -> str:33    return "-".join(name.split()).lower()343536def safecall(func: t.Callable[P, R]) -> t.Callable[P, R | None]:37    """Wraps a function so that it swallows exceptions."""3839    def wrapper(*args: P.args, **kwargs: P.kwargs) -> R | None:40        try:41            return func(*args, **kwargs)42        except Exception:43            pass44        return None4546    return update_wrapper(wrapper, func)474849def 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)575859def 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")6364    if paragraph_end != -1:65        help = help[:paragraph_end]6667    # Collapse newlines, tabs, and spaces.68    words = help.split()6970    if not words:71        return ""7273    # The first paragraph started with a "no rewrap" marker, ignore it.74    if words[0] == "\b":75        words = words[1:]7677    total_length = 078    last_index = len(words) - 17980    for i, word in enumerate(words):81        total_length += len(word) + (i > 0)8283        if total_length > max_length:  # too long, truncate84            break8586        if word[-1] == ".":  # sentence end, truncate without "..."87            return " ".join(words[: i + 1])8889        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 needed9394    # Account for the length of the suffix.95    total_length += len("...")9697    # remove words until the length is short enough98    while i > 0:99        total_length -= len(words[i]) + (i > 0)100101        if total_length <= max_length:102            break103104        i -= 1105106    return " ".join(words[:i]) + "..."107108109class LazyFile:110    """A lazy file works like a regular file but it does not fully open111    the file but it does perform some basic checks early to see if the112    filename parameter does make sense.  This is useful for safely opening113    files for writing.114    """115116    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 = mode126        self.encoding = encoding127        self.errors = errors128        self.atomic = atomic129        self._f: t.IO[t.Any] | None130        self.should_close: bool131132        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 for137                # reading so that we can catch at least some errors in138                # some cases early.139                open(filename, mode).close()140            self._f = None141            self.should_close = True142143    def __getattr__(self, name: str) -> t.Any:144        return getattr(self.open(), name)145146    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}>"150151    def open(self) -> t.IO[t.Any]:152        """Opens the file if it's not yet open.  This call might fail with153        a :exc:`FileError`.  Not handling this error will produce an error154        that Click shows.155        """156        if self._f is not None:157            return self._f158        try:159            rv, self.should_close = open_stream(160                self.name, self.mode, self.encoding, self.errors, atomic=self.atomic161            )162        except OSError as e:  # noqa: E402163            from .exceptions import FileError164165            raise FileError(self.name, hint=e.strerror) from e166        self._f = rv167        return rv168169    def close(self) -> None:170        """Closes the underlying file, no matter what."""171        if self._f is not None:172            self._f.close()173174    def close_intelligently(self) -> None:175        """This function only closes the file if it was opened by the lazy176        file wrapper.  For instance this will never close stdin.177        """178        if self.should_close:179            self.close()180181    def __enter__(self) -> LazyFile:182        return self183184    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()191192    def __iter__(self) -> cabc.Iterator[t.AnyStr]:193        self.open()194        return iter(self._f)  # type: ignore195196197class KeepOpenFile:198    def __init__(self, file: t.IO[t.Any]) -> None:199        self._file: t.IO[t.Any] = file200201    def __getattr__(self, name: str) -> t.Any:202        return getattr(self._file, name)203204    def __enter__(self) -> KeepOpenFile:205        return self206207    def __exit__(208        self,209        exc_type: type[BaseException] | None,210        exc_value: BaseException | None,211        tb: TracebackType | None,212    ) -> None:213        pass214215    def __repr__(self) -> str:216        return repr(self._file)217218    def __iter__(self) -> cabc.Iterator[t.AnyStr]:219        return iter(self._file)220221222def 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 be230    used instead of :func:`print` because it provides better support231    for different data, files, and environments.232233    Compared to :func:`print`, this does the following:234235    -   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 bytes238        to text outputs.239    -   Supports colors and styles on Windows.240    -   Removes ANSI color and style codes if the output does not look241        like an interactive terminal.242    -   Always flushes the output.243244    :param message: The string or bytes to output. Other objects are245        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. By250        default Click will remove color if the output does not look like251        an interactive terminal.252253    .. versionchanged:: 6.0254        Support Unicode output on the Windows console. Click does not255        modify ``sys.stdout``, so ``sys.stdout.write()`` and ``print()``256        will still not support Unicode.257258    .. versionchanged:: 4.0259        Added the ``color`` parameter.260261    .. versionadded:: 3.0262        Added the ``err`` parameter.263264    .. versionchanged:: 2.0265        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()272273        # There are no standard streams attached to write to. For example,274        # pythonw on Windows.275        if file is None:276            return277278    # 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 | None = str(message)281    else:282        out = message283284    if nl:285        out = out or ""286        if isinstance(out, str):287            out += "\n"288        else:289            out += b"\n"290291    if not out:292        file.flush()293        return294295    # If there is a message and the value looks like bytes, we manually296    # 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 you298    # would expect. Eg: you can write to StringIO for other cases.299    if isinstance(out, (bytes, bytearray)):300        binary_file = _find_binary_writer(file)301302        if binary_file is not None:303            file.flush()304            binary_file.write(out)305            binary_file.flush()306            return307308    # 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)312313        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)  # type: ignore318            elif not color:319                out = strip_ansi(out)320321    file.write(out)  # type: ignore322    file.flush()323324325def get_binary_stream(name: t.Literal["stdin", "stdout", "stderr"]) -> t.BinaryIO:326    """Returns a system stream for byte processing.327328    :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()335336337def 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 returns343    a wrapped stream around a binary stream returned from344    :func:`get_binary_stream` but it also can take shortcuts for already345    correctly configured streams.346347    :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)356357358def open_file(359    filename: 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 indicate367    a standard stream, lazy open on write, and atomic write. Similar to368    the behavior of the :class:`~click.File` param type.369370    If ``'-'`` is given to open ``stdout`` or ``stdin``, the stream is371    wrapped so that using it in a context manager will not close it.372    This makes it possible to use the function without accidentally373    closing a standard stream:374375    .. code-block:: python376377        with open_file(filename) as f:378            ...379380    :param filename: The name of the file to open, or ``'-'`` for381        ``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 in384        text mode.385    :param errors: The error handling mode.386    :param lazy: Wait to open the file until it is accessed. For read387        mode, the file is temporarily opened to raise access errors388        early, then closed until it is read again.389    :param atomic: Write to a temporary file and replace the given file390        on close.391392    .. versionadded:: 3.0393    """394    if lazy:395        return t.cast(396            "t.IO[t.Any]", LazyFile(filename, mode, encoding, errors, atomic=atomic)397        )398399    f, should_close = open_stream(filename, mode, encoding, errors, atomic=atomic)400401    if not should_close:402        f = t.cast("t.IO[t.Any]", KeepOpenFile(f))403404    return f405406407def 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 be412    displayed by replacing any invalid bytes or surrogate escapes in the name413    with the replacement character ``�``.414415    Invalid bytes or surrogate escapes will raise an error when written to a416    stream with ``errors="strict". This will typically happen with ``stdout``417    when the locale is something like ``en_GB.UTF-8``.418419    Many scenarios *are* safe to write surrogates though, due to PEP 538 and420    PEP 540, including:421422    -   Writing to ``stderr``, which uses ``errors="backslashreplace"``.423    -   The system has ``LANG=C.UTF-8``, ``C``, or ``POSIX``. Python opens424        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"``.428429    :param filename: formats a filename for UI display.  This will also convert430                     the filename into unicode without failing.431    :param shorten: this optionally shortens the filename to strip of the432                    path that leads up to it.433    """434    if shorten:435        filename = os.path.basename(filename)436    else:437        filename = os.fspath(filename)438439    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        )445446    return filename447448449def 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 behavior451    is to return whatever is most appropriate for the operating system.452453    To give you an idea, for an app called ``"Foo Bar"``, something like454    the following folders could be returned:455456    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``468469    .. versionadded:: 2.0470471    :param app_name: the application name.  This should be properly capitalized472                     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 the476                        folder will be stored in the home folder with a leading477                        dot instead of the XDG config home or darwin's478                        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_name491        )492    return os.path.join(493        os.environ.get("XDG_CONFIG_HOME", os.path.expanduser("~/.config")),494        _posixify(app_name),495    )496497498class PacifyFlushWrapper:499    """This wrapper is used to catch and suppress BrokenPipeErrors resulting500    from ``.flush()`` being called on broken pipe during the shutdown/final-GC501    of the Python interpreter. Notably ``.flush()`` is always called on502    ``sys.stdout`` and ``sys.stderr``. So as to have minimal impact on any503    other cleanup code, and the case where the underlying file is not a broken504    pipe, all calls and attributes are proxied.505    """506507    def __init__(self, wrapped: t.IO[t.Any]) -> None:508        self.wrapped = wrapped509510    def flush(self) -> None:511        try:512            self.wrapped.flush()513        except OSError as e:514            import errno515516            if e.errno != errno.EPIPE:517                raise518519    def __getattr__(self, attr: str) -> t.Any:520        return getattr(self.wrapped, attr)521522523def _detect_program_name(524    path: str | None = None, _main: ModuleType | None = None525) -> str:526    """Determine the command used to run the program, for use in help527    text. If a file or entry point was executed, the file name is528    returned. If ``python -m`` was used to execute a module or package,529    ``python -m name`` is returned.530531    This doesn't try to be too precise, the goal is to give a concise532    name for help text. Files are only shown as their name without the533    path. ``python`` is only shown for modules, and the full path to534    ``sys.executable`` is not shown.535536    :param path: The Python file being executed. Python puts this in537        ``sys.argv[0]``, which is used by default.538    :param _main: The ``__main__`` module. This should only be passed539        during internal testing.540541    .. versionadded:: 8.0542        Based on command args detection in the Werkzeug reloader.543544    :meta private:545    """546    if _main is None:547        _main = sys.modules["__main__"]548549    if not path:550        path = sys.argv[0]551552    # The value of __package__ indicates how Python was called. It may553    # not exist if a setuptools script is installed as an egg. It may be554    # 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)564565    # 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]570571    # A submodule like "example.cli".572    if name != "__main__":573        py_module = f"{py_module}.{name}"574575    return f"python -m {py_module.lstrip('.')}"576577578def _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.586587    See :func:`glob.glob`, :func:`os.path.expanduser`, and588    :func:`os.path.expandvars`.589590    This is intended for use on Windows, where the shell does not do any591    expansion. It may not exactly match what a Unix shell would do.592593    :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.597598    .. versionchanged:: 8.1599        Invalid glob patterns are treated as empty expansions rather600        than raising an error.601602    .. versionadded:: 8.0603604    :meta private:605    """606    from glob import glob607608    out = []609610    for arg in args:611        if user:612            arg = os.path.expanduser(arg)613614        if env:615            arg = os.path.expandvars(arg)616617        try:618            matches = glob(arg, recursive=glob_recursive)619        except re.error:620            matches = []621622        if not matches:623            out.append(arg)624        else:625            out.extend(matches)626627    return out