Coverage for typer / _adapters.py: 100%
154 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-11-18 11:12 +0000
« prev ^ index » next coverage.py v7.13.1, created at 2026-11-18 11:12 +0000
1import os 1abcdefghij
2import sys 1abcdefghij
3from collections.abc import Generator, Sequence 1abcdefghij
4from contextlib import contextmanager 1abcdefghij
5from datetime import datetime 1abcdefghij
6from enum import Enum 1abcdefghij
7from pathlib import Path 1abcdefghij
8from typing import TYPE_CHECKING, Annotated, Any, get_args, get_origin 1abcdefghij
10from pydantic import AfterValidator, BeforeValidator, Field, TypeAdapter, ValidationInfo 1abcdefghij
11from pydantic.errors import PydanticSchemaGenerationError 1abcdefghij
13from ._click import _compat 1abcdefghij
14from ._param_types import ( 1abcdefghij
15 coerce_cli_choice,
16 coerce_cli_path,
17 lenient_issubclass,
18 routes_to_path,
19 validate_annotation_structure,
20)
21from ._typing import is_literal_type, is_number_type, literal_values 1abcdefghij
22from .models import ParameterInfo 1abcdefghij
24if TYPE_CHECKING: 1abcdefghij
25 from ._click import Context
26 from .core import _TyperParameter
28_CTX_KEY = "ctx" 1abcdefghij
29_PARAM_KEY = "param" 1abcdefghij
32def validation_context( 1abcdefghij
33 ctx: "Context",
34 param: "_TyperParameter",
35) -> dict[str, Any]:
36 return {_CTX_KEY: ctx, _PARAM_KEY: param} 1abcdefghij
39def validation_ctx_param( 1abcdefghij
40 info: ValidationInfo,
41) -> tuple["Context | None", "_TyperParameter | None"]:
42 context = info.context 1abcdefghij
43 if not context: 1abcdefghij
44 return None, None 1abcdefghij
45 return context.get(_CTX_KEY), context.get(_PARAM_KEY) 1abcdefghij
48@contextmanager 1abcdefghij
49def disabled_pydantic_plugins() -> Generator[None, None, None]: 1abcdefghij
50 """Disable Pydantic plugin loading while building TypeAdapters."""
51 previous = os.environ.get("PYDANTIC_DISABLE_PLUGINS") 1abcdefghij
52 os.environ["PYDANTIC_DISABLE_PLUGINS"] = "1" 1abcdefghij
53 try: 1abcdefghij
54 yield 1abcdefghij
55 finally:
56 if previous is None: 1abcdefghij
57 del os.environ["PYDANTIC_DISABLE_PLUGINS"] 1abcdefghij
58 else:
59 os.environ["PYDANTIC_DISABLE_PLUGINS"] = previous 1abcdefghij
62def try_build_adapter( 1abcdefghij
63 annotation: Any, parameter_info: ParameterInfo
64) -> TypeAdapter[Any] | None:
65 """Build a TypeAdapter when Pydantic can schema-generate the annotation."""
66 with disabled_pydantic_plugins(): 1abcdefghij
67 try: 1abcdefghij
68 return build_adapter(annotation, parameter_info) 1abcdefghij
69 except PydanticSchemaGenerationError: 1abcdefghij
70 return None 1abcdefghij
73def build_adapter(annotation: Any, parameter_info: ParameterInfo) -> TypeAdapter[Any]: 1abcdefghij
74 """Build a Pydantic TypeAdapter for a parameter annotation and metadata.
75 Check for list/tuple and call this function recursively.
76 Otherwise, delegate to build_leaf_adapter.
77 """
78 origin = get_origin(annotation) 1abcdefghij
79 if origin is list: 1abcdefghij
80 validate_annotation_structure(annotation) 1abcdefghij
81 list_type = get_args(annotation)[0] 1abcdefghij
82 adapter = build_adapter(list_type, parameter_info) 1abcdefghij
84 def parse_list(value: Any, info: ValidationInfo) -> list[Any]: 1abcdefghij
85 if not isinstance(value, (list, tuple)): 1abcdefghij
86 value = [value] 1abcdefghij
87 context = info.context 1abcdefghij
88 return [adapter.validate_python(item, context=context) for item in value] 1abcdefghij
90 return TypeAdapter(Annotated[list[Any], BeforeValidator(parse_list)]) 1abcdefghij
92 if origin is tuple: 1abcdefghij
93 types = get_args(annotation) 1abcdefghij
94 adapters = [build_adapter(t, parameter_info) for t in types] 1abcdefghij
96 def parse_tuple(value: Any, info: ValidationInfo) -> tuple[Any, ...]: 1abcdefghij
97 if not isinstance(value, (list, tuple)): 1abcdefghij
98 raise ValueError("value is not a valid tuple") 1abcdefghij
99 if len(value) != len(adapters): 1abcdefghij
100 raise ValueError( 1abcdefghij
101 f"{len(adapters)} values are required, but {len(value)} given."
102 )
103 context = info.context 1abcdefghij
104 return tuple( 1abcdefghij
105 adapter.validate_python(item, context=context)
106 for adapter, item in zip(adapters, value, strict=False)
107 )
109 return TypeAdapter(Annotated[tuple[Any, ...], BeforeValidator(parse_tuple)]) 1abcdefghij
111 return build_leaf_adapter(annotation, parameter_info=parameter_info) 1abcdefghij
114def build_leaf_adapter( 1abcdefghij
115 annotation: Any, parameter_info: ParameterInfo
116) -> TypeAdapter[Any]:
117 """Build a Pydantic TypeAdapter for a leaf CLI annotation and constraints."""
118 if parameter_info.parser is not None: 1abcdefghij
119 parser = parameter_info.parser 1abcdefghij
121 # We need this because Pydantic would otherwise reject a callable class
122 def parse(value: Any) -> Any: 1abcdefghij
123 return parser(value) 1abcdefghij
125 return TypeAdapter(Annotated[Any, BeforeValidator(parse)]) 1abcdefghij
127 if lenient_issubclass(annotation, Enum): 1abcdefghij
128 case_sensitive = parameter_info.case_sensitive 1abcdefghij
129 return _build_choice_adapter( 1abcdefghij
130 list(annotation),
131 case_sensitive=case_sensitive,
132 )
134 if is_literal_type(annotation): 1abcdefghij
135 case_sensitive = parameter_info.case_sensitive 1abcdefghij
136 return _build_choice_adapter( 1abcdefghij
137 literal_values(annotation),
138 case_sensitive=case_sensitive,
139 )
141 if annotation is datetime: 1abcdefghij
142 return _build_datetime_adapter(parameter_info.formats) 1abcdefghij
144 if is_number_type(annotation): 1abcdefghij
145 return _build_number_adapter( 1abcdefghij
146 annotation,
147 min=parameter_info.min,
148 max=parameter_info.max,
149 clamp=parameter_info.clamp,
150 )
152 if annotation is bool: 1abcdefghij
153 return TypeAdapter(Annotated[bool, BeforeValidator(_parse_cli_bool)]) 1abcdefghij
155 if annotation is str: 1abcdefghij
156 return TypeAdapter(Annotated[str, BeforeValidator(_parse_cli_str)]) 1abcdefghij
158 # After concrete types: Path, or any fall-through type with path flags
159 if routes_to_path(annotation, parameter_info): 1abcdefghij
160 return _build_path_adapter(annotation, parameter_info) 1abcdefghij
162 return TypeAdapter(annotation) 1abcdefghij
165# DATE #
166def _build_datetime_adapter(formats: Sequence[str] | None) -> TypeAdapter[datetime]: 1abcdefghij
167 if formats is None: 1abcdefghij
168 return TypeAdapter(datetime) 1abcdefghij
170 def parse_datetime(value: Any) -> datetime: 1abcdefghij
171 if isinstance(value, datetime): 1abcdefghij
172 return value 1abcdefghij
173 for format in formats: 1abcdefghij
174 try: 1abcdefghij
175 return datetime.strptime(value, format) 1abcdefghij
176 except ValueError: 1abcdefghij
177 continue 1abcdefghij
178 formats_str = ", ".join(map(repr, formats)) 1abcdefghij
179 raise ValueError(f"{value!r} does not match the formats {formats_str}.") 1abcdefghij
181 return TypeAdapter(Annotated[datetime, BeforeValidator(parse_datetime)]) 1abcdefghij
184# STRING / BYTES #
185def _parse_cli_str(value: Any) -> str: 1abcdefghij
186 """Coerce a CLI value to str"""
187 if value is None: 1abcdefghij
188 raise ValueError("None is not a valid string") 1abcdefghij
189 if isinstance(value, bytes): 1abcdefghij
190 enc = _compat._get_argv_encoding() 1abcdefghij
191 try: 1abcdefghij
192 return value.decode(enc) 1abcdefghij
193 except UnicodeError: 1abcdefghij
194 fs_enc = sys.getfilesystemencoding() 1abcdefghij
195 if fs_enc != enc: 1abcdefghij
196 try: 1abcdefghij
197 return value.decode(fs_enc) 1abcdefghij
198 except UnicodeError: 1abcdefghij
199 return value.decode("utf-8", "replace") 1abcdefghij
200 return value.decode("utf-8", "replace") 1abcdefghij
201 return str(value) 1abcdefghij
204# BOOL #
205def _parse_cli_bool(value: Any) -> Any: 1abcdefghij
206 if not isinstance(value, str): 1abcdefghij
207 return value 1abcdefghij
209 stripped = value.strip() 1abcdefghij
210 if stripped == "": 1abcdefghij
211 return False 1abcdefghij
212 return stripped 1abcdefghij
215# NUMBER #
216def _build_number_adapter( 1abcdefghij
217 number_class: type[Any], *, min: float | None, max: float | None, clamp: bool | None
218) -> TypeAdapter[Any]:
219 if clamp: 1abcdefghij
221 def clamp_number(value: Any) -> Any: 1abcdefghij
222 if min is not None and value < min: 1abcdefghij
223 return number_class(min) 1abcdefghij
224 if max is not None and value > max: 1abcdefghij
225 return number_class(max) 1abcdefghij
226 return value 1abcdefghij
228 # Use AfterValidator so it runs after coercion
229 clamped_type: Any = Annotated[number_class, AfterValidator(clamp_number)] # ty: ignore[invalid-type-form] 1abcdefghij
230 return TypeAdapter(clamped_type) 1abcdefghij
231 else:
232 field_kwargs: dict[str, Any] = {} 1abcdefghij
233 if min is not None: 1abcdefghij
234 field_kwargs["ge"] = min 1abcdefghij
235 if max is not None: 1abcdefghij
236 field_kwargs["le"] = max 1abcdefghij
237 if field_kwargs: 1abcdefghij
238 constrained_type: Any = Annotated[number_class, Field(**field_kwargs)] # ty: ignore[invalid-type-form] 1abcdefghij
239 return TypeAdapter(constrained_type) 1abcdefghij
240 return TypeAdapter(number_class) 1abcdefghij
243# CHOICE #
244def _build_choice_adapter( 1abcdefghij
245 choices: Sequence[Any],
246 *,
247 case_sensitive: bool,
248) -> TypeAdapter[Any]:
249 def parse_choice(value: Any, info: ValidationInfo) -> Any: 1abcdefghij
250 ctx, _ = validation_ctx_param(info) 1abcdefghij
251 return coerce_cli_choice( 1abcdefghij
252 value,
253 choices=choices,
254 case_sensitive=case_sensitive,
255 ctx=ctx,
256 )
258 return TypeAdapter(Annotated[Any, BeforeValidator(parse_choice)]) 1abcdefghij
261# PATH #
262def _build_path_adapter( 1abcdefghij
263 annotation: Any,
264 parameter_info: ParameterInfo,
265) -> TypeAdapter[Any]:
266 path_type = parameter_info.path_type 1abcdefghij
267 if path_type is None and lenient_issubclass(annotation, Path): 1abcdefghij
268 path_type = annotation 1abcdefghij
270 def parse_path(value: Any, info: ValidationInfo) -> Any: 1abcdefghij
271 ctx, param = validation_ctx_param(info) 1abcdefghij
272 return coerce_cli_path( 1abcdefghij
273 value,
274 parameter_info,
275 path_type=path_type,
276 param=param,
277 ctx=ctx,
278 )
280 return TypeAdapter(Annotated[Any, BeforeValidator(parse_path)]) 1abcdefghij