Coverage for typer / _param_types.py: 100%

212 statements  

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

1import os 1abcdefghij

2import stat 1abcdefghij

3from collections.abc import Sequence 1abcdefghij

4from datetime import datetime 1abcdefghij

5from enum import Enum 1abcdefghij

6from pathlib import Path 1abcdefghij

7from typing import IO, TYPE_CHECKING, Any, TypeAlias, cast 1abcdefghij

8from uuid import UUID 1abcdefghij

9 

10from ._click import Context 1abcdefghij

11from ._click._compat import open_stream 1abcdefghij

12from ._click.exceptions import BadParameter 1abcdefghij

13from ._click.utils import ( 1abcdefghij

14 LazyFile, 

15 _escape_control_characters, 

16 format_filename, 

17 safecall, 

18) 

19from ._display import get_error_msg 1abcdefghij

20from ._typing import ( 1abcdefghij

21 get_args, 

22 get_origin, 

23 is_literal_type, 

24 is_number_type, 

25 is_union, 

26 literal_values, 

27) 

28from .models import ( 1abcdefghij

29 AnyType, 

30 FileBinaryRead, 

31 FileBinaryWrite, 

32 FileText, 

33 FileTextWrite, 

34 NoneType, 

35 ParameterInfo, 

36 ParamMeta, 

37) 

38 

39if TYPE_CHECKING: 1abcdefghij

40 from .core import _TyperParameter 

41 

42ParameterAnnotation: TypeAlias = Any 1abcdefghij

43 

44 

45def lenient_issubclass(cls: Any, class_or_tuple: AnyType | tuple[AnyType, ...]) -> bool: 1abcdefghij

46 return isinstance(cls, type) and issubclass(cls, class_or_tuple) 1abcdefghij

47 

48 

49def validate_annotation_structure(annotation: Any) -> None: 1abcdefghij

50 """Raise on invalid nested CLI annotations (developer errors).""" 

51 origin = get_origin(annotation) 1abcdefghij

52 if origin is list: 1abcdefghij

53 args = get_args(annotation) 1abcdefghij

54 if len(args) != 1: 1abcdefghij

55 raise ValueError(f"Expected one list item type, got: {args!r}") 1abcdefghij

56 validate_annotation_structure(args[0]) 1abcdefghij

57 elif origin is tuple: 1abcdefghij

58 for item_type in get_args(annotation): 1abcdefghij

59 validate_annotation_structure(item_type) 1abcdefghij

60 

61 

62def infer_annotation_from_default(default: Any | None) -> ParameterAnnotation: 1abcdefghij

63 """Infer a normalized annotation from a default value.""" 

64 if default is None: 1abcdefghij

65 return str 1abcdefghij

66 if isinstance(default, tuple) and len(default) > 0: 1abcdefghij

67 if not isinstance(default[0], (tuple, list)): 1abcdefghij

68 return tuple.__class_getitem__(tuple(map(type, default))) 1abcdefghij

69 if isinstance(default, (tuple, list)): 1abcdefghij

70 if not default: 1abcdefghij

71 return str 1abcdefghij

72 item = default[0] 1abcdefghij

73 if isinstance(item, (tuple, list)): 1abcdefghij

74 return tuple.__class_getitem__(tuple(map(type, item))) 1abcdefghij

75 return type(item) 1abcdefghij

76 return type(default) 1abcdefghij

77 

78 

79def annotation_from_prompt( 1abcdefghij

80 param_type: Any | None, default: Any | None 

81) -> ParameterAnnotation: 

82 if param_type is not None: 1abcdefghij

83 return param_type 1abcdefghij

84 return infer_annotation_from_default(default) 1abcdefghij

85 

86 

87def parse_param_annotation( 1abcdefghij

88 param: ParamMeta, default: Any | None 

89) -> ParameterAnnotation: 

90 """Parse the annotation for a callback parameter.""" 

91 if param.annotation is not param.empty: 1abcdefghij

92 main_type = param.annotation 1abcdefghij

93 origin = get_origin(main_type) 1abcdefghij

94 

95 if origin is not None: 1abcdefghij

96 if is_union(origin): 1abcdefghij

97 types = [] 1abcdefghij

