Coverage for src/debputy/manifest_parser/declarative_parser.py: 72%

800 statements  

« prev     ^ index     » next       coverage.py v7.6.0, created at 2025-01-27 13:59 +0000

1import collections 

2import dataclasses 

3import typing 

4from typing import ( 

5 Any, 

6 Callable, 

7 Tuple, 

8 TypedDict, 

9 Dict, 

10 get_type_hints, 

11 Annotated, 

12 get_args, 

13 get_origin, 

14 TypeVar, 

15 Generic, 

16 FrozenSet, 

17 Mapping, 

18 Optional, 

19 cast, 

20 Type, 

21 Union, 

22 List, 

23 Collection, 

24 NotRequired, 

25 Iterable, 

26 Literal, 

27 Sequence, 

28 Container, 

29) 

30 

31from debputy.lsp.diagnostics import LintSeverity 

32from debputy.manifest_parser.base_types import FileSystemMatchRule 

33from debputy.manifest_parser.exceptions import ( 

34 ManifestParseException, 

35) 

36from debputy.manifest_parser.mapper_code import ( 

37 normalize_into_list, 

38 wrap_into_list, 

39 map_each_element, 

40) 

41from debputy.manifest_parser.parse_hints import ( 

42 ConditionalRequired, 

43 DebputyParseHint, 

44 TargetAttribute, 

45 ManifestAttribute, 

46 ConflictWithSourceAttribute, 

47 NotPathHint, 

48) 

49from debputy.manifest_parser.parser_data import ParserContextData 

50from debputy.manifest_parser.tagging_types import ( 

51 DebputyParsedContent, 

52 DebputyDispatchableType, 

53 TypeMapping, 

54) 

55from debputy.manifest_parser.util import ( 

56 AttributePath, 

57 unpack_type, 

58 find_annotation, 

59 check_integration_mode, 

60) 

61from debputy.plugin.api.impl_types import ( 

62 DeclarativeInputParser, 

63 TD, 

64 ListWrappedDeclarativeInputParser, 

65 DispatchingObjectParser, 

66 DispatchingTableParser, 

67 TTP, 

68 TP, 

69 InPackageContextParser, 

70) 

71from debputy.plugin.api.spec import ( 

72 ParserDocumentation, 

73 DebputyIntegrationMode, 

74 StandardParserAttributeDocumentation, 

75 undocumented_attr, 

76 ParserAttributeDocumentation, 

77 reference_documentation, 

78) 

79from debputy.util import _info, _warn, assume_not_none 

80 

81if typing.TYPE_CHECKING: 81 ↛ 82line 81 didn't jump to line 82 because the condition on line 81 was never true

82 import lsprotocol.types as types 

83else: 

84 import debputy.lsprotocol.types as types 

85 

86try: 

87 from Levenshtein import distance 

88except ImportError: 

89 _WARN_ONCE = False 

90 

91 def _detect_possible_typo( 

92 _key: str, 

93 _value: object, 

94 _manifest_attributes: Mapping[str, "AttributeDescription"], 

95 _path: "AttributePath", 

96 ) -> None: 

97 global _WARN_ONCE 

98 if not _WARN_ONCE: 

99 _WARN_ONCE = True 

100 _info( 

101 "Install python3-levenshtein to have debputy try to detect typos in the manifest." 

102 ) 

103 

104else: 

105 

106 def _detect_possible_typo( 

107 key: str, 

108 value: object, 

109 manifest_attributes: Mapping[str, "AttributeDescription"], 

110 path: "AttributePath", 

111 ) -> None: 

112 k_len = len(key) 

113 key_path = path[key] 

114 matches: List[str] = [] 

115 current_match_strength = 0 

116 for acceptable_key, attr in manifest_attributes.items(): 

117 if abs(k_len - len(acceptable_key)) > 2: 

118 continue 

119 d = distance(key, acceptable_key) 

120 if d > 2: 

121 continue 

122 try: 

123 attr.type_validator.ensure_type(value, key_path) 

124 except ManifestParseException: 

125 if attr.type_validator.base_type_match(value): 

126 match_strength = 1 

127 else: 

128 match_strength = 0 

129 else: 

130 match_strength = 2 

131 

132 if match_strength < current_match_strength: 

133 continue 

134 if match_strength > current_match_strength: 

135 current_match_strength = match_strength 

136 matches.clear() 

137 matches.append(acceptable_key) 

138 

139 if not matches: 

140 return 

141 ref = f'at "{path.path}"' if path else "at the manifest root level" 

142 if len(matches) == 1: 

143 possible_match = repr(matches[0]) 

144 _warn( 

145 f'Possible typo: The key "{key}" {ref} should probably have been {possible_match}' 

146 ) 

147 else: 

148 matches.sort() 

149 possible_matches = ", ".join(repr(a) for a in matches) 

150 _warn( 

151 f'Possible typo: The key "{key}" {ref} should probably have been one of {possible_matches}' 

152 ) 

153 

154 

155SF = TypeVar("SF") 

156T = TypeVar("T") 

157S = TypeVar("S") 

158 

159 

160_NONE_TYPE = type(None) 

161 

162 

163# These must be able to appear in an "isinstance" check and must be builtin types. 

164BASIC_SIMPLE_TYPES = { 

165 str: "string", 

166 int: "integer", 

167 bool: "boolean", 

168} 

169 

170 

171class AttributeTypeHandler: 

172 __slots__ = ("_description", "_ensure_type", "base_type", "mapper") 

173 

174 def __init__( 

175 self, 

176 description: str, 

177 ensure_type: Callable[[Any, AttributePath], None], 

178 *, 

179 base_type: Optional[Type[Any]] = None, 

180 mapper: Optional[ 

181 Callable[[Any, AttributePath, Optional["ParserContextData"]], Any] 

182 ] = None, 

183 ) -> None: 

184 self._description = description 

185 self._ensure_type = ensure_type 

186 self.base_type = base_type 

187 self.mapper = mapper 

188 

189 def describe_type(self) -> str: 

190 return self._description 

191 

192 def ensure_type(self, obj: object, path: AttributePath) -> None: 

193 self._ensure_type(obj, path) 

194 

195 def base_type_match(self, obj: object) -> bool: 

196 base_type = self.base_type 

197 return base_type is not None and isinstance(obj, base_type) 

198 

199 def map_type( 

200 self, 

201 value: Any, 

202 path: AttributePath, 

203 parser_context: Optional["ParserContextData"], 

204 ) -> Any: 

205 mapper = self.mapper 

206 if mapper is not None: 

207 return mapper(value, path, parser_context) 

208 return value 

209 

210 def combine_mapper( 

211 self, 

212 mapper: Optional[ 

213 Callable[[Any, AttributePath, Optional["ParserContextData"]], Any] 

214 ], 

215 ) -> "AttributeTypeHandler": 

216 if mapper is None: 

217 return self 

218 if self.mapper is not None: 

219 m = self.mapper 

220 

221 def _combined_mapper( 

222 value: Any, 

223 path: AttributePath, 

224 parser_context: Optional["ParserContextData"], 

225 ) -> Any: 

226 return mapper(m(value, path, parser_context), path, parser_context) 

227 

228 else: 

229 _combined_mapper = mapper 

230 

231 return AttributeTypeHandler( 

232 self._description, 

233 self._ensure_type, 

234 base_type=self.base_type, 

235 mapper=_combined_mapper, 

236 ) 

237 

238 

239@dataclasses.dataclass(slots=True) 

240class AttributeDescription: 

241 source_attribute_name: str 

242 target_attribute: str 

243 attribute_type: Any 

244 type_validator: AttributeTypeHandler 

245 annotations: Tuple[Any, ...] 

246 conflicting_attributes: FrozenSet[str] 

247 conditional_required: Optional["ConditionalRequired"] 

248 parse_hints: Optional["DetectedDebputyParseHint"] = None 

249 is_optional: bool = False 

250 

251 

252def _extract_path_hint(v: Any, attribute_path: AttributePath) -> bool: 

253 if attribute_path.path_hint is not None: 253 ↛ 254line 253 didn't jump to line 254 because the condition on line 253 was never true

254 return True 

255 if isinstance(v, str): 

256 attribute_path.path_hint = v 

257 return True 

258 elif isinstance(v, list) and len(v) > 0 and isinstance(v[0], str): 

259 attribute_path.path_hint = v[0] 

260 return True 

261 return False 

262 

263 

264@dataclasses.dataclass(slots=True, frozen=True) 

265class DeclarativeNonMappingInputParser(DeclarativeInputParser[TD], Generic[TD, SF]): 

266 alt_form_parser: AttributeDescription 

267 inline_reference_documentation: Optional[ParserDocumentation] = None 

268 expected_debputy_integration_mode: Optional[Container[DebputyIntegrationMode]] = ( 

269 None 

270 ) 

271 

272 def parse_input( 

273 self, 

274 value: object, 

275 path: AttributePath, 

276 *, 

277 parser_context: Optional["ParserContextData"] = None, 

278 ) -> TD: 

279 check_integration_mode( 

280 path, 

281 parser_context, 

282 self.expected_debputy_integration_mode, 

283 ) 

284 if self.reference_documentation_url is not None: 

285 doc_ref = f" (Documentation: {self.reference_documentation_url})" 

286 else: 

287 doc_ref = "" 

288 

289 alt_form_parser = self.alt_form_parser 

290 if value is None: 290 ↛ 291line 290 didn't jump to line 291 because the condition on line 290 was never true

291 form_note = f" The value must have type: {alt_form_parser.type_validator.describe_type()}" 

292 if self.reference_documentation_url is not None: 

293 doc_ref = f" Please see {self.reference_documentation_url} for the documentation." 

294 raise ManifestParseException( 

295 f"The attribute {path.path} was missing a value. {form_note}{doc_ref}" 

296 ) 

297 _extract_path_hint(value, path) 

298 alt_form_parser.type_validator.ensure_type(value, path) 

299 attribute = alt_form_parser.target_attribute 

300 alias_mapping = { 

301 attribute: ("", None), 

302 } 

303 v = alt_form_parser.type_validator.map_type(value, path, parser_context) 

304 path.alias_mapping = alias_mapping 

305 return cast("TD", {attribute: v}) 

306 

307 

308@dataclasses.dataclass(slots=True) 

309class DeclarativeMappingInputParser(DeclarativeInputParser[TD], Generic[TD, SF]): 

310 input_time_required_parameters: FrozenSet[str] 

311 all_parameters: FrozenSet[str] 

312 manifest_attributes: Mapping[str, "AttributeDescription"] 

313 source_attributes: Mapping[str, "AttributeDescription"] 

