Coverage for typer / _click / exceptions.py: 100%

115 statements  

« prev     ^ index     » next       coverage.py v7.13.1, created at 2026-11-18 11:12 +0000

1from collections.abc import Sequence 1abcdefghij

2from typing import IO, TYPE_CHECKING, Any, Union 1abcdefghij

3 

4from ..exceptions import TyperException 1abcdefghij

5from ._compat import get_text_stderr 1abcdefghij

6from .globals import resolve_color_default 1abcdefghij

7from .utils import _escape_control_characters, echo, format_filename 1abcdefghij

8 

9if TYPE_CHECKING: 1abcdefghij

10 from ..core import _TyperParameter 

11 from .core import Command, Context 

12 

13 

14def _join_param_hints(param_hint: Sequence[str] | str | None) -> str | None: 1abcdefghij

15 if param_hint is not None and not isinstance(param_hint, str): 1abcdefghij

16 return " / ".join(repr(x) for x in param_hint) 1abcdefghij

17 

18 return param_hint 1abcdefghij

19 

20 

21class ClickException(TyperException): 1abcdefghij

22 """An exception that Click can handle and show to the user.""" 

23 

24 def __init__(self, message: str) -> None: 1abcdefghij

25 super().__init__(message) 1abcdefghij

26 # The context will be removed by the time we print the message, so cache 

27 # the color settings here to be used later on (in `show`) 

28 self.show_color: bool | None = resolve_color_default() 1abcdefghij

29 

30 def show(self, file: IO[Any] | None = None) -> None: 1abcdefghij

31 if file is None: 1abcdefghij

32 file = get_text_stderr() 1abcdefghij

33 

34 echo( 1abcdefghij

35 f"Error: {self.format_message()}", 

36 file=file, 

37 color=self.show_color, 

38 ) 

39 

40 

41class UsageError(ClickException): 1abcdefghij

42 """An internal exception that signals a usage error. This typically 

43 aborts any further handling. 

44 """ 

45 

46 exit_code = 2 1abcdefghij

47 

48 def __init__(self, message: str, ctx: Union["Context", None] = None) -> None: 1abcdefghij

49 super().__init__(message) 1abcdefghij

50 self.ctx = ctx 1abcdefghij

51 self.cmd: Command | None = self.ctx.command if self.ctx else None 1abcdefghij

52 

53 def show(self, file: IO[Any] | None = None) -> None: 1abcdefghij

54 if file is None: 1abcdefghij

55 file = get_text_stderr() 1abcdefghij

56 color = None 1abcdefghij

57 hint = "" 1abcdefghij

58 if ( 

59 self.ctx is not None 

60 and self.ctx.command.get_help_option(self.ctx) is not None 

61 ): 

62 command = self.ctx.command_path 1abcdefghij

63 option = self.ctx.help_option_names[0] 1abcdefghij

64 hint = f"Try '{command} {option}' for help.\n" 1abcdefghij

65 if self.ctx is not None: 1abcdefghij

66 color = self.ctx.color 1abcdefghij

67 echo(f"{self.ctx.get_usage()}\n{hint}", file=file, color=color) 1abcdefghij

68 echo( 1abcdefghij

69 f"Error: {self.format_message()}", 

70 file=file, 

71 color=color, 

72 ) 

73 

74 

75class BadParameter(UsageError): 1abcdefghij

76 """An exception that formats out a standardized error message for a 

77 bad parameter. This is useful when thrown from a callback or type as 

78 Click will attach contextual information to it (for instance, which 

79 parameter it is). 

80 """ 

81 

82 def __init__( 1abcdefghij

83 self, 

84 message: str, 

85 ctx: Union["Context", None] = None, 

86 param: Union["_TyperParameter", None] = None, 

87 param_hint: Sequence[str] | str | None = None, 

88 ) -> None: 

89 super().__init__(message, ctx) 1abcdefghij

90 self.param = param 1abcdefghij

91 self.param_hint = param_hint 1abcdefghij

92 

93 def format_message(self) -> str: 1abcdefghij

94 if self.param_hint is not None: 1abcdefghij

95 param_hint = self.param_hint 1abcdefghij

96 elif self.param is not None: 1abcdefghij

97 param_hint = self.param.get_error_hint() 1abcdefghij

98 else: 

99 return f"Invalid value: {self.message}" 1abcdefghij

100 

101 hint = _join_param_hints(param_hint) 1abcdefghij

102 return f"Invalid value for {hint}: {self.message}" 1abcdefghij

103 

104 

105class MissingParameter(BadParameter): 1abcdefghij

106 """Raised if click required an option or argument but it was not 

107 provided when invoking the script. 

108 """ 

109 

110 def __init__( 1abcdefghij

111 self, 

112 message: str | None = None, 

113 ctx: Union["Context", None] = None, 

114 param: Union["_TyperParameter", None] = None, 

115 param_hint: Sequence[str] | str | None = None, 

116 param_type: str | None = None, 

117 ) -> None: 