98 for type_ in get_args(main_type): 1abcdefghij

99 if type_ is NoneType: 1abcdefghij

100 continue 1abcdefghij

101 types.append(type_) 1abcdefghij

102 assert len(types) == 1, "Typer currently doesn't support Union types" 1abcdefghij

103 main_type = types[0] 1abcdefghij

104 origin = get_origin(main_type) 1abcdefghij

105 

106 if lenient_issubclass(origin, list): 1abcdefghij

107 element_type = get_args(main_type)[0] 1abcdefghij

108 assert not get_origin(element_type), ( 1abcdefghij

109 "List types with complex sub-types are not currently supported" 

110 ) 

111 return main_type 1abcdefghij

112 if lenient_issubclass(origin, tuple): 1abcdefghij

113 type_args = get_args(main_type) 1abcdefghij

114 for type_ in type_args: 1abcdefghij

115 assert not get_origin(type_), ( 1abcdefghij

116 "Tuple types with complex sub-types are not currently supported" 

117 ) 

118 return main_type 1abcdefghij

119 return main_type 1abcdefghij

120 return main_type 1abcdefghij

121 return infer_annotation_from_default(default) 1abcdefghij

122 

123 

124# ENUM # 

125def normalize_choice_value( 1abcdefghij

126 choice: Any, 

127 case_sensitive: bool, 

128 ctx: Context | None, 

129) -> str: 

130 normed_value = choice_as_str(choice) 1abcdefghij

131 if ctx is not None and ctx.token_normalize_func is not None: 1abcdefghij

132 normed_value = ctx.token_normalize_func(normed_value) 1abcdefghij

133 if not case_sensitive: 1abcdefghij

134 normed_value = normed_value.casefold() 1abcdefghij

135 return normed_value 1abcdefghij

136 

137 

138def coerce_cli_choice( 1abcdefghij

139 value: Any, 

140 *, 

141 choices: Sequence[Any], 

142 case_sensitive: bool, 

143 ctx: Context | None = None, 

144) -> Any: 

145 if any(isinstance(choice, Enum) and value is choice for choice in choices): 1abcdefghij

146 return value 1abcdefghij

147 normalized_mapping = { 1abcdefghij

148 c: normalize_choice_value(c, case_sensitive, ctx) for c in choices 

149 } 

150 normed_value = normalize_choice_value(value, case_sensitive, ctx) 1abcdefghij

151 for original, normalized in normalized_mapping.items(): 1abcdefghij

152 if normalized == normed_value: 1abcdefghij

153 return original 1abcdefghij

154 choices_str = ", ".join(map(repr, normalized_mapping.values())) 1abcdefghij

155 raise ValueError(f"{value!r} is not one of {choices_str}.") 1abcdefghij

156 

157 

158def choice_coercion_annotation( 1abcdefghij

159 annotation: Any, 

160 parameter_info: ParameterInfo, 

161) -> tuple[tuple[Any, ...], bool] | None: 

162 if lenient_issubclass(annotation, Enum): 1abcdefghij

163 return tuple(annotation), parameter_info.case_sensitive 1abcdefghij

164 if is_literal_type(annotation): 1abcdefghij

165 return literal_values(annotation), parameter_info.case_sensitive 1abcdefghij

166 return None 1abcdefghij

167 

168 

169def choice_as_str(choice: Any) -> str: 1abcdefghij

170 if isinstance(choice, Enum): 1abcdefghij

171 return str(choice.value) 1abcdefghij

172 return str(choice) 1abcdefghij

173 

174 

175# PATH # 

176def routes_to_path(annotation: Any, parameter_info: ParameterInfo) -> bool: 1abcdefghij

177 """Defined as such for bwd-compat behaviour""" 

178 if parameter_info.parser is not None: 1abcdefghij

179 return False 1abcdefghij

180 if get_origin(annotation) is not None: 1abcdefghij

181 return False 1abcdefghij

182 if lenient_issubclass(annotation, Path): 1abcdefghij

183 return True 1abcdefghij

184 if annotation in (str, bool, datetime, UUID) or is_number_type(annotation): 1abcdefghij

185 return False 1abcdefghij

186 return _path_options_requested(parameter_info) 1abcdefghij

187 

188 