314 at_least_one_of: FrozenSet[FrozenSet[str]] 

315 alt_form_parser: Optional[AttributeDescription] 

316 mutually_exclusive_attributes: FrozenSet[FrozenSet[str]] = frozenset() 

317 _per_attribute_conflicts_cache: Optional[Mapping[str, FrozenSet[str]]] = None 

318 inline_reference_documentation: Optional[ParserDocumentation] = None 

319 path_hint_source_attributes: Sequence[str] = tuple() 

320 expected_debputy_integration_mode: Optional[Container[DebputyIntegrationMode]] = ( 

321 None 

322 ) 

323 

324 def _parse_alt_form( 

325 self, 

326 value: object, 

327 path: AttributePath, 

328 *, 

329 parser_context: Optional["ParserContextData"] = None, 

330 ) -> TD: 

331 alt_form_parser = self.alt_form_parser 

332 if alt_form_parser is None: 332 ↛ 333line 332 didn't jump to line 333 because the condition on line 332 was never true

333 raise ManifestParseException( 

334 f"The attribute {path.path} must be a mapping.{self._doc_url_error_suffix()}" 

335 ) 

336 _extract_path_hint(value, path) 

337 alt_form_parser.type_validator.ensure_type(value, path) 

338 assert ( 

339 value is not None 

340 ), "The alternative form was None, but the parser should have rejected None earlier." 

341 attribute = alt_form_parser.target_attribute 

342 alias_mapping = { 

343 attribute: ("", None), 

344 } 

345 v = alt_form_parser.type_validator.map_type(value, path, parser_context) 

346 path.alias_mapping = alias_mapping 

347 return cast("TD", {attribute: v}) 

348 

349 def _validate_expected_keys( 

350 self, 

351 value: Dict[Any, Any], 

352 path: AttributePath, 

353 *, 

354 parser_context: Optional["ParserContextData"] = None, 

355 ) -> None: 

356 unknown_keys = value.keys() - self.all_parameters 

357 doc_ref = self._doc_url_error_suffix() 

358 if unknown_keys: 358 ↛ 359line 358 didn't jump to line 359 because the condition on line 358 was never true

359 for k in unknown_keys: 

360 if isinstance(k, str): 

361 _detect_possible_typo(k, value[k], self.manifest_attributes, path) 

362 unused_keys = self.all_parameters - value.keys() 

363 if unused_keys: 

364 k = ", ".join(unused_keys) 

365 raise ManifestParseException( 

366 f'Unknown keys "{unknown_keys}" at {path.path_container_lc}". Keys that could be used here are: {k}.{doc_ref}' 

367 ) 

368 raise ManifestParseException( 

369 f'Unknown keys "{unknown_keys}" at {path.path_container_lc}". Please remove them.{doc_ref}' 

370 ) 

371 missing_keys = self.input_time_required_parameters - value.keys() 

372 if missing_keys: 

373 required = ", ".join(repr(k) for k in sorted(missing_keys)) 

374 raise ManifestParseException( 

375 f"The following keys were required but not present at {path.path_container_lc}: {required}{doc_ref}" 

376 ) 

377 for maybe_required in self.all_parameters - value.keys(): 

378 attr = self.manifest_attributes[maybe_required] 

379 assert attr.conditional_required is None or parser_context is not None 

380 if ( 380 ↛ 386line 380 didn't jump to line 386

381 attr.conditional_required is not None 

382 and attr.conditional_required.condition_applies( 

383 assume_not_none(parser_context) 

384 ) 

385 ): 

386 reason = attr.conditional_required.reason 

387 raise ManifestParseException( 

388 f'Missing the *conditionally* required attribute "{maybe_required}" at {path.path_container_lc}. {reason}{doc_ref}' 

389 ) 

390 for keyset in self.at_least_one_of: 

391 matched_keys = value.keys() & keyset 

392 if not matched_keys: 392 ↛ 393line 392 didn't jump to line 393 because the condition on line 392 was never true

393 conditionally_required = ", ".join(repr(k) for k in sorted(keyset)) 

394 raise ManifestParseException( 

395 f"At least one of the following keys must be present at {path.path_container_lc}:" 

396 f" {conditionally_required}{doc_ref}" 

397 ) 

398 for group in self.mutually_exclusive_attributes: 

399 matched = value.keys() & group 

400 if len(matched) > 1: 400 ↛ 401line 400 didn't jump to line 401 because the condition on line 400 was never true

401 ck = ", ".join(repr(k) for k in sorted(matched)) 

402 raise ManifestParseException( 

403 f"Could not parse {path.path_container_lc}: The following attributes are" 

404 f" mutually exclusive: {ck}{doc_ref}" 

405 ) 

406 

407 def _parse_typed_dict_form( 

408 self, 

409 value: Dict[Any, Any], 

410 path: AttributePath, 

411 *, 

412 parser_context: Optional["ParserContextData"] = None, 

413 ) -> TD: 

414 self._validate_expected_keys(value, path, parser_context=parser_context) 

415 result = {} 

416 per_attribute_conflicts = self._per_attribute_conflicts() 

417 alias_mapping = {} 

418 for path_hint_source_attributes in self.path_hint_source_attributes: 

419 v = value.get(path_hint_source_attributes) 

420 if v is not None and _extract_path_hint(v, path): 

421 break 

422 for k, v in value.items(): 

423 attr = self.manifest_attributes[k] 

424 matched = value.keys() & per_attribute_conflicts[k] 

425 if matched: 425 ↛ 426line 425 didn't jump to line 426 because the condition on line 425 was never true

426 ck = ", ".join(repr(k) for k in sorted(matched)) 

427 raise ManifestParseException( 

428 f'The attribute "{k}" at {path.path} cannot be used with the following' 

429 f" attributes: {ck}{self._doc_url_error_suffix()}" 

430 ) 

431 nk = attr.target_attribute 

432 key_path = path[k] 

433 attr.type_validator.ensure_type(v, key_path) 

434 if v is None: 434 ↛ 435line 434 didn't jump to line 435 because the condition on line 434 was never true

435 continue 

436 if k != nk: 

437 alias_mapping[nk] = k, None 

438 v = attr.type_validator.map_type(v, key_path, parser_context) 

439 result[nk] = v 

440 if alias_mapping: 

441 path.alias_mapping = alias_mapping 

442 return cast("TD", result) 

443 

444 def _doc_url_error_suffix(self, *, see_url_version: bool = False) -> str: 

445 doc_url = self.reference_documentation_url 

446 if doc_url is not None: 

447 if see_url_version: 447 ↛ 448line 447 didn't jump to line 448 because the condition on line 447 was never true

448 return f" Please see {doc_url} for the documentation." 

449 return f" (Documentation: {doc_url})" 

450 return "" 

451 

452 def parse_input( 

453 self, 

454 value: object, 

455 path: AttributePath, 

456 *, 

457 parser_context: Optional["ParserContextData"] = None, 

458 ) -> TD: 

459 check_integration_mode( 

460 path, 

461 parser_context, 

462 self.expected_debputy_integration_mode, 

463 ) 

464 if value is None: 464 ↛ 465line 464 didn't jump to line 465 because the condition on line 464 was never true

465 form_note = " The attribute must be a mapping." 

466 if self.alt_form_parser is not None: 

467 form_note = ( 

468 " The attribute can be a mapping or a non-mapping format" 

469 ' (usually, "non-mapping format" means a string or a list of strings).' 

470 ) 

471 doc_ref = self._doc_url_error_suffix(see_url_version=True) 

472 raise ManifestParseException( 

473 f"The attribute {path.path} was missing a value. {form_note}{doc_ref}" 

474 ) 

475 

476 if not isinstance(value, dict): 

477 return self._parse_alt_form(value, path, parser_context=parser_context) 

478 return self._parse_typed_dict_form(value, path, parser_context=parser_context) 

479 

480 def _per_attribute_conflicts(self) -> Mapping[str, FrozenSet[str]]: 

481 conflicts = self._per_attribute_conflicts_cache 

482 if conflicts is not None: 

483 return conflicts 

484 attrs = self.source_attributes 

485 conflicts = { 

486 a.source_attribute_name: frozenset( 

487 attrs[ca].source_attribute_name for ca in a.conflicting_attributes 

488 ) 

489 for a in attrs.values() 

490 } 

491 self._per_attribute_conflicts_cache = conflicts 

492 return self._per_attribute_conflicts_cache 

493 

494 

495def _is_path_attribute_candidate( 

496 source_attribute: AttributeDescription, target_attribute: AttributeDescription 

497) -> bool: 

498 if ( 

499 source_attribute.parse_hints 

500 and not source_attribute.parse_hints.applicable_as_path_hint 

501 ): 

502 return False 

503 target_type = target_attribute.attribute_type 

504 _, origin, args = unpack_type(target_type, False) 

505 match_type = target_type 

506 if origin == list: 

507 match_type = args[0] 

508 return isinstance(match_type, type) and issubclass(match_type, FileSystemMatchRule) 

509 

510 

511if typing.is_typeddict(DebputyParsedContent): 511 ↛ 515line 511 didn't jump to line 515 because the condition on line 511 was always true

512 is_typeddict = typing.is_typeddict 

513else: 

514 

515 def is_typeddict(t: Any) -> bool: 

516 if typing.is_typeddict(t): 

517 return True 

518 return isinstance(t, type) and issubclass(t, DebputyParsedContent) 

519 

520 

521class ParserGenerator: 

522 def __init__(self) -> None: 

523 self._registered_types: Dict[Any, TypeMapping[Any, Any]] = {} 

524 self._object_parsers: Dict[str, DispatchingObjectParser] = {} 

525 self._table_parsers: Dict[ 

526 Type[DebputyDispatchableType], DispatchingTableParser[Any] 

527 ] = {} 

528 self._in_package_context_parser: Dict[str, Any] = {} 

529 

530 def register_mapped_type(self, mapped_type: TypeMapping[Any, Any]) -> None: 

531 existing = self._registered_types.get(mapped_type.target_type) 

532 if existing is not None: 532 ↛ 533line 532 didn't jump to line 533 because the condition on line 532 was never true

533 raise ValueError(f"The type {existing} is already registered") 

534 self._registered_types[mapped_type.target_type] = mapped_type 

535 

536 def get_mapped_type_from_target_type( 

537 self, 

538 mapped_type: Type[T], 

539 ) -> Optional[TypeMapping[Any, T]]: 

540 return self._registered_types.get(mapped_type) 

541 

542 def discard_mapped_type(self, mapped_type: Type[T]) -> None: 

543 del self._registered_types[mapped_type] 

544 

545 def add_table_parser(self, rt: Type[DebputyDispatchableType], path: str) -> None: 

