-
-
Notifications
You must be signed in to change notification settings - Fork 437
Expand file tree
/
Copy pathbase.py
More file actions
3135 lines (2725 loc) · 138 KB
/
base.py
File metadata and controls
3135 lines (2725 loc) · 138 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Abstract base parser and utilities for schema parsing.
Provides the Parser abstract base class that defines the parsing algorithm,
along with helper functions for model sorting, import resolution, and
code generation.
"""
from __future__ import annotations
import operator
import os.path
import re
import sys
from abc import ABC, abstractmethod
from collections import Counter, OrderedDict, defaultdict
from collections.abc import Callable, Hashable, Sequence
from itertools import groupby
from pathlib import Path
from typing import (
TYPE_CHECKING,
Any,
Generic,
NamedTuple,
Optional,
Protocol,
TypeAlias,
TypeVar,
cast,
runtime_checkable,
)
from urllib.parse import ParseResult
from warnings import warn
from pydantic import BaseModel
from typing_extensions import Unpack
from datamodel_code_generator import (
AllExportsCollisionStrategy,
AllExportsScope,
AllOfClassHierarchy,
AllOfMergeMode,
CollapseRootModelsNameStrategy,
Error,
FieldTypeCollisionStrategy,
ModuleSplitMode,
ReadOnlyWriteOnlyModelType,
ReuseScope,
YamlValue,
)
from datamodel_code_generator.format import (
CodeFormatter,
Formatter,
PythonVersion,
)
from datamodel_code_generator.imports import (
IMPORT_ANNOTATIONS,
IMPORT_LITERAL,
IMPORT_OPTIONAL,
IMPORT_UNION,
Import,
Imports,
)
from datamodel_code_generator.model import dataclass as dataclass_model
from datamodel_code_generator.model import msgspec as msgspec_model
from datamodel_code_generator.model import pydantic as pydantic_model
from datamodel_code_generator.model import pydantic_v2 as pydantic_model_v2
from datamodel_code_generator.model.base import (
ALL_MODEL,
GENERIC_BASE_CLASS_NAME,
GENERIC_BASE_CLASS_PATH,
UNDEFINED,
BaseClassDataType,
ConstraintsBase,
DataModel,
DataModelFieldBase,
WrappedDefault,
)
from datamodel_code_generator.model.enum import Enum, Member
from datamodel_code_generator.model.type_alias import TypeAliasBase, TypeStatement
from datamodel_code_generator.parser import DefaultPutDict, LiteralType
from datamodel_code_generator.parser._graph import stable_toposort
from datamodel_code_generator.parser._scc import find_circular_sccs, strongly_connected_components
from datamodel_code_generator.reference import ModelResolver, ModelType, Reference
from datamodel_code_generator.types import DataType, DataTypeManager
from datamodel_code_generator.util import camel_to_snake, model_copy, model_dump
if TYPE_CHECKING:
from collections.abc import Iterable, Iterator, Sequence
from datamodel_code_generator._types import ParserConfigDict
from datamodel_code_generator.config import ParserConfig
ParserConfigT = TypeVar("ParserConfigT", bound="ParserConfig")
@runtime_checkable
class HashableComparable(Hashable, Protocol):
"""Protocol for types that are both hashable and support comparison."""
def __lt__(self, value: Any, /) -> bool: ... # noqa: D105
def __le__(self, value: Any, /) -> bool: ... # noqa: D105
def __gt__(self, value: Any, /) -> bool: ... # noqa: D105
def __ge__(self, value: Any, /) -> bool: ... # noqa: D105
ModelName: TypeAlias = str
ModelNames: TypeAlias = set[ModelName]
ModelDeps: TypeAlias = dict[ModelName, set[ModelName]]
OrderIndex: TypeAlias = dict[ModelName, int]
ComponentId: TypeAlias = int
Components: TypeAlias = list[list[ModelName]]
ComponentOf: TypeAlias = dict[ModelName, ComponentId]
ComponentEdges: TypeAlias = dict[ComponentId, set[ComponentId]]
ClassNode: TypeAlias = tuple[ModelName, ...]
ClassGraph: TypeAlias = dict[ClassNode, set[ClassNode]]
ModulePath: TypeAlias = tuple[str, ...]
ModuleModels: TypeAlias = list[tuple[ModulePath, list[DataModel]]]
ForwarderMap: TypeAlias = dict[ModulePath, tuple[ModulePath, list[tuple[str, str]]]]
class ModuleContext(NamedTuple):
"""Context for processing a single module during code generation."""
module: ModulePath
module_key: ModulePath
models: list[DataModel]
is_init: bool
imports: Imports
scoped_model_resolver: ModelResolver
class ParseConfig(NamedTuple):
"""Configuration for the parse operation."""
with_import: bool
use_deferred_annotations: bool
code_formatter: CodeFormatter | None
module_split_mode: ModuleSplitMode | None
all_exports_scope: AllExportsScope | None
all_exports_collision_strategy: AllExportsCollisionStrategy | None
class _KeepModelOrderDeps(NamedTuple):
strong: ModelDeps
all: ModelDeps
class _KeepModelOrderComponents(NamedTuple):
components: Components
comp_of: ComponentOf
def _collect_keep_model_order_deps(
model: DataModel,
*,
model_names: ModelNames,
imported: ModelNames,
use_deferred_annotations: bool,
) -> tuple[set[ModelName], set[ModelName]]:
"""Collect (strong_deps, all_deps) used by keep_model_order sorting.
- strong_deps: base class references (within-module, non-imported)
- all_deps: base class refs + (optionally) field refs (within-module, non-imported)
"""
class_name = model.class_name
base_class_refs = {b.reference.short_name for b in model.base_classes if b.reference}
field_refs = {t.reference.short_name for f in model.fields for t in f.data_type.all_data_types if t.reference}
if use_deferred_annotations and not isinstance(model, (TypeAliasBase, pydantic_model_v2.RootModel)):
field_refs = set()
strong = {r for r in base_class_refs if r in model_names and r not in imported and r != class_name}
deps = {r for r in (base_class_refs | field_refs) if r in model_names and r not in imported and r != class_name}
return strong, deps
def _build_keep_model_order_dependency_maps(
models: list[DataModel],
*,
model_names: ModelNames,
imported: ModelNames,
use_deferred_annotations: bool,
) -> _KeepModelOrderDeps:
strong_deps: ModelDeps = {}
all_deps: ModelDeps = {}
for model in models:
strong, deps = _collect_keep_model_order_deps(
model,
model_names=model_names,
imported=imported,
use_deferred_annotations=use_deferred_annotations,
)
strong_deps[model.class_name] = strong
all_deps[model.class_name] = deps
return _KeepModelOrderDeps(strong=strong_deps, all=all_deps)
def _build_keep_model_order_components(
all_deps: ModelDeps,
order_index: OrderIndex,
) -> _KeepModelOrderComponents:
graph: ClassGraph = {(name,): {(dep,) for dep in deps} for name, deps in all_deps.items()}
sccs = strongly_connected_components(graph)
components: Components = [sorted((node[0] for node in scc), key=order_index.__getitem__) for scc in sccs]
components.sort(key=lambda members: min(order_index[n] for n in members))
comp_of: ComponentOf = {name: i for i, members in enumerate(components) for name in members}
return _KeepModelOrderComponents(components=components, comp_of=comp_of)
def _build_keep_model_order_component_edges(
all_deps: ModelDeps,
comp_of: ComponentOf,
num_components: int,
) -> ComponentEdges:
comp_edges: ComponentEdges = {i: set() for i in range(num_components)}
for name, deps in all_deps.items():
name_comp = comp_of[name]
for dep in deps:
if (dep_comp := comp_of[dep]) != name_comp:
comp_edges[dep_comp].add(name_comp)
return comp_edges
def _build_keep_model_order_component_order(
components: Components,
comp_edges: ComponentEdges,
order_index: OrderIndex,
) -> list[ComponentId]:
comp_key = [min(order_index[n] for n in members) for members in components]
return stable_toposort(
list(range(len(components))),
comp_edges,
key=lambda component_id: comp_key[component_id],
)
def _build_keep_model_ordered_names(
ordered_comp_ids: list[ComponentId],
components: Components,
strong_deps: ModelDeps,
order_index: OrderIndex,
) -> list[ModelName]:
ordered_names: list[ModelName] = []
for component_id in ordered_comp_ids:
members = components[component_id]
if len(members) > 1:
strong_edges: dict[ModelName, set[ModelName]] = {n: set() for n in members}
member_set = set(members)
for base in members:
derived_members = {member for member in members if base in strong_deps.get(member, set()) & member_set}
strong_edges[base].update(derived_members)
members = stable_toposort(members, strong_edges, key=order_index.__getitem__)
ordered_names.extend(members)
return ordered_names
def _reorder_models_keep_model_order(
models: list[DataModel],
imports: Imports,
*,
use_deferred_annotations: bool,
) -> None:
"""Reorder models deterministically based on their dependencies.
Starts from class_name order and only moves models when required to satisfy dependencies.
Cycles are kept as SCC groups; within each SCC, base-class dependencies are prioritized.
"""
models.sort(key=lambda x: x.class_name)
imported: ModelNames = {i for v in imports.values() for i in v}
model_by_name = {m.class_name: m for m in models}
model_names: ModelNames = set(model_by_name)
order_index: OrderIndex = {m.class_name: i for i, m in enumerate(models)}
deps = _build_keep_model_order_dependency_maps(
models,
model_names=model_names,
imported=imported,
use_deferred_annotations=use_deferred_annotations,
)
comps = _build_keep_model_order_components(deps.all, order_index)
comp_edges = _build_keep_model_order_component_edges(deps.all, comps.comp_of, len(comps.components))
ordered_comp_ids = _build_keep_model_order_component_order(comps.components, comp_edges, order_index)
ordered_names = _build_keep_model_ordered_names(ordered_comp_ids, comps.components, deps.strong, order_index)
models[:] = [model_by_name[name] for name in ordered_names]
SPECIAL_PATH_FORMAT: str = "#-datamodel-code-generator-#-{}-#-special-#"
def get_special_path(keyword: str, path: list[str]) -> list[str]:
"""Create a special path marker for internal reference tracking."""
return [*path, SPECIAL_PATH_FORMAT.format(keyword)]
escape_characters = str.maketrans({
"\u0000": r"\x00", # Null byte
"\\": r"\\",
"'": r"\'",
"\b": r"\b",
"\f": r"\f",
"\n": r"\n",
"\r": r"\r",
"\t": r"\t",
})
def to_hashable(item: Any) -> HashableComparable: # noqa: PLR0911
"""Convert an item to a hashable and comparable representation.
Returns a value that is both hashable and supports comparison operators.
Used for caching and deduplication of models.
"""
if isinstance(
item,
(
list,
tuple,
),
):
try:
return tuple(sorted((to_hashable(i) for i in item), key=lambda v: (str(type(v)), v)))
except TypeError:
# Fallback when mixed, non-comparable types are present; preserve original order
return tuple(to_hashable(i) for i in item)
if isinstance(item, dict):
return tuple(
sorted(
(
k,
to_hashable(v),
)
for k, v in item.items()
)
)
if isinstance(item, set): # pragma: no cover
return frozenset(to_hashable(i) for i in item) # type: ignore[return-value]
if isinstance(item, BaseModel):
return to_hashable(model_dump(item))
if item is None:
return ""
return item # type: ignore[return-value]
def dump_templates(templates: list[DataModel]) -> str:
"""Join model templates into a single code string."""
return "\n\n\n".join(str(m) for m in templates)
def iter_models_field_data_types(
models: Iterable[DataModel],
) -> Iterator[tuple[DataModel, DataModelFieldBase, DataType]]:
"""Yield (model, field, data_type) for all models, fields, and nested data types."""
for model in models:
for field in model.fields:
for data_type in field.data_type.all_data_types:
yield model, field, data_type
ReferenceMapSet = dict[str, set[str]]
SortedDataModels = dict[str, DataModel]
MAX_RECURSION_COUNT: int = sys.getrecursionlimit()
def add_model_path_to_list(
paths: list[str] | None,
model: DataModel,
/,
) -> list[str]:
"""
Auxiliary method which adds model path to list, provided the following hold.
- model is not a type alias
- path is not already in the list.
"""
if paths is None:
paths = []
if model.is_alias:
return paths
if (path := model.path) in paths:
return paths
paths.append(path)
return paths
def sort_data_models( # noqa: PLR0912, PLR0915
unsorted_data_models: list[DataModel],
sorted_data_models: SortedDataModels | None = None,
require_update_action_models: list[str] | None = None,
recursion_count: int = MAX_RECURSION_COUNT,
) -> tuple[list[DataModel], SortedDataModels, list[str]]:
"""Sort data models by dependency order for correct forward references."""
if sorted_data_models is None:
sorted_data_models = OrderedDict()
if require_update_action_models is None:
require_update_action_models = []
sorted_model_count: int = len(sorted_data_models)
unresolved_references: list[DataModel] = []
for model in unsorted_data_models:
if not model.reference_classes:
sorted_data_models[model.path] = model
elif model.path in model.reference_classes and len(model.reference_classes) == 1: # only self-referencing
sorted_data_models[model.path] = model
add_model_path_to_list(require_update_action_models, model)
elif (
not model.reference_classes - {model.path} - sorted_data_models.keys()
): # reference classes have been resolved
sorted_data_models[model.path] = model
if model.path in model.reference_classes:
add_model_path_to_list(require_update_action_models, model)
else:
unresolved_references.append(model)
if unresolved_references:
if sorted_model_count != len(sorted_data_models) and recursion_count:
try:
return sort_data_models(
unresolved_references,
sorted_data_models,
require_update_action_models,
recursion_count - 1,
)
except RecursionError: # pragma: no cover
pass
# sort on base_class dependency
while True:
ordered_models: list[tuple[int, DataModel]] = []
# Build lookup dict for O(1) index access instead of O(n) list.index()
path_to_index = {m.path: idx for idx, m in enumerate(unresolved_references)}
for model in unresolved_references:
if isinstance(model, pydantic_model_v2.RootModel):
indexes = [
path_to_index[ref_path]
for f in model.fields
for t in f.data_type.all_data_types
if t.reference and (ref_path := t.reference.path) in path_to_index
]
else:
indexes = [
path_to_index[b.reference.path]
for b in model.base_classes
if b.reference and b.reference.path in path_to_index
]
if indexes:
ordered_models.append((
max(indexes),
model,
))
else:
ordered_models.append((
-1,
model,
))
sorted_unresolved_models = [m[1] for m in sorted(ordered_models, key=operator.itemgetter(0))]
if sorted_unresolved_models == unresolved_references:
break
unresolved_references = sorted_unresolved_models
# circular reference
unsorted_data_model_names = set(path_to_index.keys())
for model in unresolved_references:
unresolved_model = model.reference_classes - {model.path} - sorted_data_models.keys()
base_models = [getattr(s.reference, "path", None) for s in model.base_classes]
update_action_parent = set(require_update_action_models).intersection(base_models)
if not unresolved_model:
sorted_data_models[model.path] = model
if update_action_parent:
add_model_path_to_list(require_update_action_models, model)
continue
if not unresolved_model - unsorted_data_model_names:
sorted_data_models[model.path] = model
add_model_path_to_list(require_update_action_models, model)
continue
# unresolved
unresolved_classes = ", ".join(
f"[class: {item.path} references: {item.reference_classes}]" for item in unresolved_references
)
msg = f"A Parser can not resolve classes: {unresolved_classes}."
raise Exception(msg) # noqa: TRY002
return unresolved_references, sorted_data_models, require_update_action_models
def relative(
current_module: str,
reference: str,
*,
reference_is_module: bool = False,
current_is_init: bool = False,
) -> tuple[str, str]:
"""Find relative module path.
Args:
current_module: Current module path (e.g., "foo.bar")
reference: Reference path (e.g., "foo.baz.ClassName" or "foo.baz" if reference_is_module)
reference_is_module: If True, treat reference as a module path (not module.class)
current_is_init: If True, treat current_module as a package __init__.py (adds depth)
Returns:
Tuple of (from_path, import_name) for constructing import statements
"""
if current_is_init:
current_module_path = [*current_module.split("."), "__init__"] if current_module else ["__init__"]
else:
current_module_path = current_module.split(".") if current_module else []
if reference_is_module:
reference_path = reference.split(".") if reference else []
name = reference_path[-1] if reference_path else ""
else:
*reference_path, name = reference.split(".")
if current_module_path == reference_path:
return "", ""
i = 0
for x, y in zip(current_module_path, reference_path, strict=False):
if x != y:
break
i += 1
left = "." * (len(current_module_path) - i)
right = ".".join(reference_path[i:])
if not left:
left = "."
if not right:
right = name
elif "." in right:
extra, right = right.rsplit(".", 1)
left += extra
return left, right
def is_ancestor_package_reference(current_module: str, reference: str) -> bool:
"""Check if reference is in an ancestor package (__init__.py).
When the reference's module path is an ancestor (prefix) of the current module,
the reference is in an ancestor package's __init__.py file.
Args:
current_module: The current module path (e.g., "v0.mammal.canine")
reference: The full reference path (e.g., "v0.Animal")
Returns:
True if the reference is in an ancestor package, False otherwise.
Examples:
- current="v0.animal", ref="v0.Animal" -> True (immediate parent)
- current="v0.mammal.canine", ref="v0.Animal" -> True (grandparent)
- current="v0.animal", ref="v0.animal.Dog" -> False (same or child)
- current="pets", ref="Animal" -> True (root package is immediate parent)
"""
current_path = current_module.split(".") if current_module else []
*reference_path, _ = reference.split(".")
if not current_path:
return False
# Case 1: Direct parent package (includes root package when reference_path is empty)
# e.g., current="pets", ref="Animal" -> current_path[:-1]=[] == reference_path=[]
if current_path[:-1] == reference_path:
return True
# Case 2: Deeper ancestor package (reference_path must be non-empty proper prefix)
# e.g., current="v0.mammal.canine", ref="v0.Animal" -> ["v0"] is prefix of ["v0","mammal","canine"]
return (
len(reference_path) > 0
and len(reference_path) < len(current_path)
and current_path[: len(reference_path)] == reference_path
)
def exact_import(from_: str, import_: str, short_name: str) -> tuple[str, str]:
"""Create exact import path to avoid relative import issues."""
if from_ == len(from_) * ".":
# Prevents "from . import foo" becoming "from ..foo import Foo"
# or "from .. import foo" becoming "from ...foo import Foo"
# when our imported module has the same parent
return f"{from_}{import_}", short_name
return f"{from_}.{import_}", short_name
def get_module_directory(module: tuple[str, ...]) -> tuple[str, ...]:
"""Get the directory portion of a module tuple.
Note: Module tuples in module_models do NOT include .py extension.
The last element is either the module name (e.g., "issuing") or empty for root.
Examples:
("pkg",) -> ("pkg",) - root module
("pkg", "issuing") -> ("pkg",) - submodule
("foo", "bar", "baz") -> ("foo", "bar") - deeply nested module
"""
if not module:
return ()
if len(module) == 1:
return module
return module[:-1]
@runtime_checkable
class Child(Protocol):
"""Protocol for objects with a parent reference."""
@property
def parent(self) -> Any | None:
"""Get the parent object reference."""
raise NotImplementedError
T = TypeVar("T")
def get_most_of_parent(value: Any, type_: type[T] | None = None) -> T | None:
"""Traverse parent chain to find the outermost matching parent."""
if isinstance(value, Child) and (type_ is None or not isinstance(value, type_)):
return get_most_of_parent(value.parent, type_)
return value
def title_to_class_name(title: str) -> str:
"""Convert a schema title to a valid Python class name."""
classname = re.sub(r"[^A-Za-z0-9]+", " ", title)
return "".join(x for x in classname.title() if not x.isspace())
def _find_base_classes(model: DataModel) -> list[DataModel]:
"""Get direct base class DataModels."""
return [b.reference.source for b in model.base_classes if b.reference and isinstance(b.reference.source, DataModel)]
def _find_field(original_name: str, models: list[DataModel]) -> DataModelFieldBase | None:
"""Find a field by original_name in the models and their base classes."""
for model in models:
for field in model.iter_all_fields(): # pragma: no cover
if field.original_name == original_name:
return field
return None # pragma: no cover
def _copy_data_types(data_types: list[DataType]) -> list[DataType]:
"""Deep copy a list of DataType objects, preserving references."""
copied_data_types: list[DataType] = []
for data_type_ in data_types:
if data_type_.reference:
copied_data_types.append(data_type_.__class__(reference=data_type_.reference))
elif data_type_.data_types: # pragma: no cover
copied_data_type = model_copy(data_type_)
copied_data_type.data_types = _copy_data_types(data_type_.data_types)
copied_data_types.append(copied_data_type)
else:
copied_data_types.append(model_copy(data_type_))
return copied_data_types
class Result(BaseModel):
"""Generated code result with optional source file reference."""
body: str
future_imports: str = ""
source: Optional[Path] = None # noqa: UP045
class Source(BaseModel):
"""Schema source file with path and content."""
path: Path
text: str = ""
raw_data: dict[str, YamlValue] | None = None
@classmethod
def from_path(cls, path: Path, base_path: Path, encoding: str) -> Source:
"""Create a Source from a file path relative to base_path."""
return cls(
path=path.relative_to(base_path),
text=path.read_text(encoding=encoding),
)
@classmethod
def from_dict(cls, data: dict[str, YamlValue]) -> Source:
"""Create a Source from a dict."""
return cls(path=Path(), raw_data=data)
class Parser(ABC, Generic[ParserConfigT]):
"""Abstract base class for schema parsers.
Provides the parsing algorithm and code generation. Subclasses implement
parse_raw() to handle specific schema formats.
"""
@classmethod
def _create_default_config(cls, options: ParserConfigDict) -> ParserConfigT:
"""Create a default config from options.
Subclasses should override this to return their own config type.
"""
from datamodel_code_generator import types as types_module # noqa: PLC0415
from datamodel_code_generator.config import ParserConfig # noqa: PLC0415
from datamodel_code_generator.model import base as model_base # noqa: PLC0415
from datamodel_code_generator.util import is_pydantic_v2 # noqa: PLC0415
if is_pydantic_v2():
ParserConfig.model_rebuild(
_types_namespace={
"StrictTypes": types_module.StrictTypes,
"DataModel": model_base.DataModel,
"DataModelFieldBase": model_base.DataModelFieldBase,
"DataTypeManager": types_module.DataTypeManager,
}
)
return ParserConfig.model_validate(options) # type: ignore[return-value]
ParserConfig.update_forward_refs(
StrictTypes=types_module.StrictTypes,
DataModel=model_base.DataModel,
DataModelFieldBase=model_base.DataModelFieldBase,
DataTypeManager=types_module.DataTypeManager,
)
defaults = {name: field.default for name, field in ParserConfig.__fields__.items()}
defaults.update(options)
return ParserConfig.construct(**defaults) # type: ignore[return-value]
def __init__( # noqa: PLR0912, PLR0915
self,
source: str | Path | list[Path] | ParseResult | dict[str, YamlValue],
*,
config: ParserConfigT | None = None,
**options: Unpack[ParserConfigDict],
) -> None:
"""Initialize the Parser with configuration options.
Args:
source: The schema source to parse.
config: Optional ParserConfig object with all configuration options.
**options: Individual configuration options (alternative to config).
Raises:
ValueError: If both config and **options are provided.
"""
if config is not None and options:
msg = "Cannot specify both 'config' and keyword arguments. Use one or the other."
raise ValueError(msg)
if config is None:
config = self._create_default_config(options)
self.config = config
self.keyword_only = config.keyword_only
self.target_pydantic_version = config.target_pydantic_version
self.frozen_dataclasses = config.frozen_dataclasses
self.data_type_manager: DataTypeManager = config.data_type_manager_type(
python_version=config.target_python_version,
use_standard_collections=config.use_standard_collections,
use_generic_container_types=config.use_generic_container_types,
use_non_positive_negative_number_constrained_types=config.use_non_positive_negative_number_constrained_types,
use_decimal_for_multiple_of=config.use_decimal_for_multiple_of,
strict_types=config.strict_types,
use_union_operator=config.use_union_operator,
use_pendulum=config.use_pendulum,
use_standard_primitive_types=config.use_standard_primitive_types,
target_datetime_class=config.target_datetime_class,
target_date_class=config.target_date_class,
treat_dot_as_module=config.treat_dot_as_module or False,
use_serialize_as_any=config.use_serialize_as_any,
)
self.data_model_type: type[DataModel] = config.data_model_type
self.data_model_root_type: type[DataModel] = config.data_model_root_type
self.data_model_field_type: type[DataModelFieldBase] = config.data_model_field_type
self.imports: Imports = Imports(config.use_exact_imports)
self.use_exact_imports: bool = config.use_exact_imports
self._append_additional_imports(additional_imports=config.additional_imports)
self.class_decorators: list[str] = config.class_decorators or []
self.base_class: str | None = config.base_class
self.base_class_map: dict[str, str] | None = config.base_class_map
self.target_python_version: PythonVersion = config.target_python_version
self.results: list[DataModel] = []
self.dump_resolve_reference_action: Callable[[Iterable[str]], str] | None = config.dump_resolve_reference_action
self.validation: bool = config.validation
self.field_constraints: bool = config.field_constraints
self.snake_case_field: bool = config.snake_case_field
self.strip_default_none: bool = config.strip_default_none
self.apply_default_values_for_required_fields: bool = config.apply_default_values_for_required_fields
self.force_optional_for_required_fields: bool = config.force_optional_for_required_fields
self.use_schema_description: bool = config.use_schema_description
self.use_field_description: bool = config.use_field_description
self.use_field_description_example: bool = config.use_field_description_example
self.use_inline_field_description: bool = config.use_inline_field_description
self.use_default_kwarg: bool = config.use_default_kwarg
self.reuse_model: bool = config.reuse_model
self.reuse_scope: ReuseScope | None = config.reuse_scope
self.shared_module_name: str = config.shared_module_name
self.encoding: str = config.encoding
self.enum_field_as_literal: LiteralType | None = config.enum_field_as_literal
self.enum_field_as_literal_map: dict[str, str] = config.enum_field_as_literal_map or {}
self.ignore_enum_constraints: bool = config.ignore_enum_constraints
self.set_default_enum_member: bool = config.set_default_enum_member
self.use_subclass_enum: bool = config.use_subclass_enum
self.use_specialized_enum: bool = config.use_specialized_enum
self.strict_nullable: bool = config.strict_nullable
self.use_generic_container_types: bool = config.use_generic_container_types
self.use_union_operator: bool = config.use_union_operator
self.enable_faux_immutability: bool = config.enable_faux_immutability
self.custom_class_name_generator: Callable[[str], str] | None = config.custom_class_name_generator
self.field_extra_keys: set[str] = config.field_extra_keys or set()
self.field_extra_keys_without_x_prefix: set[str] = config.field_extra_keys_without_x_prefix or set()
self.model_extra_keys: set[str] = config.model_extra_keys or set()
self.model_extra_keys_without_x_prefix: set[str] = config.model_extra_keys_without_x_prefix or set()
self.field_include_all_keys: bool = config.field_include_all_keys
self.remote_text_cache: DefaultPutDict[str, str] = config.remote_text_cache or DefaultPutDict()
self.current_source_path: Path | None = None
self.use_title_as_name: bool = config.use_title_as_name
self.use_operation_id_as_name: bool = config.use_operation_id_as_name
self.use_unique_items_as_set: bool = config.use_unique_items_as_set
self.use_tuple_for_fixed_items: bool = config.use_tuple_for_fixed_items
self.allof_merge_mode: AllOfMergeMode = config.allof_merge_mode
self.allof_class_hierarchy: AllOfClassHierarchy = config.allof_class_hierarchy
self.dataclass_arguments = config.dataclass_arguments
if config.base_path:
self.base_path = config.base_path
elif isinstance(source, Path):
self.base_path = source.absolute() if source.is_dir() else source.absolute().parent
else:
self.base_path = Path.cwd()
self.source: str | Path | list[Path] | ParseResult | dict[str, YamlValue] = source
self.custom_template_dir = config.custom_template_dir
self.extra_template_data: defaultdict[str, Any] = config.extra_template_data or defaultdict(dict)
self.use_generic_base_class: bool = config.use_generic_base_class
self.generic_base_class_config: dict[str, Any] = {}
if config.allow_population_by_field_name:
if config.use_generic_base_class:
self.generic_base_class_config["allow_population_by_field_name"] = True
else:
self.extra_template_data[ALL_MODEL]["allow_population_by_field_name"] = True
if config.allow_extra_fields:
if config.use_generic_base_class:
self.generic_base_class_config["allow_extra_fields"] = True
else:
self.extra_template_data[ALL_MODEL]["allow_extra_fields"] = True
if config.extra_fields:
if config.use_generic_base_class:
self.generic_base_class_config["extra_fields"] = config.extra_fields
else:
self.extra_template_data[ALL_MODEL]["extra_fields"] = config.extra_fields
if config.enable_faux_immutability:
if config.use_generic_base_class:
self.generic_base_class_config["allow_mutation"] = False
else:
self.extra_template_data[ALL_MODEL]["allow_mutation"] = False
if config.use_attribute_docstrings:
if config.use_generic_base_class:
self.generic_base_class_config["use_attribute_docstrings"] = True
else:
self.extra_template_data[ALL_MODEL]["use_attribute_docstrings"] = True
if config.target_pydantic_version:
if config.use_generic_base_class:
self.generic_base_class_config["target_pydantic_version"] = config.target_pydantic_version
else:
self.extra_template_data[ALL_MODEL]["target_pydantic_version"] = config.target_pydantic_version
self.model_resolver = ModelResolver(
base_url=source.geturl() if isinstance(source, ParseResult) else None,
singular_name_suffix="" if config.disable_appending_item_suffix else None,
aliases=config.aliases,
empty_field_name=config.empty_enum_field_name,
snake_case_field=config.snake_case_field,
custom_class_name_generator=config.custom_class_name_generator,
base_path=self.base_path,
original_field_name_delimiter=config.original_field_name_delimiter,
special_field_name_prefix=config.special_field_name_prefix,
remove_special_field_name_prefix=config.remove_special_field_name_prefix,
capitalise_enum_members=config.capitalise_enum_members,
no_alias=config.no_alias,
parent_scoped_naming=config.parent_scoped_naming,
treat_dot_as_module=config.treat_dot_as_module,
naming_strategy=config.naming_strategy,
duplicate_name_suffix_map=config.duplicate_name_suffix,
class_name_prefix=config.class_name_prefix,
class_name_suffix=config.class_name_suffix,
class_name_affix_scope=config.class_name_affix_scope,
skip_affix_for_root=config.class_name is not None,
default_value_overrides=config.default_value_overrides,
)
self.class_name: str | None = config.class_name
self.wrap_string_literal: bool | None = config.wrap_string_literal
self.http_headers: Sequence[tuple[str, str]] | None = config.http_headers
self.http_query_parameters: Sequence[tuple[str, str]] | None = config.http_query_parameters
self.http_ignore_tls: bool = config.http_ignore_tls
self.http_timeout: float | None = config.http_timeout
self.use_annotated: bool = config.use_annotated
if self.use_annotated and not self.field_constraints: # pragma: no cover
msg = "`use_annotated=True` has to be used with `field_constraints=True`"
raise Exception(msg) # noqa: TRY002
self.use_serialize_as_any: bool = config.use_serialize_as_any
self.use_non_positive_negative_number_constrained_types = (
config.use_non_positive_negative_number_constrained_types
)
self.use_double_quotes = config.use_double_quotes
self.allow_responses_without_content = config.allow_responses_without_content
self.collapse_root_models = config.collapse_root_models
self.collapse_root_models_name_strategy = config.collapse_root_models_name_strategy
self.collapse_reuse_models = config.collapse_reuse_models
self.skip_root_model = config.skip_root_model
self.use_type_alias = config.use_type_alias
self.capitalise_enum_members = config.capitalise_enum_members
self.keep_model_order = config.keep_model_order
self.use_one_literal_as_default = config.use_one_literal_as_default
self.use_enum_values_in_discriminator = config.use_enum_values_in_discriminator
self.known_third_party = config.known_third_party
self.custom_formatter = config.custom_formatters
self.custom_formatters_kwargs = config.custom_formatters_kwargs
self.treat_dot_as_module = config.treat_dot_as_module
self.default_field_extras: dict[str, Any] | None = config.default_field_extras
self.formatters: list[Formatter] | None = config.formatters
self.defer_formatting: bool = config.defer_formatting
self.type_mappings: dict[tuple[str, str], str] = Parser._parse_type_mappings(config.type_mappings)
self.type_overrides: dict[str, str] = config.type_overrides or {}
self._type_override_imports: dict[str, Import] = {
key: Import.from_full_path(value) for key, value in self.type_overrides.items()
}
self.read_only_write_only_model_type: ReadOnlyWriteOnlyModelType | None = config.read_only_write_only_model_type
self.use_frozen_field: bool = config.use_frozen_field
self.use_default_factory_for_optional_nested_models: bool = (
config.use_default_factory_for_optional_nested_models
)
self.field_type_collision_strategy: FieldTypeCollisionStrategy | None = config.field_type_collision_strategy
@property
def field_name_model_type(self) -> ModelType:
"""Get the ModelType for field name validation based on data_model_type.
Returns ModelType.PYDANTIC for Pydantic models (which have reserved attributes
like 'schema', 'model_fields', etc.), and ModelType.CLASS for other model types
(TypedDict, dataclass, msgspec) which don't have such constraints.
"""
if issubclass(
self.data_model_type,
(pydantic_model.BaseModel, pydantic_model_v2.BaseModel),
):
return ModelType.PYDANTIC
return ModelType.CLASS
@staticmethod
def _parse_type_mappings(type_mappings: list[str] | None) -> dict[tuple[str, str], str]:
"""Parse type mappings from CLI format to internal format.
Supports two formats:
- "type+format=target" (e.g., "string+binary=string")
- "format=target" (e.g., "binary=string", assumes type="string")
Returns a dict mapping (type, format) tuples to target type names.
"""
if not type_mappings:
return {}
result: dict[tuple[str, str], str] = {}
for mapping in type_mappings:
if "=" not in mapping:
msg = f"Invalid type mapping format: {mapping!r}. Expected 'type+format=target' or 'format=target'."
raise ValueError(msg)
source, target = mapping.split("=", 1)
if "+" in source:
type_, format_ = source.split("+", 1)
else:
# Default to "string" type if only format is specified
type_ = "string"
format_ = source
result[type_, format_] = target
return result
@property
def iter_source(self) -> Iterator[Source]:
"""Iterate over all source files to be parsed."""
match self.source:
case str():
yield Source(path=Path(), text=self.source)
case dict():
yield Source.from_dict(self.source)
case Path() as path: # pragma: no cover