118 super().__init__(message or "", ctx, param, param_hint) 1abcdefghij

119 self.param_type = param_type 1abcdefghij

120 

121 def format_message(self) -> str: 1abcdefghij

122 if self.param_hint is not None: 1abcdefghij

123 param_hint: Sequence[str] | str | None = self.param_hint 1abcdefghij

124 elif self.param is not None: 1abcdefghij

125 param_hint = self.param.get_error_hint() 1abcdefghij

126 else: 

127 param_hint = None 1abcdefghij

128 

129 param_hint = _join_param_hints(param_hint) 1abcdefghij

130 param_hint = f" {param_hint}" if param_hint else "" 1abcdefghij

131 

132 param_type = self.param_type 1abcdefghij

133 if param_type is None and self.param is not None: 1abcdefghij

134 param_type = self.param.param_type_name 1abcdefghij

135 

136 msg = self.message 1abcdefghij

137 if self.param is not None: 1abcdefghij

138 from ..core import _TyperParameter 1abcdefghij

139 

140 assert isinstance(self.param, _TyperParameter) 1abcdefghij

141 msg_extra = self.param.get_missing_message(ctx=self.ctx) 1abcdefghij

142 if msg_extra: 1abcdefghij

143 if msg: 1abcdefghij

144 msg += f". {msg_extra}" 1abcdefghij

145 else: 

146 msg = msg_extra 1abcdefghij

147 

148 if msg: 1abcdefghij

149 return f"Missing {param_type}{param_hint}. {msg}" 1abcdefghij

150 

151 return f"Missing {param_type}{param_hint}." 1abcdefghij

152 

153 def __str__(self) -> str: 1abcdefghij

154 if not self.message: 1abcdefghij

155 param_name = self.param.name if self.param else None 1abcdefghij

156 return f"Missing parameter: {param_name}" 1abcdefghij

157 else: 

158 return self.message 1abcdefghij

159 

160 

161class NoSuchOption(UsageError): 1abcdefghij

162 """Raised if click attempted to handle an option that does not 

163 exist. 

164 """ 

165 

166 def __init__( 1abcdefghij

167 self, 

168 option_name: str, 

169 message: str | None = None, 

170 possibilities: Sequence[str] | None = None, 

171 ctx: Union["Context", None] = None, 

172 ) -> None: 

173 if message is None: 1abcdefghij

174 message = f"No such option: {_escape_control_characters(option_name)}" 1abcdefghij

175 

176 super().__init__(message, ctx) 1abcdefghij

177 self.option_name = option_name 1abcdefghij

178 self.possibilities = possibilities 1abcdefghij

179 

180 def format_message(self) -> str: 1abcdefghij

181 if not self.possibilities: 1abcdefghij

182 return self.message 1abcdefghij

183 

184 possibility_str = ", ".join(sorted(self.possibilities)) 1abcdefghij

185 suggest = f"(Possible options: {possibility_str})" 1abcdefghij

186 return f"{self.message} {suggest}" 1abcdefghij

187 

188 

189class BadOptionUsage(UsageError): 1abcdefghij

190 """Raised if an option is generally supplied but the use of the option 

191 was incorrect. This is for instance raised if the number of arguments 

192 for an option is not correct. 

193 """ 

194 

195 def __init__( 1abcdefghij

196 self, option_name: str, message: str, ctx: Union["Context", None] = None 

197 ) -> None: 

198 super().__init__(message, ctx) 1abcdefghij

199 self.option_name = option_name 1abcdefghij

200 

201 

202class BadArgumentUsage(UsageError): 1abcdefghij

203 """Raised if an argument is generally supplied but the use of the argument 

204 was incorrect. This is for instance raised if the number of values 

205 for an argument is not correct. 

206 """ 

207 

208 

209class NoArgsIsHelpError(UsageError): 1abcdefghij

210 def __init__(self, ctx: "Context") -> None: 1abcdefghij

211 self.ctx: Context 1abcdefghij

212 super().__init__(ctx.get_help(), ctx=ctx) 1abcdefghij

213 

214 def show(self, file: IO[Any] | None = None) -> None: 1abcdefghij

215 echo(self.format_message(), file=file, err=True, color=self.ctx.color) 1abcdefghij

216 

217 

218class FileError(ClickException): 1abcdefghij

219 """Raised if a file cannot be opened.""" 

220 

221 def __init__(self, filename: str, hint: str | None = None) -> None: 1abcdefghij

222 if hint is None: 1abcdefghij

223 hint = "unknown error" 1abcdefghij

224 

225 super().__init__(hint) 1abcdefghij

226 self.ui_filename: str = format_filename(filename) 1abcdefghij

227 self.filename = filename 1abcdefghij

228 

229 def format_message(self) -> str: 1abcdefghij

230 return f"Could not open file {self.ui_filename!r}: {self.message}" 1abcdefghij