546 assert rt not in self._table_parsers 

547 self._table_parsers[rt] = DispatchingTableParser(rt, path) 

548 

549 def add_object_parser( 

550 self, 

551 path: str, 

552 *, 

553 parser_documentation: Optional[ParserDocumentation] = None, 

554 expected_debputy_integration_mode: Optional[ 

555 Container[DebputyIntegrationMode] 

556 ] = None, 

557 unknown_keys_diagnostic_severity: Optional[LintSeverity] = "error", 

558 ) -> None: 

559 assert path not in self._in_package_context_parser 

560 assert path not in self._object_parsers 

561 self._object_parsers[path] = DispatchingObjectParser( 

562 path, 

563 parser_documentation=parser_documentation, 

564 expected_debputy_integration_mode=expected_debputy_integration_mode, 

565 unknown_keys_diagnostic_severity=unknown_keys_diagnostic_severity, 

566 ) 

567 

568 def add_in_package_context_parser( 

569 self, 

570 path: str, 

571 delegate: DeclarativeInputParser[Any], 

572 ) -> None: 

573 assert path not in self._in_package_context_parser 

574 assert path not in self._object_parsers 

575 self._in_package_context_parser[path] = InPackageContextParser(path, delegate) 

576 

577 @property 

578 def dispatchable_table_parsers( 

579 self, 

580 ) -> Mapping[Type[DebputyDispatchableType], DispatchingTableParser[Any]]: 

581 return self._table_parsers 

582 

583 @property 

584 def dispatchable_object_parsers(self) -> Mapping[str, DispatchingObjectParser]: 

585 return self._object_parsers 

586 

587 def dispatch_parser_table_for( 

588 self, rule_type: TTP 

589 ) -> Optional[DispatchingTableParser[TP]]: 

590 return cast( 

591 "Optional[DispatchingTableParser[TP]]", self._table_parsers.get(rule_type) 

592 ) 

593 

594 def generate_parser( 

595 self, 

596 parsed_content: Type[TD], 

597 *, 

598 source_content: Optional[SF] = None, 

599 allow_optional: bool = False, 

600 inline_reference_documentation: Optional[ParserDocumentation] = None, 

601 expected_debputy_integration_mode: Optional[ 

602 Container[DebputyIntegrationMode] 

603 ] = None, 

604 automatic_docs: Optional[ 

605 Mapping[Type[Any], Sequence[StandardParserAttributeDocumentation]] 

606 ] = None, 

607 ) -> DeclarativeInputParser[TD]: 

608 """Derive a parser from a TypedDict 

609 

610 Generates a parser for a segment of the manifest (think the `install-docs` snippet) from a TypedDict 

611 or two that are used as a description. 

612 

613 In its most simple use-case, the caller provides a TypedDict of the expected attributed along with 

614 their types. As an example: 

615 

616 >>> class InstallDocsRule(DebputyParsedContent): 

617 ... sources: List[str] 

618 ... into: List[str] 

619 >>> pg = ParserGenerator() 

620 >>> simple_parser = pg.generate_parser(InstallDocsRule) 

621 

622 This will create a parser that would be able to interpret something like: 

623 

624 ```yaml 

625 install-docs: 

626 sources: ["docs/*"] 

627 into: ["my-pkg"] 

628 ``` 

629 

630 While this is sufficient for programmers, it is a bit rigid for the packager writing the manifest. Therefore, 

631 you can also provide a TypedDict describing the input, enabling more flexibility: 

632 

633 >>> class InstallDocsRule(DebputyParsedContent): 

634 ... sources: List[str] 

635 ... into: List[str] 

636 >>> class InputDocsRuleInputFormat(TypedDict): 

637 ... source: NotRequired[Annotated[str, DebputyParseHint.target_attribute("sources")]] 

638 ... sources: NotRequired[List[str]] 

639 ... into: Union[str, List[str]] 

640 >>> pg = ParserGenerator() 

641 >>> flexible_parser = pg.generate_parser( 

642 ... InstallDocsRule, 

643 ... source_content=InputDocsRuleInputFormat, 

644 ... ) 

645 

646 In this case, the `sources` field can either come from a single `source` in the manifest (which must be a string) 

647 or `sources` (which must be a list of strings). The parser also ensures that only one of `source` or `sources` 

648 is used to ensure the input is not ambiguous. For the `into` parameter, the parser will accept it being a str 

649 or a list of strings. Regardless of how the input was provided, the parser will normalize the input so that 

650 both `sources` and `into` in the result is a list of strings. As an example, this parser can accept 

651 both the previous input but also the following input: 

652 

653 ```yaml 

654 install-docs: 

655 source: "docs/*" 

656 into: "my-pkg" 

657 ``` 

658 

659 The `source` and `into` attributes are then normalized to lists as if the user had written them as lists 

660 with a single string in them. As noted above, the name of the `source` attribute will also be normalized 

661 while parsing. 

662 

663 In the cases where only one field is required by the user, it can sometimes make sense to allow a non-dict 

664 as part of the input. Example: 

665 

666 >>> class DiscardRule(DebputyParsedContent): 

667 ... paths: List[str] 

668 >>> class DiscardRuleInputDictFormat(TypedDict): 

669 ... path: NotRequired[Annotated[str, DebputyParseHint.target_attribute("paths")]] 

670 ... paths: NotRequired[List[str]] 

671 >>> # This format relies on DiscardRule having exactly one Required attribute 

672 >>> DiscardRuleInputWithAltFormat = Union[ 

673 ... DiscardRuleInputDictFormat, 

674 ... str, 

675 ... List[str], 

676 ... ] 

677 >>> pg = ParserGenerator() 

678 >>> flexible_parser = pg.generate_parser( 

679 ... DiscardRule, 

680 ... source_content=DiscardRuleInputWithAltFormat, 

681 ... ) 

682 

683 

684 Supported types: 

685 * `List` - must have a fixed type argument (such as `List[str]`) 

686 * `str` 

687 * `int` 

688 * `BinaryPackage` - When provided (or required), the user must provide a package name listed 

689 in the debian/control file. The code receives the BinaryPackage instance 

690 matching that input. 

691 * `FileSystemMode` - When provided (or required), the user must provide a file system mode in any 

692 format that `debputy' provides (such as `0644` or `a=rw,go=rw`). 

693 * `FileSystemOwner` - When provided (or required), the user must a file system owner that is 

694 available statically on all Debian systems (must be in `base-passwd`). 

695 The user has multiple options for how to specify it (either via name or id). 

696 * `FileSystemGroup` - When provided (or required), the user must a file system group that is 

697 available statically on all Debian systems (must be in `base-passwd`). 

698 The user has multiple options for how to specify it (either via name or id). 

699 * `ManifestCondition` - When provided (or required), the user must specify a conditional rule to apply. 

700 Usually, it is better to extend `DebputyParsedContentStandardConditional`, which 

701 provides the `debputy' default `when` parameter for conditionals. 

702 

703 Supported special type-like parameters: 

704 

705 * `Required` / `NotRequired` to mark a field as `Required` or `NotRequired`. Must be provided at the 

706 outermost level. Cannot vary between `parsed_content` and `source_content`. 

707 * `Annotated`. Accepted at the outermost level (inside Required/NotRequired) but ignored at the moment. 

708 * `Union`. Must be the outermost level (inside `Annotated` or/and `Required`/`NotRequired` if these are present). 

709 Automapping (see below) is restricted to two members in the Union. 

710 

711 Notable non-supported types: 

712 * `Mapping` and all variants therefore (such as `dict`). In the future, nested `TypedDict`s may be allowed. 

713 * `Optional` (or `Union[..., None]`): Use `NotRequired` for optional fields. 

714 

715 Automatic mapping rules from `source_content` to `parsed_content`: 

716 - `Union[T, List[T]]` can be narrowed automatically to `List[T]`. Transformation is basically: 

717 `lambda value: value if isinstance(value, list) else [value]` 

718 - `T` can be mapped automatically to `List[T]`, Transformation being: `lambda value: [value]` 

719 

720 Additionally, types can be annotated (`Annotated[str, ...]`) with `DebputyParseHint`s. Check its classmethod 

721 for concrete features that may be useful to you. 

722 

723 :param parsed_content: A DebputyParsedContent / TypedDict describing the desired model of the input once parsed. 

724 (DebputyParsedContent is a TypedDict subclass that work around some inadequate type checkers). 

725 It can also be a `List[DebputyParsedContent]`. In that case, `source_content` must be a 

726 `List[TypedDict[...]]`. 

727 :param source_content: Optionally, a TypedDict describing the input allowed by the user. This can be useful 

728 to describe more variations than in `parsed_content` that the parser will normalize for you. If omitted, 

729 the parsed_content is also considered the source_content (which affects what annotations are allowed in it). 

730 Note you should never pass the parsed_content as source_content directly. 

731 :param allow_optional: In rare cases, you want to support explicitly provided vs. optional. In this case, you 

732 should set this to True. Though, in 99.9% of all cases, you want `NotRequired` rather than `Optional` (and 

733 can keep this False). 

734 :param inline_reference_documentation: Optionally, programmatic documentation 

735 :param expected_debputy_integration_mode: If provided, this declares the integration modes where the 

736 result of the parser can be used. This is primarily useful for "fail-fast" on incorrect usage. 

737 When the restriction is not satisfiable, the generated parser will trigger a parse error immediately 

738 (resulting in a "compile time" failure rather than a "runtime" failure). 

739 :return: An input parser capable of reading input matching the TypedDict(s) used as reference. 

740 """ 

741 orig_parsed_content = parsed_content 

742 if source_content is parsed_content: 742 ↛ 743line 742 didn't jump to line 743 because the condition on line 742 was never true

743 raise ValueError( 

744 "Do not provide source_content if it is the same as parsed_content" 

745 ) 

746 is_list_wrapped = False 

747 if get_origin(orig_parsed_content) == list: 

748 parsed_content = get_args(orig_parsed_content)[0] 

749 is_list_wrapped = True 

750 

751 if isinstance(parsed_content, type) and issubclass( 

752 parsed_content, DebputyDispatchableType 

753 ): 

754 parser = self.dispatch_parser_table_for(parsed_content) 

755 if parser is None: 755 ↛ 756line 755 didn't jump to line 756 because the condition on line 755 was never true

756 raise ValueError( 

757 f"Unsupported parsed_content descriptor: {parsed_content.__qualname__}." 

758 f" The class {parsed_content.__qualname__} is not a pre-registered type." 

759 ) 

760 # FIXME: Only the list wrapped version has documentation. 