189def _path_options_requested(parameter_info: ParameterInfo) -> bool: 1abcdefghij

190 """Defined as such for bwd-compat behaviour""" 

191 return ( 1abcdefghij

192 parameter_info.allow_dash 

193 or parameter_info.path_type is not None 

194 or parameter_info.resolve_path 

195 ) 

196 

197 

198def path_type_name(parameter_info: ParameterInfo) -> str: 1abcdefghij

199 if parameter_info.file_okay and not parameter_info.dir_okay: 1abcdefghij

200 return "file" 1abcdefghij

201 if parameter_info.dir_okay and not parameter_info.file_okay: 1abcdefghij

202 return "dir" 1abcdefghij

203 return "path" 1abcdefghij

204 

205 

206def _coerce_path_result( 1abcdefghij

207 value: str | os.PathLike[str], 

208 path_type: type[Any] | None, 

209) -> str | bytes | os.PathLike[str]: 

210 if path_type is not None and not isinstance(value, path_type): 1abcdefghij

211 if path_type is bytes: 1abcdefghij

212 return os.fsencode(value) 1abcdefghij

213 return cast("os.PathLike[str]", path_type(value)) 1abcdefghij

214 return value 1abcdefghij

215 

216 

217def coerce_cli_path( 1abcdefghij

218 value: str | os.PathLike[str], 

219 parameter_info: ParameterInfo, 

220 *, 

221 path_type: type[Any] | None, 

222 param: "_TyperParameter | None" = None, 

223 ctx: Context | None = None, 

224) -> str | bytes | os.PathLike[str] | Path: 

225 if path_type is None or path_type is str or path_type is bytes: 1abcdefghij

226 rv: Any = value 1abcdefghij

227 else: 

228 assert lenient_issubclass(path_type, Path) 1abcdefghij

229 if isinstance(value, path_type): 1abcdefghij

230 rv = value 1abcdefghij

231 else: 

232 from pydantic import TypeAdapter, ValidationError 1abcdefghij

233 

234 from ._adapters import disabled_pydantic_plugins 1abcdefghij

235 

236 try: 1abcdefghij

237 with disabled_pydantic_plugins(): 1abcdefghij

238 adapter = TypeAdapter(path_type) 1abcdefghij

239 rv = adapter.validate_python(value) 1abcdefghij

240 except ValidationError as exc: 1abcdefghij

241 raise BadParameter(get_error_msg(exc), ctx=ctx, param=param) from exc 1abcdefghij

242 

243 is_dash = ( 1abcdefghij

244 parameter_info.file_okay and parameter_info.allow_dash and rv in (b"-", "-") 

245 ) 

246 

247 if not is_dash: 1abcdefghij

248 if parameter_info.resolve_path: 1abcdefghij

249 rv = os.path.realpath(rv) 1abcdefghij

250 

251 label = path_type_name(parameter_info) 1abcdefghij

252 try: 1abcdefghij

253 st = os.stat(rv) 1abcdefghij

254 except OSError: 1abcdefghij

255 if not parameter_info.exists: 1abcdefghij

256 return _coerce_path_result(rv, path_type) 1abcdefghij

257 raise BadParameter( 1abcdefghij

258 f"{label} {format_filename(value)!r} does not exist.", 

259 ctx=ctx, 

260 param=param, 

261 ) from None 

262 

263 loc = repr(format_filename(value)) 1abcdefghij

264 if not parameter_info.file_okay and stat.S_ISREG(st.st_mode): 1abcdefghij

265 raise BadParameter(f"{label} {loc} is a file.", ctx=ctx, param=param) 1abcdefghij

266 

267 if not parameter_info.dir_okay and stat.S_ISDIR(st.st_mode): 1abcdefghij

268 raise BadParameter(f"{label} {loc} is a directory.", ctx=ctx, param=param) 1abcdefghij

269 

270 if parameter_info.readable and not os.access(rv, os.R_OK): 1abcdefghij

271 raise BadParameter(f"{label} {loc} is not readable.", ctx=ctx, param=param) 1abcdefghij

272 

273 if parameter_info.writable and not os.access(rv, os.W_OK): 1abcdefghij

274 raise BadParameter(f"{label} {loc} is not writable.", ctx=ctx, param=param) 1abcdefghij

