Skip to content
Myr

exceptions.py

This file

Path

click/exceptions.py

188 lines · 6.2 KiB · Python

Last changed by

Refactor missing parameter handling.Armin Ronacherbefore adoption64f57fe

History of this file

Take it

1from ._compat import PY2, filename_to_ui, get_text_stderr2from .utils import echo345class ClickException(Exception):6    """An exception that Click can handle and show to the user."""78    #: The exit code for this exception9    exit_code = 11011    def __init__(self, message):12        if PY2:13            if message is not None:14                message = message.encode('utf-8')15        Exception.__init__(self, message)16        self.message = message1718    def format_message(self):19        return self.message2021    def show(self, file=None):22        if file is None:23            file = get_text_stderr()24        echo('Error: %s' % self.format_message(), file=file)252627class UsageError(ClickException):28    """An internal exception that signals a usage error.  This typically29    aborts any further handling.3031    :param message: the error message to display.32    :param ctx: optionally the context that caused this error.  Click will33                fill in the context automatically in some situations.34    """35    exit_code = 23637    def __init__(self, message, ctx=None):38        ClickException.__init__(self, message)39        self.ctx = ctx4041    def show(self, file=None):42        if file is None:43            file = get_text_stderr()44        color = None45        if self.ctx is not None:46            color = self.ctx.color47            echo(self.ctx.get_usage() + '\n', file=file, color=color)48        echo('Error: %s' % self.format_message(), file=file, color=color)495051class BadParameter(UsageError):52    """An exception that formats out a standardized error message for a53    bad parameter.  This is useful when thrown from a callback or type as54    Click will attach contextual information to it (for instance, which55    parameter it is).5657    .. versionadded:: 2.05859    :param param: the parameter object that caused this error.  This can60                  be left out, and Click will attach this info itself61                  if possible.62    :param param_hint: a string that shows up as parameter name.  This63                       can be used as alternative to `param` in cases64                       where custom validation should happen.  If it is65                       a string it's used as such, if it's a list then66                       each item is quoted and separated.67    """6869    def __init__(self, message, ctx=None, param=None,70                 param_hint=None):71        UsageError.__init__(self, message, ctx)72        self.param = param73        self.param_hint = param_hint7475    def format_message(self):76        if self.param_hint is not None:77            param_hint = self.param_hint78        elif self.param is not None:79            param_hint = self.param.opts or [self.param.human_readable_name]80        else:81            return 'Invalid value: %s' % self.message82        if isinstance(param_hint, (tuple, list)):83            param_hint = ' / '.join('"%s"' % x for x in param_hint)84        return 'Invalid value for %s: %s' % (param_hint, self.message)858687class MissingParameter(BadParameter):88    """Raised if click required an option or argument but it was not89    provided when invoking the script.9091    .. versionadded:: 4.09293    :param param_type: a string that indicates the type of the parameter.94                       The default is to inherit the parameter type from95                       the given `param`.  Valid values are ``'parameter'``,96                       ``'option'`` or ``'argument'``.97    """9899    def __init__(self, message=None, ctx=None, param=None,100                 param_hint=None, param_type=None):101        BadParameter.__init__(self, message, ctx, param, param_hint)102        self.param_type = param_type103104    def format_message(self):105        if self.param_hint is not None:106            param_hint = self.param_hint107        elif self.param is not None:108            param_hint = self.param.opts or [self.param.human_readable_name]109        else:110            param_hint = None111        if isinstance(param_hint, (tuple, list)):112            param_hint = ' / '.join('"%s"' % x for x in param_hint)113114        param_type = self.param_type115        if param_type is None and self.param is not None:116            param_type = self.param.param_type_name117118        msg = self.message119        msg_extra = self.param.type.get_missing_message(self.param)120        if msg_extra:121            if msg:122                msg += '.  ' + msg_extra123            else:124                msg = msg_extra125126        return 'Missing %s%s%s%s' % (127            param_type,128            param_hint and ' %s' % param_hint or '',129            msg and '.  ' or '.',130            msg,131        )132133134class NoSuchOption(UsageError):135    """Raised if click attempted to handle an option that does not136    exist.137138    .. versionadded:: 4.0139    """140141    def __init__(self, option_name, message=None, possibilities=None,142                 ctx=None):143        if message is None:144            message = 'no such option: %s' % option_name145        UsageError.__init__(self, message, ctx)146        self.option_name = option_name147        self.possibilities = possibilities148149    def format_message(self):150        bits = [self.message]151        if self.possibilities:152            if len(self.possibilities) == 1:153                bits.append('Did you mean %s?' % self.possibilities[0])154            else:155                possibilities = sorted(self.possibilities)156                bits.append('(Possible options: %s)' % ', '.join(possibilities))157        return '  '.join(bits)158159160class BadOptionUsage(UsageError):161    """Raised if an option is generally supplied but the use of the option162    was incorrect.  This is for instance raised if the number of arguments163    for an option is not correct.164165    .. versionadded:: 4.0166    """167168    def __init__(self, option_name, message, ctx=None):169        UsageError.__init__(self, message, ctx)170171172class FileError(ClickException):173    """Raised if a file cannot be opened."""174175    def __init__(self, filename, hint=None):176        ui_filename = filename_to_ui(filename)177        if hint is None:178            hint = 'unknown error'179        ClickException.__init__(self, hint)180        self.ui_filename = ui_filename181        self.filename = filename182183    def format_message(self):184        return 'Could not open file %s: %s' % (self.ui_filename, self.message)185186187class Abort(RuntimeError):188    """An internal signalling exception that signals Click to abort."""