761 if is_list_wrapped: 761 ↛ 767line 761 didn't jump to line 767 because the condition on line 761 was always true

762 parser = ListWrappedDeclarativeInputParser( 

763 parser, 

764 inline_reference_documentation=inline_reference_documentation, 

765 expected_debputy_integration_mode=expected_debputy_integration_mode, 

766 ) 

767 return parser 

768 

769 if not is_typeddict(parsed_content): 769 ↛ 770line 769 didn't jump to line 770 because the condition on line 769 was never true

770 raise ValueError( 

771 f"Unsupported parsed_content descriptor: {parsed_content.__qualname__}." 

772 ' Only "TypedDict"-based types and a subset of "DebputyDispatchableType" are supported.' 

773 ) 

774 if is_list_wrapped and source_content is not None: 

775 if get_origin(source_content) != list: 775 ↛ 776line 775 didn't jump to line 776 because the condition on line 775 was never true

776 raise ValueError( 

777 "If the parsed_content is a List type, then source_format must be a List type as well." 

778 ) 

779 source_content = get_args(source_content)[0] 

780 

781 target_attributes = self._parse_types( 

782 parsed_content, 

783 allow_source_attribute_annotations=source_content is None, 

784 forbid_optional=not allow_optional, 

785 ) 

786 required_target_parameters = frozenset(parsed_content.__required_keys__) 

787 parsed_alt_form = None 

788 non_mapping_source_only = False 

789 

790 if source_content is not None: 

791 default_target_attribute = None 

792 if len(required_target_parameters) == 1: 

793 default_target_attribute = next(iter(required_target_parameters)) 

794 

795 source_typed_dict, alt_source_forms = _extract_typed_dict( 

796 source_content, 

797 default_target_attribute, 

798 ) 

799 if alt_source_forms: 

800 parsed_alt_form = self._parse_alt_form( 

801 alt_source_forms, 

802 default_target_attribute, 

803 ) 

804 if source_typed_dict is not None: 

805 source_content_attributes = self._parse_types( 

806 source_typed_dict, 

807 allow_target_attribute_annotation=True, 

808 allow_source_attribute_annotations=True, 

809 forbid_optional=not allow_optional, 

810 ) 

811 source_content_parameter = "source_content" 

812 source_and_parsed_differs = True 

813 else: 

814 source_typed_dict = parsed_content 

815 source_content_attributes = target_attributes 

816 source_content_parameter = "parsed_content" 

817 source_and_parsed_differs = True 

818 non_mapping_source_only = True 

819 else: 

820 source_typed_dict = parsed_content 

821 source_content_attributes = target_attributes 

822 source_content_parameter = "parsed_content" 

823 source_and_parsed_differs = False 

824 

825 sources = collections.defaultdict(set) 

826 seen_targets = set() 

827 seen_source_names: Dict[str, str] = {} 

828 source_attributes: Dict[str, AttributeDescription] = {} 

829 path_hint_source_attributes = [] 

830 

831 for k in source_content_attributes: 

832 ia = source_content_attributes[k] 

833 

834 ta = ( 

835 target_attributes.get(ia.target_attribute) 

836 if source_and_parsed_differs 

837 else ia 

838 ) 

839 if ta is None: 839 ↛ 841line 839 didn't jump to line 841 because the condition on line 839 was never true

840 # Error message would be wrong if this assertion is false. 

841 assert source_and_parsed_differs 

842 raise ValueError( 

843 f'The attribute "{k}" from the "source_content" parameter should have mapped' 

844 f' to "{ia.target_attribute}", but that parameter does not exist in "parsed_content"' 

845 ) 

846 if _is_path_attribute_candidate(ia, ta): 

847 path_hint_source_attributes.append(ia.source_attribute_name) 

848 existing_source_name = seen_source_names.get(ia.source_attribute_name) 

849 if existing_source_name: 849 ↛ 850line 849 didn't jump to line 850 because the condition on line 849 was never true

850 raise ValueError( 

851 f'The attribute "{k}" and "{existing_source_name}" both share the source name' 

852 f' "{ia.source_attribute_name}". Please change the {source_content_parameter} parameter,' 

853 f' so only one attribute use "{ia.source_attribute_name}".' 

854 ) 

855 seen_source_names[ia.source_attribute_name] = k 

856 seen_targets.add(ta.target_attribute) 

857 sources[ia.target_attribute].add(k) 

858 if source_and_parsed_differs: 

859 bridge_mapper = self._type_normalize( 

860 k, ia.attribute_type, ta.attribute_type, False 

861 ) 

862 ia.type_validator = ia.type_validator.combine_mapper(bridge_mapper) 

863 source_attributes[k] = ia 

864 

865 def _as_attr_names(td_name: Iterable[str]) -> FrozenSet[str]: 

866 return frozenset( 

867 source_content_attributes[a].source_attribute_name for a in td_name 

868 ) 

869 

870 _check_attributes( 

871 parsed_content, 

872 source_typed_dict, 

873 source_content_attributes, 

874 sources, 

875 ) 

876 

877 at_least_one_of = frozenset( 

878 _as_attr_names(g) 

879 for k, g in sources.items() 

880 if len(g) > 1 and k in required_target_parameters 

881 ) 

882 

883 if source_and_parsed_differs and seen_targets != target_attributes.keys(): 883 ↛ 884line 883 didn't jump to line 884 because the condition on line 883 was never true

884 missing = ", ".join( 

885 repr(k) for k in (target_attributes.keys() - seen_targets) 

886 ) 

887 raise ValueError( 

888 'The following attributes in "parsed_content" did not have a source field in "source_content":' 

889 f" {missing}" 

890 ) 

891 all_mutually_exclusive_fields = frozenset( 

892 _as_attr_names(g) for g in sources.values() if len(g) > 1 

893 ) 

894 

895 all_parameters = ( 

896 source_typed_dict.__required_keys__ | source_typed_dict.__optional_keys__ 

897 ) 

898 _check_conflicts( 

899 source_content_attributes, 

900 source_typed_dict.__required_keys__, 

901 all_parameters, 

902 ) 

903 

904 manifest_attributes = { 

905 a.source_attribute_name: a for a in source_content_attributes.values() 

906 } 

907 

908 if parsed_alt_form is not None: 

909 target_attribute = parsed_alt_form.target_attribute 

910 if ( 910 ↛ 915line 910 didn't jump to line 915

911 target_attribute not in required_target_parameters 

912 and required_target_parameters 

913 or len(required_target_parameters) > 1 

914 ): 

915 raise NotImplementedError( 

916 "When using alternative source formats (Union[TypedDict, ...]), then the" 

917 " target must have at most one require parameter" 

918 ) 

919 bridge_mapper = self._type_normalize( 

920 target_attribute, 

921 parsed_alt_form.attribute_type, 

922 target_attributes[target_attribute].attribute_type, 

923 False, 

924 ) 

925 parsed_alt_form.type_validator = ( 

926 parsed_alt_form.type_validator.combine_mapper(bridge_mapper) 

927 ) 

928 

929 inline_reference_documentation = ( 

930 _verify_and_auto_correct_inline_reference_documentation( 

931 parsed_content, 

932 source_typed_dict, 

933 source_content_attributes, 

934 inline_reference_documentation, 

935 parsed_alt_form is not None, 

936 automatic_docs, 

937 ) 

938 ) 

939 if non_mapping_source_only: 

940 parser = DeclarativeNonMappingInputParser( 

941 assume_not_none(parsed_alt_form), 

942 inline_reference_documentation=inline_reference_documentation, 

943 expected_debputy_integration_mode=expected_debputy_integration_mode, 

944 ) 

945 else: 

946 parser = DeclarativeMappingInputParser( 

947 _as_attr_names(source_typed_dict.__required_keys__), 

948 _as_attr_names(all_parameters), 

949 manifest_attributes, 

950 source_attributes, 

951 mutually_exclusive_attributes=all_mutually_exclusive_fields, 

952 alt_form_parser=parsed_alt_form, 

953 at_least_one_of=at_least_one_of, 

954 inline_reference_documentation=inline_reference_documentation, 

955 path_hint_source_attributes=tuple(path_hint_source_attributes), 

956 expected_debputy_integration_mode=expected_debputy_integration_mode, 

957 ) 

958 if is_list_wrapped: 

959 parser = ListWrappedDeclarativeInputParser( 

960 parser, 

961 expected_debputy_integration_mode=expected_debputy_integration_mode, 

962 ) 

963 return parser 

964 

965 def _as_type_validator( 

966 self, 

967 attribute: str, 

968 provided_type: Any, 

969 parsing_typed_dict_attribute: bool, 

970 ) -> AttributeTypeHandler: 

971 assert not isinstance(provided_type, tuple) 

972 

973 if isinstance(provided_type, type) and issubclass( 

974 provided_type, DebputyDispatchableType 

975 ): 

976 return _dispatch_parser(provided_type) 

977 

978 unmapped_type = self._strip_mapped_types( 

979 provided_type, 

980 parsing_typed_dict_attribute, 

981 ) 

982 type_normalizer = self._type_normalize( 

983 attribute, 

984 unmapped_type, 

985 provided_type, 

986 parsing_typed_dict_attribute, 

987 ) 

988 t_unmapped, t_orig, t_args = unpack_type( 

989 unmapped_type, 

990 parsing_typed_dict_attribute, 

991 ) 

992 

993 if ( 993 ↛ 999line 993 didn't jump to line 999

994 t_orig == Union 

995 and t_args 

996 and len(t_args) == 2 

997 and any(v is _NONE_TYPE for v in t_args) 

998 ): 

999 _, _, args = unpack_type(provided_type, parsing_typed_dict_attribute) 

1000 actual_type = [a for a in args if a is not _NONE_TYPE][0] 

1001 validator = self._as_type_validator( 

1002 attribute, actual_type, parsing_typed_dict_attribute 

1003 ) 

1004 

1005 def _validator(v: Any, path: AttributePath) -> None: 

1006 if v is None: 

1007 return 

1008 validator.ensure_type(v, path) 

1009 

1010 return AttributeTypeHandler( 

1011 validator.describe_type(), 

1012 _validator, 

1013 base_type=validator.base_type, 

1014 mapper=type_normalizer, 

1015 ) 

1016 

1017 if unmapped_type in BASIC_SIMPLE_TYPES: 

1018 type_name = BASIC_SIMPLE_TYPES[unmapped_type] 

1019 

1020 type_mapping = self._registered_types.get(provided_type) 

1021 if type_mapping is not None: 

1022 simple_type = f" ({type_name})" 

1023 type_name = type_mapping.target_type.__name__ 

1024 else: 

1025 simple_type = "" 

1026 

