exceptions.py
This file
Path
src/click/exceptions.py
253 lines · 7.9 KiB · Python
Last changed by
Merge pull request #1496 from pallets/fix-typoDavid Lordbefore adoptionc0329ac
History of this fileTake it
1from ._compat import filename_to_ui2from ._compat import get_text_stderr3from ._compat import PY24from .utils import echo567def _join_param_hints(param_hint):8 if isinstance(param_hint, (tuple, list)):9 return " / ".join(repr(x) for x in param_hint)10 return param_hint111213class ClickException(Exception):14 """An exception that Click can handle and show to the user."""1516 #: The exit code for this exception17 exit_code = 11819 def __init__(self, message):20 ctor_msg = message21 if PY2:22 if ctor_msg is not None:23 ctor_msg = ctor_msg.encode("utf-8")24 Exception.__init__(self, ctor_msg)25 self.message = message2627 def format_message(self):28 return self.message2930 def __str__(self):31 return self.message3233 if PY2:34 __unicode__ = __str__3536 def __str__(self):37 return self.message.encode("utf-8")3839 def show(self, file=None):40 if file is None:41 file = get_text_stderr()42 echo("Error: {}".format(self.format_message()), file=file)434445class UsageError(ClickException):46 """An internal exception that signals a usage error. This typically47 aborts any further handling.4849 :param message: the error message to display.50 :param ctx: optionally the context that caused this error. Click will51 fill in the context automatically in some situations.52 """5354 exit_code = 25556 def __init__(self, message, ctx=None):57 ClickException.__init__(self, message)58 self.ctx = ctx59 self.cmd = self.ctx.command if self.ctx else None6061 def show(self, file=None):62 if file is None:63 file = get_text_stderr()64 color = None65 hint = ""66 if self.cmd is not None and self.cmd.get_help_option(self.ctx) is not None:67 hint = "Try '{} {}' for help.\n".format(68 self.ctx.command_path, self.ctx.help_option_names[0]69 )70 if self.ctx is not None:71 color = self.ctx.color72 echo("{}\n{}".format(self.ctx.get_usage(), hint), file=file, color=color)73 echo("Error: {}".format(self.format_message()), file=file, color=color)747576class BadParameter(UsageError):77 """An exception that formats out a standardized error message for a78 bad parameter. This is useful when thrown from a callback or type as79 Click will attach contextual information to it (for instance, which80 parameter it is).8182 .. versionadded:: 2.08384 :param param: the parameter object that caused this error. This can85 be left out, and Click will attach this info itself86 if possible.87 :param param_hint: a string that shows up as parameter name. This88 can be used as alternative to `param` in cases89 where custom validation should happen. If it is90 a string it's used as such, if it's a list then91 each item is quoted and separated.92 """9394 def __init__(self, message, ctx=None, param=None, param_hint=None):95 UsageError.__init__(self, message, ctx)96 self.param = param97 self.param_hint = param_hint9899 def format_message(self):100 if self.param_hint is not None:101 param_hint = self.param_hint102 elif self.param is not None:103 param_hint = self.param.get_error_hint(self.ctx)104 else:105 return "Invalid value: {}".format(self.message)106 param_hint = _join_param_hints(param_hint)107108 return "Invalid value for {}: {}".format(param_hint, self.message)109110111class MissingParameter(BadParameter):112 """Raised if click required an option or argument but it was not113 provided when invoking the script.114115 .. versionadded:: 4.0116117 :param param_type: a string that indicates the type of the parameter.118 The default is to inherit the parameter type from119 the given `param`. Valid values are ``'parameter'``,120 ``'option'`` or ``'argument'``.121 """122123 def __init__(124 self, message=None, ctx=None, param=None, param_hint=None, param_type=None125 ):126 BadParameter.__init__(self, message, ctx, param, param_hint)127 self.param_type = param_type128129 def format_message(self):130 if self.param_hint is not None:131 param_hint = self.param_hint132 elif self.param is not None:133 param_hint = self.param.get_error_hint(self.ctx)134 else:135 param_hint = None136 param_hint = _join_param_hints(param_hint)137138 param_type = self.param_type139 if param_type is None and self.param is not None:140 param_type = self.param.param_type_name141142 msg = self.message143 if self.param is not None:144 msg_extra = self.param.type.get_missing_message(self.param)145 if msg_extra:146 if msg:147 msg += ". {}".format(msg_extra)148 else:149 msg = msg_extra150151 return "Missing {}{}{}{}".format(152 param_type,153 " {}".format(param_hint) if param_hint else "",154 ". " if msg else ".",155 msg or "",156 )157158 def __str__(self):159 if self.message is None:160 param_name = self.param.name if self.param else None161 return "missing parameter: {}".format(param_name)162 else:163 return self.message164165 if PY2:166 __unicode__ = __str__167168 def __str__(self):169 return self.__unicode__().encode("utf-8")170171172class NoSuchOption(UsageError):173 """Raised if click attempted to handle an option that does not174 exist.175176 .. versionadded:: 4.0177 """178179 def __init__(self, option_name, message=None, possibilities=None, ctx=None):180 if message is None:181 message = "no such option: {}".format(option_name)182 UsageError.__init__(self, message, ctx)183 self.option_name = option_name184 self.possibilities = possibilities185186 def format_message(self):187 bits = [self.message]188 if self.possibilities:189 if len(self.possibilities) == 1:190 bits.append("Did you mean {}?".format(self.possibilities[0]))191 else:192 possibilities = sorted(self.possibilities)193 bits.append("(Possible options: {})".format(", ".join(possibilities)))194 return " ".join(bits)195196197class BadOptionUsage(UsageError):198 """Raised if an option is generally supplied but the use of the option199 was incorrect. This is for instance raised if the number of arguments200 for an option is not correct.201202 .. versionadded:: 4.0203204 :param option_name: the name of the option being used incorrectly.205 """206207 def __init__(self, option_name, message, ctx=None):208 UsageError.__init__(self, message, ctx)209 self.option_name = option_name210211212class BadArgumentUsage(UsageError):213 """Raised if an argument is generally supplied but the use of the argument214 was incorrect. This is for instance raised if the number of values215 for an argument is not correct.216217 .. versionadded:: 6.0218 """219220 def __init__(self, message, ctx=None):221 UsageError.__init__(self, message, ctx)222223224class FileError(ClickException):225 """Raised if a file cannot be opened."""226227 def __init__(self, filename, hint=None):228 ui_filename = filename_to_ui(filename)229 if hint is None:230 hint = "unknown error"231 ClickException.__init__(self, hint)232 self.ui_filename = ui_filename233 self.filename = filename234235 def format_message(self):236 return "Could not open file {}: {}".format(self.ui_filename, self.message)237238239class Abort(RuntimeError):240 """An internal signalling exception that signals Click to abort."""241242243class Exit(RuntimeError):244 """An exception that indicates that the application should exit with some245 status code.246247 :param code: the status code to exit with.248 """249250 __slots__ = ("exit_code",)251252 def __init__(self, code=0):253 self.exit_code = code