exceptions.py 9.0 KB

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