1027 def _validator(v: Any, path: AttributePath) -> None: 

1028 if not isinstance(v, unmapped_type): 

1029 _validation_type_error( 

1030 path, f"The attribute must be a {type_name}{simple_type}" 

1031 ) 

1032 

1033 return AttributeTypeHandler( 

1034 type_name, 

1035 _validator, 

1036 base_type=unmapped_type, 

1037 mapper=type_normalizer, 

1038 ) 

1039 if t_orig == list: 

1040 if not t_args: 1040 ↛ 1041line 1040 didn't jump to line 1041 because the condition on line 1040 was never true

1041 raise ValueError( 

1042 f'The attribute "{attribute}" is List but does not have Generics (Must use List[X])' 

1043 ) 

1044 _, t_provided_orig, t_provided_args = unpack_type( 

1045 provided_type, 

1046 parsing_typed_dict_attribute, 

1047 ) 

1048 genetic_type = t_args[0] 

1049 key_mapper = self._as_type_validator( 

1050 attribute, 

1051 genetic_type, 

1052 parsing_typed_dict_attribute, 

1053 ) 

1054 

1055 def _validator(v: Any, path: AttributePath) -> None: 

1056 if not isinstance(v, list): 1056 ↛ 1057line 1056 didn't jump to line 1057 because the condition on line 1056 was never true

1057 _validation_type_error(path, "The attribute must be a list") 

1058 for i, v in enumerate(v): 

1059 key_mapper.ensure_type(v, path[i]) 

1060 

1061 list_mapper = ( 

1062 map_each_element(key_mapper.mapper) 

1063 if key_mapper.mapper is not None 

1064 else None 

1065 ) 

1066 

1067 return AttributeTypeHandler( 

1068 f"List of {key_mapper.describe_type()}", 

1069 _validator, 

1070 base_type=list, 

1071 mapper=type_normalizer, 

1072 ).combine_mapper(list_mapper) 

1073 if is_typeddict(provided_type): 

1074 subparser = self.generate_parser(cast("Type[TD]", provided_type)) 

1075 return AttributeTypeHandler( 

1076 description=f"{provided_type.__name__} (Typed Mapping)", 

1077 ensure_type=lambda v, ap: None, 

1078 base_type=dict, 

1079 mapper=lambda v, ap, cv: subparser.parse_input( 

1080 v, ap, parser_context=cv 

1081 ), 

1082 ) 

1083 if t_orig == dict: 

1084 if not t_args or len(t_args) != 2: 1084 ↛ 1085line 1084 didn't jump to line 1085 because the condition on line 1084 was never true

1085 raise ValueError( 

1086 f'The attribute "{attribute}" is Dict but does not have Generics (Must use Dict[str, Y])' 

1087 ) 

1088 if t_args[0] != str: 1088 ↛ 1089line 1088 didn't jump to line 1089 because the condition on line 1088 was never true

1089 raise ValueError( 

1090 f'The attribute "{attribute}" is Dict and has a non-str type as key.' 

1091 " Currently, only `str` is supported (Dict[str, Y])" 

1092 ) 

1093 key_mapper = self._as_type_validator( 

1094 attribute, 

1095 t_args[0], 

1096 parsing_typed_dict_attribute, 

1097 ) 

1098 value_mapper = self._as_type_validator( 

1099 attribute, 

1100 t_args[1], 

1101 parsing_typed_dict_attribute, 

1102 ) 

1103 

1104 if key_mapper.base_type is None: 1104 ↛ 1105line 1104 didn't jump to line 1105 because the condition on line 1104 was never true

1105 raise ValueError( 

1106 f'The attribute "{attribute}" is Dict and the key did not have a trivial base type. Key types' 

1107 f" without trivial base types (such as `str`) are not supported at the moment." 

1108 ) 

1109 

1110 if value_mapper.mapper is not None: 1110 ↛ 1111line 1110 didn't jump to line 1111 because the condition on line 1110 was never true

1111 raise ValueError( 

1112 f'The attribute "{attribute}" is Dict and the value requires mapping.' 

1113 " Currently, this is not supported. Consider a simpler type (such as Dict[str, str] or Dict[str, Any])." 

1114 " Better typing may come later" 

1115 ) 

1116 

1117 def _validator(uv: Any, path: AttributePath) -> None: 

1118 if not isinstance(uv, dict): 1118 ↛ 1119line 1118 didn't jump to line 1119 because the condition on line 1118 was never true

1119 _validation_type_error(path, "The attribute must be a mapping") 

1120 key_name = "the first key in the mapping" 

1121 for i, (k, v) in enumerate(uv.items()): 

1122 if not key_mapper.base_type_match(k): 1122 ↛ 1123line 1122 didn't jump to line 1123 because the condition on line 1122 was never true

1123 kp = path.copy_with_path_hint(key_name) 

1124 _validation_type_error( 

1125 kp, 

1126 f'The key number {i + 1} in attribute "{kp}" must be a {key_mapper.describe_type()}', 

1127 ) 

1128 key_name = f"the key after {k}" 

1129 value_mapper.ensure_type(v, path[k]) 

1130 

1131 return AttributeTypeHandler( 

1132 f"Mapping of {value_mapper.describe_type()}", 

1133 _validator, 

1134 base_type=dict, 

1135 mapper=type_normalizer, 

1136 ).combine_mapper(key_mapper.mapper) 

1137 if t_orig == Union: 

1138 if _is_two_arg_x_list_x(t_args): 

1139 # Force the order to be "X, List[X]" as it simplifies the code 

1140 x_list_x = ( 

1141 t_args if get_origin(t_args[1]) == list else (t_args[1], t_args[0]) 

1142 ) 

1143 

1144 # X, List[X] could match if X was List[Y]. However, our code below assumes 

1145 # that X is a non-list. The `_is_two_arg_x_list_x` returns False for this 

1146 # case to avoid this assert and fall into the "generic case". 

1147 assert get_origin(x_list_x[0]) != list 

1148 x_subtype_checker = self._as_type_validator( 

1149 attribute, 

1150 x_list_x[0], 

1151 parsing_typed_dict_attribute, 

1152 ) 

1153 list_x_subtype_checker = self._as_type_validator( 

1154 attribute, 

1155 x_list_x[1], 

1156 parsing_typed_dict_attribute, 

1157 ) 

1158 type_description = x_subtype_checker.describe_type() 

1159 type_description = f"{type_description} or a list of {type_description}" 

1160 

1161 def _validator(v: Any, path: AttributePath) -> None: 

1162 if isinstance(v, list): 

1163 list_x_subtype_checker.ensure_type(v, path) 

1164 else: 

1165 x_subtype_checker.ensure_type(v, path) 

1166 

1167 return AttributeTypeHandler( 

1168 type_description, 

1169 _validator, 

1170 mapper=type_normalizer, 

1171 ) 

1172 else: 

1173 subtype_checker = [ 

1174 self._as_type_validator(attribute, a, parsing_typed_dict_attribute) 

1175 for a in t_args 

1176 ] 

1177 type_description = "one-of: " + ", ".join( 

1178 f"{sc.describe_type()}" for sc in subtype_checker 

1179 ) 

1180 mapper = subtype_checker[0].mapper 

1181 if any(mapper != sc.mapper for sc in subtype_checker): 1181 ↛ 1182line 1181 didn't jump to line 1182 because the condition on line 1181 was never true

1182 raise ValueError( 

1183 f'Cannot handle the union "{provided_type}" as the target types need different' 

1184 " type normalization/mapping logic. Unions are generally limited to Union[X, List[X]]" 

1185 " where X is a non-collection type." 

1186 ) 

1187 

1188 def _validator(v: Any, path: AttributePath) -> None: 

1189 partial_matches = [] 

1190 for sc in subtype_checker: 1190 ↛ 1198line 1190 didn't jump to line 1198 because the loop on line 1190 didn't complete

1191 try: 

1192 sc.ensure_type(v, path) 

1193 return 

1194 except ManifestParseException as e: 

1195 if sc.base_type_match(v): 1195 ↛ 1196line 1195 didn't jump to line 1196 because the condition on line 1195 was never true

1196 partial_matches.append((sc, e)) 

1197 

1198 if len(partial_matches) == 1: 

1199 raise partial_matches[0][1] 

1200 _validation_type_error( 

1201 path, f"Could not match against: {type_description}" 

1202 ) 

1203 

1204 return AttributeTypeHandler( 

1205 type_description, 

1206 _validator, 

1207 mapper=type_normalizer, 

1208 ) 

1209 if t_orig == Literal: 

1210 # We want "x" for string values; repr provides 'x' 

1211 pretty = ", ".join( 

1212 f'"{v}"' if isinstance(v, str) else str(v) for v in t_args 

1213 ) 

1214 

1215 def _validator(v: Any, path: AttributePath) -> None: 

1216 if v not in t_args: 

1217 value_hint = "" 

1218 if isinstance(v, str): 1218 ↛ 1220line 1218 didn't jump to line 1220 because the condition on line 1218 was always true

1219 value_hint = f"({v}) " 

1220 _validation_type_error( 

1221 path, 

1222 f"Value {value_hint}must be one of the following literal values: {pretty}", 

1223 ) 

1224 

1225 return AttributeTypeHandler( 

1226 f"One of the following literal values: {pretty}", 

1227 _validator, 

1228 ) 

1229 

1230 if provided_type == Any: 1230 ↛ 1235line 1230 didn't jump to line 1235 because the condition on line 1230 was always true

1231 return AttributeTypeHandler( 

1232 "any (unvalidated)", 

1233 lambda *a: None, 

1234 ) 

1235 raise ValueError( 

1236 f'The attribute "{attribute}" had/contained a type {provided_type}, which is not supported' 

1237 ) 

1238 

1239 def _parse_types( 

1240 self, 

1241 spec: Type[TypedDict], 

1242 allow_target_attribute_annotation: bool = False, 

1243 allow_source_attribute_annotations: bool = False, 

1244 forbid_optional: bool = True, 

1245 ) -> Dict[str, AttributeDescription]: 

1246 annotations = get_type_hints(spec, include_extras=True) 

1247 return { 

1248 k: self._attribute_description( 

1249 k, 

1250 t, 

1251 k in spec.__required_keys__, 

1252 allow_target_attribute_annotation=allow_target_attribute_annotation, 

1253 allow_source_attribute_annotations=allow_source_attribute_annotations, 

1254 forbid_optional=forbid_optional, 

1255 ) 

1256 for k, t in annotations.items() 

1257 } 

1258 

