exceptions.py 9.1 KB

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