exceptions.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. from ._compat import filename_to_ui
  2. from ._compat import get_text_stderr
  3. from ._compat import PY2
  4. from .utils import echo
  5. def _join_param_hints(param_hint):
  6. if isinstance(param_hint, (tuple, list)):
  7. return " / ".join(repr(x) for x in param_hint)
  8. return param_hint
  9. class ClickException(Exception):
  10. """An exception that Click can handle and show to the user."""
  11. #: The exit code for this exception
  12. exit_code = 1
  13. def __init__(self, message):
  14. ctor_msg = message
  15. if PY2:
  16. if ctor_msg is not None:
  17. ctor_msg = ctor_msg.encode("utf-8")
  18. Exception.__init__(self, ctor_msg)
  19. self.message = message
  20. def format_message(self):
  21. return self.message
  22. def __str__(self):
  23. return self.message
  24. if PY2:
  25. __unicode__ = __str__
  26. def __str__(self):
  27. return self.message.encode("utf-8")
  28. def show(self, file=None):
  29. if file is None:
  30. file = get_text_stderr()
  31. echo("Error: {}".format(self.format_message()), file=file)
  32. class UsageError(ClickException):
  33. """An internal exception that signals a usage error. This typically
  34. aborts any further handling.
  35. :param message: the error message to display.
  36. :param ctx: optionally the context that caused this error. Click will
  37. fill in the context automatically in some situations.
  38. """
  39. exit_code = 2
  40. def __init__(self, message, ctx=None):
  41. ClickException.__init__(self, message)
  42. self.ctx = ctx
  43. self.cmd = self.ctx.command if self.ctx else None
  44. def show(self, file=None):
  45. if file is None:
  46. file = get_text_stderr()
  47. color = None
  48. hint = ""
  49. if self.cmd is not None and self.cmd.get_help_option(self.ctx) is not None:
  50. hint = "Try '{} {}' for help.\n".format(
  51. self.ctx.command_path, self.ctx.help_option_names[0]
  52. )
  53. if self.ctx is not None:
  54. color = self.ctx.color
  55. echo("{}\n{}".format(self.ctx.get_usage(), hint), file=file, color=color)
  56. echo("Error: {}".format(self.format_message()), file=file, color=color)
  57. class BadParameter(UsageError):
  58. """An exception that formats out a standardized error message for a
  59. bad parameter. This is useful when thrown from a callback or type as
  60. Click will attach contextual information to it (for instance, which
  61. parameter it is).
  62. .. versionadded:: 2.0
  63. :param param: the parameter object that caused this error. This can
  64. be left out, and Click will attach this info itself
  65. if possible.
  66. :param param_hint: a string that shows up as parameter name. This
  67. can be used as alternative to `param` in cases
  68. where custom validation should happen. If it is
  69. a string it's used as such, if it's a list then
  70. each item is quoted and separated.
  71. """
  72. def __init__(self, message, ctx=None, param=None, param_hint=None):
  73. UsageError.__init__(self, message, ctx)
  74. self.param = param
  75. self.param_hint = param_hint
  76. def format_message(self):
  77. if self.param_hint is not None:
  78. param_hint = self.param_hint
  79. elif self.param is not None:
  80. param_hint = self.param.get_error_hint(self.ctx)
  81. else:
  82. return "Invalid value: {}".format(self.message)
  83. param_hint = _join_param_hints(param_hint)
  84. return "Invalid value for {}: {}".format(param_hint, self.message)
  85. class MissingParameter(BadParameter):
  86. """Raised if click required an option or argument but it was not
  87. provided when invoking the script.
  88. .. versionadded:: 4.0
  89. :param param_type: a string that indicates the type of the parameter.
  90. The default is to inherit the parameter type from
  91. the given `param`. Valid values are ``'parameter'``,
  92. ``'option'`` or ``'argument'``.
  93. """
  94. def __init__(
  95. self, message=None, ctx=None, param=None, param_hint=None, param_type=None
  96. ):
  97. BadParameter.__init__(self, message, ctx, param, param_hint)
  98. self.param_type = param_type
  99. def format_message(self):
  100. if self.param_hint is not None:
  101. param_hint = self.param_hint
  102. elif self.param is not None:
  103. param_hint = self.param.get_error_hint(self.ctx)
  104. else:
  105. param_hint = None
  106. param_hint = _join_param_hints(param_hint)
  107. param_type = self.param_type
  108. if param_type is None and self.param is not None:
  109. param_type = self.param.param_type_name
  110. msg = self.message
  111. if self.param is not None:
  112. msg_extra = self.param.type.get_missing_message(self.param)
  113. if msg_extra:
  114. if msg:
  115. msg += ". {}".format(msg_extra)
  116. else:
  117. msg = msg_extra
  118. return "Missing {}{}{}{}".format(
  119. param_type,
  120. " {}".format(param_hint) if param_hint else "",
  121. ". " if msg else ".",
  122. msg or "",
  123. )
  124. def __str__(self):
  125. if self.message is None:
  126. param_name = self.param.name if self.param else None
  127. return "missing parameter: {}".format(param_name)
  128. else:
  129. return self.message
  130. if PY2:
  131. __unicode__ = __str__
  132. def __str__(self):
  133. return self.__unicode__().encode("utf-8")
  134. class NoSuchOption(UsageError):
  135. """Raised if click attempted to handle an option that does not
  136. exist.
  137. .. versionadded:: 4.0
  138. """
  139. def __init__(self, option_name, message=None, possibilities=None, ctx=None):
  140. if message is None:
  141. message = "no such option: {}".format(option_name)
  142. UsageError.__init__(self, message, ctx)
  143. self.option_name = option_name
  144. self.possibilities = possibilities
  145. def format_message(self):
  146. bits = [self.message]
  147. if self.possibilities:
  148. if len(self.possibilities) == 1:
  149. bits.append("Did you mean {}?".format(self.possibilities[0]))
  150. else:
  151. possibilities = sorted(self.possibilities)
  152. bits.append("(Possible options: {})".format(", ".join(possibilities)))
  153. return " ".join(bits)
  154. class BadOptionUsage(UsageError):
  155. """Raised if an option is generally supplied but the use of the option
  156. was incorrect. This is for instance raised if the number of arguments
  157. for an option is not correct.
  158. .. versionadded:: 4.0
  159. :param option_name: the name of the option being used incorrectly.
  160. """
  161. def __init__(self, option_name, message, ctx=None):
  162. UsageError.__init__(self, message, ctx)
  163. self.option_name = option_name
  164. class BadArgumentUsage(UsageError):
  165. """Raised if an argument is generally supplied but the use of the argument
  166. was incorrect. This is for instance raised if the number of values
  167. for an argument is not correct.
  168. .. versionadded:: 6.0
  169. """
  170. def __init__(self, message, ctx=None):
  171. UsageError.__init__(self, message, ctx)
  172. class FileError(ClickException):
  173. """Raised if a file cannot be opened."""
  174. def __init__(self, filename, hint=None):
  175. ui_filename = filename_to_ui(filename)
  176. if hint is None:
  177. hint = "unknown error"
  178. ClickException.__init__(self, hint)
  179. self.ui_filename = ui_filename
  180. self.filename = filename
  181. def format_message(self):
  182. return "Could not open file {}: {}".format(self.ui_filename, self.message)
  183. class Abort(RuntimeError):
  184. """An internal signalling exception that signals Click to abort."""
  185. class Exit(RuntimeError):
  186. """An exception that indicates that the application should exit with some
  187. status code.
  188. :param code: the status code to exit with.
  189. """
  190. __slots__ = ("exit_code",)
  191. def __init__(self, code=0):
  192. self.exit_code = code