1259 def _attribute_description( 

1260 self, 

1261 attribute: str, 

1262 orig_td: Any, 

1263 is_required: bool, 

1264 forbid_optional: bool = True, 

1265 allow_target_attribute_annotation: bool = False, 

1266 allow_source_attribute_annotations: bool = False, 

1267 ) -> AttributeDescription: 

1268 td, anno, is_optional = _parse_type( 

1269 attribute, orig_td, forbid_optional=forbid_optional 

1270 ) 

1271 type_validator = self._as_type_validator(attribute, td, True) 

1272 parsed_annotations = DetectedDebputyParseHint.parse_annotations( 

1273 anno, 

1274 f' Seen with attribute "{attribute}".', 

1275 attribute, 

1276 is_required, 

1277 allow_target_attribute_annotation=allow_target_attribute_annotation, 

1278 allow_source_attribute_annotations=allow_source_attribute_annotations, 

1279 ) 

1280 return AttributeDescription( 

1281 target_attribute=parsed_annotations.target_attribute, 

1282 attribute_type=td, 

1283 type_validator=type_validator, 

1284 annotations=anno, 

1285 is_optional=is_optional, 

1286 conflicting_attributes=parsed_annotations.conflict_with_source_attributes, 

1287 conditional_required=parsed_annotations.conditional_required, 

1288 source_attribute_name=assume_not_none( 

1289 parsed_annotations.source_manifest_attribute 

1290 ), 

1291 parse_hints=parsed_annotations, 

1292 ) 

1293 

1294 def _parse_alt_form( 

1295 self, 

1296 alt_form, 

1297 default_target_attribute: Optional[str], 

1298 ) -> AttributeDescription: 

1299 td, anno, is_optional = _parse_type( 

1300 "source_format alternative form", 

1301 alt_form, 

1302 forbid_optional=True, 

1303 parsing_typed_dict_attribute=False, 

1304 ) 

1305 type_validator = self._as_type_validator( 

1306 "source_format alternative form", 

1307 td, 

1308 True, 

1309 ) 

1310 parsed_annotations = DetectedDebputyParseHint.parse_annotations( 

1311 anno, 

1312 " The alternative for source_format.", 

1313 None, 

1314 False, 

1315 default_target_attribute=default_target_attribute, 

1316 allow_target_attribute_annotation=True, 

1317 allow_source_attribute_annotations=False, 

1318 ) 

1319 return AttributeDescription( 

1320 target_attribute=parsed_annotations.target_attribute, 

1321 attribute_type=td, 

1322 type_validator=type_validator, 

1323 annotations=anno, 

1324 is_optional=is_optional, 

1325 conflicting_attributes=parsed_annotations.conflict_with_source_attributes, 

1326 conditional_required=parsed_annotations.conditional_required, 

1327 source_attribute_name="Alt form of the source_format", 

1328 ) 

1329 

1330 def _union_narrowing( 

1331 self, 

1332 input_type: Any, 

1333 target_type: Any, 

1334 parsing_typed_dict_attribute: bool, 

1335 ) -> Optional[Callable[[Any, AttributePath, Optional["ParserContextData"]], Any]]: 

1336 _, input_orig, input_args = unpack_type( 

1337 input_type, parsing_typed_dict_attribute 

1338 ) 

1339 _, target_orig, target_args = unpack_type( 

1340 target_type, parsing_typed_dict_attribute 

1341 ) 

1342 

1343 if input_orig != Union or not input_args: 1343 ↛ 1344line 1343 didn't jump to line 1344 because the condition on line 1343 was never true

1344 raise ValueError("input_type must be a Union[...] with non-empty args") 

1345 

1346 # Currently, we only support Union[X, List[X]] -> List[Y] narrowing or Union[X, List[X]] -> Union[Y, Union[Y]] 

1347 # - Where X = Y or there is a simple standard transformation from X to Y. 

1348 

1349 if target_orig not in (Union, list) or not target_args: 

1350 # Not supported 

1351 return None 

1352 

1353 if target_orig == Union and set(input_args) == set(target_args): 1353 ↛ 1355line 1353 didn't jump to line 1355 because the condition on line 1353 was never true

1354 # Not needed (identity mapping) 

1355 return None 

1356 

1357 if target_orig == list and not any(get_origin(a) == list for a in input_args): 1357 ↛ exit,   1357 ↛ 13592 missed branches: 1) line 1357 didn't finish the generator expression on line 1357, 2) line 1357 didn't jump to line 1359 because the condition on line 1357 was never true

1358 # Not supported 

1359 return None 

1360 

1361 target_arg = target_args[0] 

1362 simplified_type = self._strip_mapped_types( 

1363 target_arg, parsing_typed_dict_attribute 

1364 ) 

1365 acceptable_types = { 

1366 target_arg, 

1367 List[target_arg], # type: ignore 

1368 simplified_type, 

1369 List[simplified_type], # type: ignore 

1370 } 

1371 target_format = ( 

1372 target_arg, 

1373 List[target_arg], # type: ignore 

1374 ) 

1375 in_target_format = 0 

1376 in_simple_format = 0 

1377 for input_arg in input_args: 

1378 if input_arg not in acceptable_types: 1378 ↛ 1380line 1378 didn't jump to line 1380 because the condition on line 1378 was never true

1379 # Not supported 

1380 return None 

1381 if input_arg in target_format: 

1382 in_target_format += 1 

1383 else: 

1384 in_simple_format += 1 

1385 

1386 assert in_simple_format or in_target_format 

1387 

1388 if in_target_format and not in_simple_format: 

1389 # Union[X, List[X]] -> List[X] 

1390 return normalize_into_list 

1391 mapped = self._registered_types[target_arg] 

1392 if not in_target_format and in_simple_format: 1392 ↛ 1407line 1392 didn't jump to line 1407 because the condition on line 1392 was always true

1393 # Union[X, List[X]] -> List[Y] 

1394 

1395 def _mapper_x_list_y( 

1396 x: Union[Any, List[Any]], 

1397 ap: AttributePath, 

1398 pc: Optional["ParserContextData"], 

1399 ) -> List[Any]: 

1400 in_list_form: List[Any] = normalize_into_list(x, ap, pc) 

1401 

1402 return [mapped.mapper(x, ap, pc) for x in in_list_form] 

1403 

1404 return _mapper_x_list_y 

1405 

1406 # Union[Y, List[X]] -> List[Y] 

1407 if not isinstance(target_arg, type): 

1408 raise ValueError( 

1409 f"Cannot narrow {input_type} -> {target_type}: The automatic conversion does" 

1410 f" not support mixed types. Please use either {simplified_type} or {target_arg}" 

1411 f" in the source content (but both a mix of both)" 

1412 ) 

1413 

1414 def _mapper_mixed_list_y( 

1415 x: Union[Any, List[Any]], 

1416 ap: AttributePath, 

1417 pc: Optional["ParserContextData"], 

1418 ) -> List[Any]: 

1419 in_list_form: List[Any] = normalize_into_list(x, ap, pc) 

1420 

1421 return [ 

1422 x if isinstance(x, target_arg) else mapped.mapper(x, ap, pc) 

1423 for x in in_list_form 

1424 ] 

1425 

1426 return _mapper_mixed_list_y 

1427 

1428 def _type_normalize( 

1429 self, 

1430 attribute: str, 

1431 input_type: Any, 

1432 target_type: Any, 

1433 parsing_typed_dict_attribute: bool, 

1434 ) -> Optional[Callable[[Any, AttributePath, Optional["ParserContextData"]], Any]]: 

1435 if input_type == target_type: 

1436 return None 

1437 _, input_orig, input_args = unpack_type( 

1438 input_type, parsing_typed_dict_attribute 

1439 ) 

1440 _, target_orig, target_args = unpack_type( 

1441 target_type, 

1442 parsing_typed_dict_attribute, 

1443 ) 

1444 if input_orig == Union: 

1445 result = self._union_narrowing( 

1446 input_type, target_type, parsing_typed_dict_attribute 

1447 ) 

1448 if result: 

1449 return result 

1450 elif target_orig == list and target_args[0] == input_type: 

1451 return wrap_into_list 

1452 

1453 mapped = self._registered_types.get(target_type) 

1454 if mapped is not None and input_type == mapped.source_type: 

1455 # Source -> Target 

1456 return mapped.mapper 

1457 if target_orig == list and target_args: 1457 ↛ 1475line 1457 didn't jump to line 1475 because the condition on line 1457 was always true

1458 mapped = self._registered_types.get(target_args[0]) 

1459 if mapped is not None: 1459 ↛ 1475line 1459 didn't jump to line 1475 because the condition on line 1459 was always true

1460 # mypy is dense and forgot `mapped` cannot be optional in the comprehensions. 

1461 mapped_type: TypeMapping = mapped 

1462 if input_type == mapped.source_type: 1462 ↛ 1464line 1462 didn't jump to line 1464 because the condition on line 1462 was never true

1463 # Source -> List[Target] 

1464 return lambda x, ap, pc: [mapped_type.mapper(x, ap, pc)] 

1465 if ( 1465 ↛ 1475line 1465 didn't jump to line 1475

1466 input_orig == list 

1467 and input_args 

1468 and input_args[0] == mapped_type.source_type 

1469 ): 

1470 # List[Source] -> List[Target] 

1471 return lambda xs, ap, pc: [ 

1472 mapped_type.mapper(x, ap, pc) for x in xs 

1473 ] 

1474 

1475 raise ValueError( 

1476 f'Unsupported type normalization for "{attribute}": Cannot automatically map/narrow' 

1477 f" {input_type} to {target_type}" 

1478 ) 

1479 

1480 def _strip_mapped_types( 

1481 self, orig_td: Any, parsing_typed_dict_attribute: bool 

1482 ) -> Any: 

1483 m = self._registered_types.get(orig_td) 

1484 if m is not None: 

1485 return m.source_type 

1486 _, v, args = unpack_type(orig_td, parsing_typed_dict_attribute) 

1487 if v == list: 

1488 arg = args[0] 

1489 m = self._registered_types.get(arg) 

1490 if m: 

1491 return List[m.source_type] # type: ignore 

1492 if v == Union: 

1493 stripped_args = tuple( 

1494 self._strip_mapped_types(x, parsing_typed_dict_attribute) for x in args 

1495 ) 

1496 if stripped_args != args: 

1497 return Union[stripped_args] 

1498 return orig_td 

1499 

1500 

1501def _sort_key(attr: StandardParserAttributeDocumentation) -> Any: 

1502 key = next(iter(attr.attributes)) 

1503 return attr.sort_category, key 

1504 

1505 