275 

276 return _coerce_path_result(rv, path_type) 1abcdefghij

277 

278 

279# FILE # 

280CLI_FILE_TYPES = (FileTextWrite, FileText, FileBinaryRead, FileBinaryWrite) 1abcdefghij

281 

282 

283def is_file_annotation(annotation: Any) -> bool: 1abcdefghij

284 return lenient_issubclass(annotation, CLI_FILE_TYPES) 1abcdefghij

285 

286 

287def file_coercion_annotation(annotation: Any) -> Any | None: 1abcdefghij

288 """Return the file marker type when this parameter opens files.""" 

289 origin = get_origin(annotation) 1abcdefghij

290 if origin is list: 1abcdefghij

291 args = get_args(annotation) 1abcdefghij

292 if args and all(is_file_annotation(arg) for arg in args): 1abcdefghij

293 return args[0] 1abcdefghij

294 return None 1abcdefghij

295 if origin is tuple: 1abcdefghij

296 args = get_args(annotation) 1abcdefghij

297 if args and any(is_file_annotation(arg) for arg in args): 1abcdefghij

298 return args 1abcdefghij

299 return None 1abcdefghij

300 if is_file_annotation(annotation): 1abcdefghij

301 return annotation 1abcdefghij

302 return None 1abcdefghij

303 

304 

305def resolve_file_mode(parameter_info: ParameterInfo, annotation: Any) -> str: 1abcdefghij

306 if parameter_info.mode is not None: 1abcdefghij

307 return parameter_info.mode 1abcdefghij

308 if lenient_issubclass(annotation, FileBinaryWrite): 1abcdefghij

309 return "wb" 1abcdefghij

310 if lenient_issubclass(annotation, FileTextWrite): 1abcdefghij

311 return "w" 1abcdefghij

312 if lenient_issubclass(annotation, FileBinaryRead): 1abcdefghij

313 return "rb" 1abcdefghij

314 return "r" 1abcdefghij

315 

316 

317def _open_cli_file( 1abcdefghij

318 value: str | os.PathLike[str] | IO[Any], 

319 parameter_info: ParameterInfo, 

320 *, 

321 mode: str, 

322 param: "_TyperParameter | None" = None, 

323 ctx: Context | None = None, 

324) -> IO[Any]: 

325 if hasattr(value, "read") or hasattr(value, "write"): 1abcdefghij

326 return cast("IO[Any]", value) 1abcdefghij

327 

328 path: str | os.PathLike[str] = value 1abcdefghij

329 

330 try: 1abcdefghij

331 lazy = parameter_info.lazy 1abcdefghij

332 if lazy is None: 1abcdefghij

333 if os.fspath(path) == "-": 1abcdefghij

334 lazy = False 1abcdefghij

335 elif "w" in mode: 1abcdefghij

336 lazy = True 1abcdefghij

337 else: 

338 lazy = False 1abcdefghij

339 

340 if lazy: 1abcdefghij

341 lf = LazyFile( 1abcdefghij

342 path, 

343 mode, 

344 parameter_info.encoding, 

345 parameter_info.errors, 

346 atomic=parameter_info.atomic, 

347 ) 

348 

349 if ctx is not None: 1abcdefghij

350 ctx.call_on_close(lf.close_intelligently) 1abcdefghij

351 

352 return cast("IO[Any]", lf) 1abcdefghij

353 

354 f, should_close = open_stream( 1abcdefghij

355 path, 

356 mode, 

357 parameter_info.encoding, 

358 parameter_info.errors, 

359 atomic=parameter_info.atomic, 

360 ) 

361 

362 if ctx is not None: 1abcdefghij

363 if should_close: 1abcdefghij

364 ctx.call_on_close(safecall(f.close)) 1abcdefghij

365 else: 

366 ctx.call_on_close(safecall(f.flush)) 1abcdefghij

367 

368 return f 1abcdefghij

369 except OSError as exc: 1abcdefghij

370 filename = _escape_control_characters(format_filename(path)) 1abcdefghij

371 raise BadParameter( 1abcdefghij

372 f"'{filename}': {exc.strerror}", ctx=ctx, param=param 

373 ) from exc