exceptions.py 9.4 KB

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