1506def _apply_std_docs( 

1507 std_doc_table: Optional[ 

1508 Mapping[Type[Any], Sequence[StandardParserAttributeDocumentation]] 

1509 ], 

1510 source_format_typed_dict: Type[Any], 

1511 attribute_docs: Optional[Sequence[ParserAttributeDocumentation]], 

1512) -> Optional[Sequence[ParserAttributeDocumentation]]: 

1513 if std_doc_table is None or not std_doc_table: 1513 ↛ 1516line 1513 didn't jump to line 1516 because the condition on line 1513 was always true

1514 return attribute_docs 

1515 

1516 has_docs_for = set() 

1517 if attribute_docs: 

1518 for attribute_doc in attribute_docs: 

1519 has_docs_for.update(attribute_doc.attributes) 

1520 

1521 base_seen = set() 

1522 std_docs_used = [] 

1523 

1524 remaining_bases = set(getattr(source_format_typed_dict, "__orig_bases__", [])) 

1525 base_seen.update(remaining_bases) 

1526 while remaining_bases: 

1527 base = remaining_bases.pop() 

1528 new_bases_to_check = { 

1529 x for x in getattr(base, "__orig_bases__", []) if x not in base_seen 

1530 } 

1531 remaining_bases.update(new_bases_to_check) 

1532 base_seen.update(new_bases_to_check) 

1533 std_docs = std_doc_table.get(base) 

1534 if std_docs: 

1535 for std_doc in std_docs: 

1536 if any(a in has_docs_for for a in std_doc.attributes): 

1537 # If there is any overlap, do not add the docs 

1538 continue 

1539 has_docs_for.update(std_doc.attributes) 

1540 std_docs_used.append(std_doc) 

1541 

1542 if not std_docs_used: 

1543 return attribute_docs 

1544 docs = sorted(std_docs_used, key=_sort_key) 

1545 if attribute_docs: 

1546 # Plugin provided attributes first 

1547 c = list(attribute_docs) 

1548 c.extend(docs) 

1549 docs = c 

1550 return tuple(docs) 

1551 

1552 

1553def _verify_and_auto_correct_inline_reference_documentation( 

1554 parsed_content: Type[TD], 

1555 source_typed_dict: Type[Any], 

1556 source_content_attributes: Mapping[str, AttributeDescription], 

1557 inline_reference_documentation: Optional[ParserDocumentation], 

1558 has_alt_form: bool, 

1559 automatic_docs: Optional[ 

1560 Mapping[Type[Any], Sequence[StandardParserAttributeDocumentation]] 

1561 ] = None, 

1562) -> Optional[ParserDocumentation]: 

1563 orig_attribute_docs = ( 

1564 inline_reference_documentation.attribute_doc 

1565 if inline_reference_documentation 

1566 else None 

1567 ) 

1568 attribute_docs = _apply_std_docs( 

1569 automatic_docs, 

1570 source_typed_dict, 

1571 orig_attribute_docs, 

1572 ) 

1573 if inline_reference_documentation is None and attribute_docs is None: 

1574 return None 

1575 changes = {} 

1576 if attribute_docs: 

1577 seen = set() 

1578 had_any_custom_docs = False 

1579 for attr_doc in attribute_docs: 

1580 if not isinstance(attr_doc, StandardParserAttributeDocumentation): 

1581 had_any_custom_docs = True 

1582 for attr_name in attr_doc.attributes: 

1583 attr = source_content_attributes.get(attr_name) 

1584 if attr is None: 1584 ↛ 1585line 1584 didn't jump to line 1585 because the condition on line 1584 was never true

1585 raise ValueError( 

1586 f"The inline_reference_documentation for the source format of {parsed_content.__qualname__}" 

1587 f' references an attribute "{attr_name}", which does not exist in the source format.' 

1588 ) 

1589 if attr_name in seen: 1589 ↛ 1590line 1589 didn't jump to line 1590 because the condition on line 1589 was never true

1590 raise ValueError( 

1591 f"The inline_reference_documentation for the source format of {parsed_content.__qualname__}" 

1592 f' has documentation for "{attr_name}" twice, which is not supported.' 

1593 f" Please document it at most once" 

1594 ) 

1595 seen.add(attr_name) 

1596 undocumented = source_content_attributes.keys() - seen 

1597 if undocumented: 1597 ↛ 1598line 1597 didn't jump to line 1598 because the condition on line 1597 was never true

1598 if had_any_custom_docs: 

1599 undocumented_attrs = ", ".join(undocumented) 

1600 raise ValueError( 

1601 f"The following attributes were not documented for the source format of" 

1602 f" {parsed_content.__qualname__}. If this is deliberate, then please" 

1603 ' declare each them as undocumented (via undocumented_attr("foo")):' 

1604 f" {undocumented_attrs}" 

1605 ) 

1606 combined_docs = list(attribute_docs) 

1607 combined_docs.extend(undocumented_attr(a) for a in sorted(undocumented)) 

1608 attribute_docs = combined_docs 

1609 

1610 if attribute_docs and orig_attribute_docs != attribute_docs: 1610 ↛ 1611line 1610 didn't jump to line 1611 because the condition on line 1610 was never true

1611 assert attribute_docs is not None 

1612 changes["attribute_doc"] = tuple(attribute_docs) 

1613 

1614 if ( 1614 ↛ 1619line 1614 didn't jump to line 1619

1615 inline_reference_documentation is not None 

1616 and inline_reference_documentation.alt_parser_description 

1617 and not has_alt_form 

1618 ): 

1619 raise ValueError( 

1620 "The inline_reference_documentation had documentation for an non-mapping format," 

1621 " but the source format does not have a non-mapping format." 

1622 ) 

1623 if changes: 1623 ↛ 1624line 1623 didn't jump to line 1624 because the condition on line 1623 was never true

1624 if inline_reference_documentation is None: 

1625 inline_reference_documentation = reference_documentation() 

1626 return inline_reference_documentation.replace(**changes) 

1627 return inline_reference_documentation 

1628 

1629 

1630def _check_conflicts( 

1631 input_content_attributes: Dict[str, AttributeDescription], 

1632 required_attributes: FrozenSet[str], 

1633 all_attributes: FrozenSet[str], 

1634) -> None: 

1635 for attr_name, attr in input_content_attributes.items(): 

1636 if attr_name in required_attributes and attr.conflicting_attributes: 1636 ↛ 1637line 1636 didn't jump to line 1637 because the condition on line 1636 was never true

1637 c = ", ".join(repr(a) for a in attr.conflicting_attributes) 

1638 raise ValueError( 

1639 f'The attribute "{attr_name}" is required and conflicts with the attributes: {c}.' 

1640 " This makes it impossible to use these attributes. Either remove the attributes" 

1641 f' (along with the conflicts for them), adjust the conflicts or make "{attr_name}"' 

1642 " optional (NotRequired)" 

1643 ) 

1644 else: 

1645 required_conflicts = attr.conflicting_attributes & required_attributes 

1646 if required_conflicts: 1646 ↛ 1647line 1646 didn't jump to line 1647 because the condition on line 1646 was never true

1647 c = ", ".join(repr(a) for a in required_conflicts) 

1648 raise ValueError( 

1649 f'The attribute "{attr_name}" conflicts with the following *required* attributes: {c}.' 

1650 f' This makes it impossible to use the "{attr_name}" attribute. Either remove it,' 

1651 f" adjust the conflicts or make the listed attributes optional (NotRequired)" 

1652 ) 

1653 unknown_attributes = attr.conflicting_attributes - all_attributes 

1654 if unknown_attributes: 1654 ↛ 1655line 1654 didn't jump to line 1655 because the condition on line 1654 was never true

1655 c = ", ".join(repr(a) for a in unknown_attributes) 

1656 raise ValueError( 

1657 f'The attribute "{attr_name}" declares a conflict with the following unknown attributes: {c}.' 

1658 f" None of these attributes were declared in the input." 

1659 ) 

1660 

1661 

1662def _check_attributes( 

1663 content: Type[TypedDict], 

1664 input_content: Type[TypedDict], 

1665 input_content_attributes: Dict[str, AttributeDescription], 

1666 sources: Mapping[str, Collection[str]], 

1667) -> None: 

1668 target_required_keys = content.__required_keys__ 

1669 input_required_keys = input_content.__required_keys__ 

1670 all_input_keys = input_required_keys | input_content.__optional_keys__ 

1671 

1672 for input_name in all_input_keys: 

1673 attr = input_content_attributes[input_name] 

1674 target_name = attr.target_attribute 

1675 source_names = sources[target_name] 

1676 input_is_required = input_name in input_required_keys 

1677 target_is_required = target_name in target_required_keys 

1678 

1679 assert source_names 

1680 

1681 if input_is_required and len(source_names) > 1: 1681 ↛ 1682line 1681 didn't jump to line 1682 because the condition on line 1681 was never true

1682 raise ValueError( 

1683 f'The source attribute "{input_name}" is required, but it maps to "{target_name}",' 

1684 f' which has multiple sources "{source_names}". If "{input_name}" should be required,' 

1685 f' then there is no need for additional sources for "{target_name}". Alternatively,' 

1686 f' "{input_name}" might be missing a NotRequired type' 

1687 f' (example: "{input_name}: NotRequired[<OriginalTypeHere>]")' 

1688 ) 

1689 if not input_is_required and target_is_required and len(source_names) == 1: 1689 ↛ 1690line 1689 didn't jump to line 1690 because the condition on line 1689 was never true

1690 raise ValueError( 

1691 f'The source attribute "{input_name}" is not marked as required and maps to' 

1692 f' "{target_name}", which is marked as required. As there are no other attributes' 

1693 f' mapping to "{target_name}", then "{input_name}" must be required as well' 

1694 f' ("{input_name}: Required[<Type>]"). Alternatively, "{target_name}" should be optional' 

1695 f' ("{target_name}: NotRequired[<Type>]") or an "MappingHint.aliasOf" might be missing.' 

1696 ) 

1697 

1698 

1699def _validation_type_error(path: AttributePath, message: str) -> None: 

1700 raise ManifestParseException( 

1701 f'The attribute "{path.path}" did not have a valid structure/type: {message}' 

1702 ) 

1703 

1704 

1705def _is_two_arg_x_list_x(t_args: Tuple[Any, ...]) -> bool: 

1706 if len(t_args) != 2: 1706 ↛ 1707line 1706 didn't jump to line 1707 because the condition on line 1706 was never true

1707 return False 

1708 lhs, rhs = t_args 

1709 if get_origin(lhs) == list: 

1710 if get_origin(rhs) == list: 1710 ↛ 1713line 1710 didn't jump to line 1713 because the condition on line 1710 was never true

1711 # It could still match X, List[X] - but we do not allow this case for now as the caller 

1712 # does not support it. 

1713 return False 

