Skip to content
Myr

exceptions.py

This file

Path

src/click/exceptions.py

344 lines · 11.0 KiB · Python

Last changed by

Merge Main into Stable (#3442)Rowlando13before adoptioncd4674a

History of this file

Take it

1from __future__ import annotations23import collections.abc as cabc4import typing as t5from gettext import gettext as _6from gettext import ngettext78from ._compat import get_text_stderr9from .globals import resolve_color_default10from .utils import echo11from .utils import format_filename1213if t.TYPE_CHECKING:14    from .core import Command15    from .core import Context16    from .core import Parameter171819def _join_param_hints(param_hint: cabc.Sequence[str] | str | None) -> str | None:20    if param_hint is not None and not isinstance(param_hint, str):21        return " / ".join(repr(x) for x in param_hint)2223    return param_hint242526def _format_possibilities(possibilities: list[str]) -> str:27    possibility_str = ", ".join(repr(p) for p in sorted(possibilities))28    return ngettext(29        "Did you mean {possibility}?",30        "(Did you mean one of: {possibilities}?)",31        len(possibilities),32    ).format(possibility=possibility_str, possibilities=possibility_str)333435class ClickException(Exception):36    """An exception that Click can handle and show to the user."""3738    #: The exit code for this exception.39    exit_code = 14041    def __init__(self, message: str) -> None:42        super().__init__(message)43        # The context will be removed by the time we print the message, so cache44        # the color settings here to be used later on (in `show`)45        self.show_color: bool | None = resolve_color_default()46        self.message = message4748    def format_message(self) -> str:49        return self.message5051    def __str__(self) -> str:52        return self.message5354    def show(self, file: t.IO[t.Any] | None = None) -> None:55        if file is None:56            file = get_text_stderr()5758        echo(59            _("Error: {message}").format(message=self.format_message()),60            file=file,61            color=self.show_color,62        )636465class UsageError(ClickException):66    """An internal exception that signals a usage error.  This typically67    aborts any further handling.6869    :param message: the error message to display.70    :param ctx: optionally the context that caused this error.  Click will71                fill in the context automatically in some situations.72    """7374    exit_code = 27576    def __init__(self, message: str, ctx: Context | None = None) -> None:77        super().__init__(message)78        self.ctx = ctx79        self.cmd: Command | None = self.ctx.command if self.ctx else None8081    def show(self, file: t.IO[t.Any] | None = None) -> None:82        if file is None:83            file = get_text_stderr()84        color = None85        hint = ""86        if (87            self.ctx is not None88            and self.ctx.command.get_help_option(self.ctx) is not None89        ):90            help_names = self.ctx.command.get_help_option_names(self.ctx)91            # Pick the longest name (like ``--help`` over ``-h``) for92            # readability in error messages.93            hint = _("Try '{command} {option}' for help.").format(94                command=self.ctx.command_path,95                option=max(help_names, key=len),96            )97            hint = f"{hint}\n"98        if self.ctx is not None:99            color = self.ctx.color100            echo(f"{self.ctx.get_usage()}\n{hint}", file=file, color=color)101        echo(102            _("Error: {message}").format(message=self.format_message()),103            file=file,104            color=color,105        )106107108class BadParameter(UsageError):109    """An exception that formats out a standardized error message for a110    bad parameter.  This is useful when thrown from a callback or type as111    Click will attach contextual information to it (for instance, which112    parameter it is).113114    .. versionadded:: 2.0115116    :param param: the parameter object that caused this error.  This can117                  be left out, and Click will attach this info itself118                  if possible.119    :param param_hint: a string that shows up as parameter name.  This120                       can be used as alternative to `param` in cases121                       where custom validation should happen.  If it is122                       a string it's used as such, if it's a list then123                       each item is quoted and separated.124    """125126    def __init__(127        self,128        message: str,129        ctx: Context | None = None,130        param: Parameter | None = None,131        param_hint: cabc.Sequence[str] | str | None = None,132    ) -> None:133        super().__init__(message, ctx)134        self.param = param135        self.param_hint = param_hint136137    def format_message(self) -> str:138        if self.param_hint is not None:139            param_hint = self.param_hint140        elif self.param is not None:141            param_hint = self.param.get_error_hint(self.ctx)142        else:143            return _("Invalid value: {message}").format(message=self.message)144145        return _("Invalid value for {param_hint}: {message}").format(146            param_hint=_join_param_hints(param_hint), message=self.message147        )148149150class MissingParameter(BadParameter):151    """Raised if click required an option or argument but it was not152    provided when invoking the script.153154    .. versionadded:: 4.0155156    :param param_type: a string that indicates the type of the parameter.157                       The default is to inherit the parameter type from158                       the given `param`.  Valid values are ``'parameter'``,159                       ``'option'`` or ``'argument'``.160    """161162    def __init__(163        self,164        message: str | None = None,165        ctx: Context | None = None,166        param: Parameter | None = None,167        param_hint: cabc.Sequence[str] | str | None = None,168        param_type: str | None = None,169    ) -> None:170        super().__init__(message or "", ctx, param, param_hint)171        self.param_type = param_type172173    def format_message(self) -> str:174        if self.param_hint is not None:175            param_hint: cabc.Sequence[str] | str | None = self.param_hint176        elif self.param is not None:177            param_hint = self.param.get_error_hint(self.ctx)178        else:179            param_hint = None180181        param_hint = _join_param_hints(param_hint)182        param_hint = f" {param_hint}" if param_hint else ""183184        param_type = self.param_type185        if param_type is None and self.param is not None:186            param_type = self.param.param_type_name187188        msg = self.message189        if self.param is not None:190            msg_extra = self.param.type.get_missing_message(191                param=self.param, ctx=self.ctx192            )193            if msg_extra:194                if msg:195                    msg += f". {msg_extra}"196                else:197                    msg = msg_extra198199        msg = f" {msg}" if msg else ""200201        # Translate param_type for known types.202        if param_type == "argument":203            missing = _("Missing argument")204        elif param_type == "option":205            missing = _("Missing option")206        elif param_type == "parameter":207            missing = _("Missing parameter")208        else:209            missing = _("Missing {param_type}").format(param_type=param_type)210211        return f"{missing}{param_hint}.{msg}"212213    def __str__(self) -> str:214        if not self.message:215            param_name = self.param.name if self.param else None216            return _("Missing parameter: {param_name}").format(param_name=param_name)217        else:218            return self.message219220221class NoSuchOption(UsageError):222    """Raised if Click attempted to handle an option that does not exist.223224    .. versionadded:: 4.0225    """226227    def __init__(228        self,229        option_name: str,230        message: str | None = None,231        possibilities: cabc.Iterable[str] | None = None,232        ctx: Context | None = None,233    ) -> None:234        if message is None:235            message = _("No such option {name!r}.").format(name=option_name)236237        super().__init__(message, ctx)238        self.option_name = option_name239        self.possibilities: list[str] | None = None240        if possibilities:241            from difflib import get_close_matches242243            self.possibilities = get_close_matches(option_name, possibilities)244245    def format_message(self) -> str:246        if not self.possibilities:247            return self.message248        return f"{self.message} {_format_possibilities(self.possibilities)}"249250251class NoSuchCommand(UsageError):252    """Raised if Click attempted to handle a command that does not exist."""253254    def __init__(255        self,256        command_name: str,257        message: str | None = None,258        possibilities: cabc.Iterable[str] | None = None,259        ctx: Context | None = None,260    ) -> None:261        if message is None:262            message = _("No such command {name!r}.").format(name=command_name)263264        super().__init__(message, ctx)265        self.command_name = command_name266        self.possibilities: list[str] | None = None267        if possibilities:268            from difflib import get_close_matches269270            self.possibilities = get_close_matches(command_name, possibilities)271272    def format_message(self) -> str:273        if not self.possibilities:274            return self.message275        return f"{self.message} {_format_possibilities(self.possibilities)}"276277278class BadOptionUsage(UsageError):279    """Raised if an option is generally supplied but the use of the option280    was incorrect.  This is for instance raised if the number of arguments281    for an option is not correct.282283    .. versionadded:: 4.0284285    :param option_name: the name of the option being used incorrectly.286    """287288    def __init__(289        self, option_name: str, message: str, ctx: Context | None = None290    ) -> None:291        super().__init__(message, ctx)292        self.option_name = option_name293294295class BadArgumentUsage(UsageError):296    """Raised if an argument is generally supplied but the use of the argument297    was incorrect.  This is for instance raised if the number of values298    for an argument is not correct.299300    .. versionadded:: 6.0301    """302303304class NoArgsIsHelpError(UsageError):305    def __init__(self, ctx: Context) -> None:306        self.ctx: Context307        super().__init__(ctx.get_help(), ctx=ctx)308309    def show(self, file: t.IO[t.Any] | None = None) -> None:310        echo(self.format_message(), file=file, err=True, color=self.ctx.color)311312313class FileError(ClickException):314    """Raised if a file cannot be opened."""315316    def __init__(self, filename: str, hint: str | None = None) -> None:317        if hint is None:318            hint = _("unknown error")319320        super().__init__(hint)321        self.ui_filename: str = format_filename(filename)322        self.filename = filename323324    def format_message(self) -> str:325        return _("Could not open file {filename!r}: {message}").format(326            filename=self.ui_filename, message=self.message327        )328329330class Abort(RuntimeError):331    """An internal signalling exception that signals Click to abort."""332333334class Exit(RuntimeError):335    """An exception that indicates that the application should exit with some336    status code.337338    :param code: the status code to exit with.339    """340341    __slots__ = ("exit_code",)342343    def __init__(self, code: int = 0) -> None:344        self.exit_code: int = code