1714 l_args = get_args(lhs) 

1715 return bool(l_args and l_args[0] == rhs) 

1716 if get_origin(rhs) == list: 

1717 r_args = get_args(rhs) 

1718 return bool(r_args and r_args[0] == lhs) 

1719 return False 

1720 

1721 

1722def _extract_typed_dict( 

1723 base_type, 

1724 default_target_attribute: Optional[str], 

1725) -> Tuple[Optional[Type[TypedDict]], Any]: 

1726 if is_typeddict(base_type): 

1727 return base_type, None 

1728 _, origin, args = unpack_type(base_type, False) 

1729 if origin != Union: 

1730 if isinstance(base_type, type) and issubclass(base_type, (dict, Mapping)): 1730 ↛ 1731line 1730 didn't jump to line 1731 because the condition on line 1730 was never true

1731 raise ValueError( 

1732 "The source_format cannot be nor contain a (non-TypedDict) dict" 

1733 ) 

1734 return None, base_type 

1735 typed_dicts = [x for x in args if is_typeddict(x)] 

1736 if len(typed_dicts) > 1: 1736 ↛ 1737line 1736 didn't jump to line 1737 because the condition on line 1736 was never true

1737 raise ValueError( 

1738 "When source_format is a Union, it must contain at most one TypedDict" 

1739 ) 

1740 typed_dict = typed_dicts[0] if typed_dicts else None 

1741 

1742 if any(x is None or x is _NONE_TYPE for x in args): 1742 ↛ 1743line 1742 didn't jump to line 1743 because the condition on line 1742 was never true

1743 raise ValueError( 

1744 "The source_format cannot be nor contain Optional[X] or Union[X, None]" 

1745 ) 

1746 

1747 if any( 1747 ↛ 1752line 1747 didn't jump to line 1752 because the condition on line 1747 was never true

1748 isinstance(x, type) and issubclass(x, (dict, Mapping)) 

1749 for x in args 

1750 if x is not typed_dict 

1751 ): 

1752 raise ValueError( 

1753 "The source_format cannot be nor contain a (non-TypedDict) dict" 

1754 ) 

1755 remaining = [x for x in args if x is not typed_dict] 

1756 has_target_attribute = False 

1757 anno = None 

1758 if len(remaining) == 1: 1758 ↛ 1759line 1758 didn't jump to line 1759 because the condition on line 1758 was never true

1759 base_type, anno, _ = _parse_type( 

1760 "source_format alternative form", 

1761 remaining[0], 

1762 forbid_optional=True, 

1763 parsing_typed_dict_attribute=False, 

1764 ) 

1765 has_target_attribute = bool(anno) and any( 

1766 isinstance(x, TargetAttribute) for x in anno 

1767 ) 

1768 target_type = base_type 

1769 else: 

1770 target_type = Union[tuple(remaining)] 

1771 

1772 if default_target_attribute is None and not has_target_attribute: 1772 ↛ 1773line 1772 didn't jump to line 1773 because the condition on line 1772 was never true

1773 raise ValueError( 

1774 'The alternative format must be Union[TypedDict,Annotated[X, DebputyParseHint.target_attribute("...")]]' 

1775 " OR the parsed_content format must have exactly one attribute that is required." 

1776 ) 

1777 if anno: 1777 ↛ 1778line 1777 didn't jump to line 1778 because the condition on line 1777 was never true

1778 final_anno = [target_type] 

1779 final_anno.extend(anno) 

1780 return typed_dict, Annotated[tuple(final_anno)] 

1781 return typed_dict, target_type 

1782 

1783 

1784def _dispatch_parse_generator( 

1785 dispatch_type: Type[DebputyDispatchableType], 

1786) -> Callable[[Any, AttributePath, Optional["ParserContextData"]], Any]: 

1787 def _dispatch_parse( 

1788 value: Any, 

1789 attribute_path: AttributePath, 

1790 parser_context: Optional["ParserContextData"], 

1791 ): 

1792 assert parser_context is not None 

1793 dispatching_parser = parser_context.dispatch_parser_table_for(dispatch_type) 

1794 return dispatching_parser.parse_input( 

1795 value, attribute_path, parser_context=parser_context 

1796 ) 

1797 

1798 return _dispatch_parse 

1799 

1800 

1801def _dispatch_parser( 

1802 dispatch_type: Type[DebputyDispatchableType], 

1803) -> AttributeTypeHandler: 

1804 return AttributeTypeHandler( 

1805 dispatch_type.__name__, 

1806 lambda *a: None, 

1807 mapper=_dispatch_parse_generator(dispatch_type), 

1808 ) 

1809 

1810 

1811def _parse_type( 

1812 attribute: str, 

1813 orig_td: Any, 

1814 forbid_optional: bool = True, 

1815 parsing_typed_dict_attribute: bool = True, 

1816) -> Tuple[Any, Tuple[Any, ...], bool]: 

1817 td, v, args = unpack_type(orig_td, parsing_typed_dict_attribute) 

1818 md: Tuple[Any, ...] = tuple() 

1819 optional = False 

1820 if v is not None: 

1821 if v == Annotated: 

1822 anno = get_args(td) 

1823 md = anno[1:] 

1824 td, v, args = unpack_type(anno[0], parsing_typed_dict_attribute) 

1825 

1826 if td is _NONE_TYPE: 1826 ↛ 1827line 1826 didn't jump to line 1827 because the condition on line 1826 was never true

1827 raise ValueError( 

1828 f'The attribute "{attribute}" resolved to type "None". "Nil" / "None" fields are not allowed in the' 

1829 " debputy manifest, so this attribute does not make sense in its current form." 

1830 ) 

1831 if forbid_optional and v == Union and any(a is _NONE_TYPE for a in args): 1831 ↛ 1832line 1831 didn't jump to line 1832 because the condition on line 1831 was never true

1832 raise ValueError( 

1833 f'Detected use of Optional in "{attribute}", which is not allowed here.' 

1834 " Please use NotRequired for optional fields" 

1835 ) 

1836 

1837 return td, md, optional 

1838 

1839 

1840def _normalize_attribute_name(attribute: str) -> str: 

1841 if attribute.endswith("_"): 

1842 attribute = attribute[:-1] 

1843 return attribute.replace("_", "-") 

1844 

1845 

1846@dataclasses.dataclass 

1847class DetectedDebputyParseHint: 

1848 target_attribute: str 

1849 source_manifest_attribute: Optional[str] 

1850 conflict_with_source_attributes: FrozenSet[str] 

1851 conditional_required: Optional[ConditionalRequired] 

1852 applicable_as_path_hint: bool 

1853 

1854 @classmethod 

1855 def parse_annotations( 

1856 cls, 

1857 anno: Tuple[Any, ...], 

1858 error_context: str, 

1859 default_attribute_name: Optional[str], 

1860 is_required: bool, 

1861 default_target_attribute: Optional[str] = None, 

1862 allow_target_attribute_annotation: bool = False, 

1863 allow_source_attribute_annotations: bool = False, 

1864 ) -> "DetectedDebputyParseHint": 

1865 target_attr_anno = find_annotation(anno, TargetAttribute) 

1866 if target_attr_anno: 

1867 if not allow_target_attribute_annotation: 1867 ↛ 1868line 1867 didn't jump to line 1868 because the condition on line 1867 was never true

1868 raise ValueError( 

1869 f"The DebputyParseHint.target_attribute annotation is not allowed in this context.{error_context}" 

1870 ) 

1871 target_attribute = target_attr_anno.attribute 

1872 elif default_target_attribute is not None: 

1873 target_attribute = default_target_attribute 

1874 elif default_attribute_name is not None: 1874 ↛ 1877line 1874 didn't jump to line 1877 because the condition on line 1874 was always true

1875 target_attribute = default_attribute_name 

1876 else: 

1877 if default_attribute_name is None: 

1878 raise ValueError( 

1879 "allow_target_attribute_annotation must be True OR " 

1880 "default_attribute_name/default_target_attribute must be not None" 

1881 ) 

1882 raise ValueError( 

1883 f"Missing DebputyParseHint.target_attribute annotation.{error_context}" 

1884 ) 

1885 source_attribute_anno = find_annotation(anno, ManifestAttribute) 

1886 _source_attribute_allowed( 

1887 allow_source_attribute_annotations, error_context, source_attribute_anno 

1888 ) 

1889 if source_attribute_anno: 

1890 source_attribute_name = source_attribute_anno.attribute 

1891 elif default_attribute_name is not None: 

1892 source_attribute_name = _normalize_attribute_name(default_attribute_name) 

1893 else: 

1894 source_attribute_name = None 

1895 mutual_exclusive_with_anno = find_annotation(anno, ConflictWithSourceAttribute) 

1896 if mutual_exclusive_with_anno: 

1897 _source_attribute_allowed( 

1898 allow_source_attribute_annotations, 

1899 error_context, 

1900 mutual_exclusive_with_anno, 

1901 ) 

1902 conflicting_attributes = mutual_exclusive_with_anno.conflicting_attributes 

1903 else: 

1904 conflicting_attributes = frozenset() 

1905 conditional_required = find_annotation(anno, ConditionalRequired) 

1906 

1907 if conditional_required and is_required: 1907 ↛ 1908line 1907 didn't jump to line 1908 because the condition on line 1907 was never true

1908 if default_attribute_name is None: 

1909 raise ValueError( 

1910 f"is_required cannot be True without default_attribute_name being not None" 

1911 ) 

1912 raise ValueError( 

1913 f'The attribute "{default_attribute_name}" is Required while also being conditionally required.' 

1914 ' Please make the attribute "NotRequired" or remove the conditional requirement.' 

1915 ) 

1916 

1917 not_path_hint_anno = find_annotation(anno, NotPathHint) 

1918 applicable_as_path_hint = not_path_hint_anno is None 

1919 

1920 return DetectedDebputyParseHint( 

1921 target_attribute=target_attribute, 

1922 source_manifest_attribute=source_attribute_name, 

1923 conflict_with_source_attributes=conflicting_attributes, 

1924 conditional_required=conditional_required, 

1925 applicable_as_path_hint=applicable_as_path_hint, 

1926 ) 

1927 

1928 

1929def _source_attribute_allowed( 

1930 source_attribute_allowed: bool, 

1931 error_context: str, 

1932 annotation: Optional[DebputyParseHint], 

1933) -> None: 

1934 if source_attribute_allowed or annotation is None: 1934 ↛ 1936line 1934 didn't jump to line 1936 because the condition on line 1934 was always true

1935 return 

1936 raise ValueError( 

1937 f'The annotation "{annotation}" cannot be used here. {error_context}' 

1938 )