-
-
Notifications
You must be signed in to change notification settings - Fork 437
Expand file tree
/
Copy path__main__.py
More file actions
1357 lines (1167 loc) · 56.1 KB
/
__main__.py
File metadata and controls
1357 lines (1167 loc) · 56.1 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
"""Main module for datamodel-code-generator CLI."""
from __future__ import annotations
import sys
# Fast path for --version (avoid importing heavy modules)
if len(sys.argv) == 2 and sys.argv[1] in {"--version", "-V"}: # pragma: no cover # noqa: PLR2004
from importlib.metadata import version
print(f"datamodel-codegen {version('datamodel-code-generator')}") # noqa: T201
sys.exit(0)
# Fast path for --help (avoid importing heavy modules)
if len(sys.argv) == 2 and sys.argv[1] in {"--help", "-h"}: # pragma: no cover # noqa: PLR2004
from datamodel_code_generator.arguments import arg_parser
arg_parser.print_help()
sys.exit(0)
# Fast path for --generate-prompt
if any(arg.startswith("--generate-prompt") for arg in sys.argv[1:]): # pragma: no cover
from datamodel_code_generator.arguments import arg_parser
namespace = arg_parser.parse_args()
if namespace.generate_prompt is not None:
from datamodel_code_generator.prompt import generate_prompt
help_text = arg_parser.format_help()
prompt_output = generate_prompt(namespace, help_text)
print(prompt_output) # noqa: T201
sys.exit(0)
import difflib
import json
import os
import shlex
import signal
import tempfile
import warnings
from collections import defaultdict
from collections.abc import Callable, Sequence # noqa: TC003 # pydantic needs it
from enum import IntEnum
from io import TextIOBase
from pathlib import Path
from typing import TYPE_CHECKING, Any, ClassVar, Optional, TypeAlias, Union, cast
from urllib.parse import ParseResult, urlparse
from pydantic import BaseModel
from datamodel_code_generator import (
DEFAULT_SHARED_MODULE_NAME,
AllExportsCollisionStrategy,
AllExportsScope,
AllOfClassHierarchy,
AllOfMergeMode,
ClassNameAffixScope,
CollapseRootModelsNameStrategy,
DataclassArguments,
DataModelType,
Error,
FieldTypeCollisionStrategy,
InputFileType,
InputModelRefStrategy,
InvalidClassNameError,
ModuleSplitMode,
NamingStrategy,
OpenAPIScope,
ReadOnlyWriteOnlyModelType,
ReuseScope,
TargetPydanticVersion,
enable_debug_message,
generate,
)
from datamodel_code_generator.arguments import DEFAULT_ENCODING, arg_parser, namespace
from datamodel_code_generator.format import (
DateClassType,
DatetimeClassType,
Formatter,
PythonVersion,
PythonVersionMin,
_get_black,
is_supported_in_black,
)
from datamodel_code_generator.model.pydantic_v2 import UnionMode # noqa: TC001 # needed for pydantic
from datamodel_code_generator.parser import LiteralType # noqa: TC001 # needed for pydantic
from datamodel_code_generator.reference import is_url
from datamodel_code_generator.types import StrictTypes # noqa: TC001 # needed for pydantic
from datamodel_code_generator.util import (
ConfigDict,
field_validator,
is_pydantic_v2,
load_toml,
model_validator,
)
if TYPE_CHECKING:
from argparse import Namespace
from typing_extensions import Self
# Options that should be excluded from pyproject.toml config generation
EXCLUDED_CONFIG_OPTIONS: frozenset[str] = frozenset({
"check",
"generate_pyproject_config",
"generate_cli_command",
"generate_prompt",
"ignore_pyproject",
"profile",
"version",
"help",
"debug",
"no_color",
"disable_warnings",
"watch",
"watch_delay",
})
BOOLEAN_OPTIONAL_OPTIONS: frozenset[str] = frozenset({
"use_specialized_enum",
"use_standard_collections",
})
class Exit(IntEnum):
"""Exit reasons."""
OK = 0
DIFF = 1
ERROR = 2
KeyboardInterrupt = 3
def sig_int_handler(_: int, __: Any) -> None: # pragma: no cover
"""Handle SIGINT signal gracefully."""
sys.exit(Exit.OK)
signal.signal(signal.SIGINT, sig_int_handler)
class Config(BaseModel):
"""Configuration model for code generation."""
if is_pydantic_v2():
model_config = ConfigDict(arbitrary_types_allowed=True) # pyright: ignore[reportAssignmentType]
def get(self, item: str) -> Any: # pragma: no cover
"""Get attribute value by name."""
return getattr(self, item)
def __getitem__(self, item: str) -> Any: # pragma: no cover
"""Get item by key."""
return self.get(item)
@classmethod
def parse_obj(cls, obj: Any) -> Self:
"""Parse object into Config model."""
return cls.model_validate(obj)
@classmethod
def get_fields(cls) -> dict[str, Any]:
"""Get model fields."""
return cls.model_fields
else:
class Config:
"""Pydantic v1 configuration."""
# Pydantic 1.5.1 doesn't support validate_assignment correctly
arbitrary_types_allowed = (TextIOBase,)
@classmethod
def get_fields(cls) -> dict[str, Any]:
"""Get model fields."""
return cls.__fields__
@field_validator("aliases", "extra_template_data", "custom_formatters_kwargs", "default_values", mode="before")
def validate_file(cls, value: Any) -> TextIOBase | None: # noqa: N805
"""Validate and open file path."""
if value is None: # pragma: no cover
return value
path = Path(value)
if path.is_file():
return cast("TextIOBase", path.expanduser().resolve().open("rt"))
msg = f"A file was expected but {value} is not a file." # pragma: no cover
raise Error(msg) # pragma: no cover
@field_validator(
"input",
"output",
"custom_template_dir",
"custom_file_header_path",
mode="before",
)
def validate_path(cls, value: Any) -> Path | None: # noqa: N805
"""Validate and resolve path."""
if value is None or isinstance(value, Path):
return value # pragma: no cover
return Path(value).expanduser().resolve()
@field_validator("url", mode="before")
def validate_url(cls, value: Any) -> ParseResult | None: # noqa: N805
"""Validate and parse URL."""
if isinstance(value, str) and is_url(value): # pragma: no cover
return urlparse(value)
if value is None: # pragma: no cover
return None
msg = f"Unsupported URL scheme. Supported: http, https, file. --input={value}" # pragma: no cover
raise Error(msg) # pragma: no cover
# Pydantic 1.5.1 doesn't support each_item=True correctly
@field_validator("http_headers", mode="before")
def validate_http_headers(cls, value: Any) -> list[tuple[str, str]] | None: # noqa: N805
"""Validate HTTP headers."""
if value is None: # pragma: no cover
return None
def validate_each_item(each_item: str | tuple[str, str]) -> tuple[str, str]:
if isinstance(each_item, str): # pragma: no cover
try:
field_name, field_value = each_item.split(":", maxsplit=1)
return field_name, field_value.lstrip()
except ValueError as exc:
msg = f"Invalid http header: {each_item!r}"
raise Error(msg) from exc
return each_item # pragma: no cover
if isinstance(value, list):
return [validate_each_item(each_item) for each_item in value]
msg = f"Invalid http_headers value: {value!r}" # pragma: no cover
raise Error(msg) # pragma: no cover
@field_validator("http_query_parameters", mode="before")
def validate_http_query_parameters(cls, value: Any) -> list[tuple[str, str]] | None: # noqa: N805
"""Validate HTTP query parameters."""
if value is None: # pragma: no cover
return None
def validate_each_item(each_item: str | tuple[str, str]) -> tuple[str, str]:
if isinstance(each_item, str): # pragma: no cover
try:
field_name, field_value = each_item.split("=", maxsplit=1)
return field_name, field_value.lstrip()
except ValueError as exc:
msg = f"Invalid http query parameter: {each_item!r}"
raise Error(msg) from exc
return each_item # pragma: no cover
if isinstance(value, list):
return [validate_each_item(each_item) for each_item in value]
msg = f"Invalid http_query_parameters value: {value!r}" # pragma: no cover
raise Error(msg) # pragma: no cover
@model_validator(mode="before")
def validate_additional_imports(cls, values: dict[str, Any]) -> dict[str, Any]: # noqa: N805
"""Validate and split additional imports."""
additional_imports = values.get("additional_imports")
if additional_imports is not None:
values["additional_imports"] = additional_imports.split(",")
return values
@model_validator(mode="before")
def validate_custom_formatters(cls, values: dict[str, Any]) -> dict[str, Any]: # noqa: N805
"""Validate and split custom formatters."""
custom_formatters = values.get("custom_formatters")
if custom_formatters is not None:
values["custom_formatters"] = custom_formatters.split(",")
return values
@model_validator(mode="before")
def validate_duplicate_name_suffix(cls, values: dict[str, Any]) -> dict[str, Any]: # noqa: N805
"""Validate and parse duplicate_name_suffix JSON string."""
duplicate_name_suffix = values.get("duplicate_name_suffix")
if duplicate_name_suffix is not None and isinstance(duplicate_name_suffix, str):
try:
values["duplicate_name_suffix"] = json.loads(duplicate_name_suffix)
except json.JSONDecodeError as e:
msg = f"Invalid JSON for --duplicate-name-suffix: {e}"
raise Error(msg) from e
return values
@model_validator(mode="before")
def validate_naming_strategy_migration(cls, values: dict[str, Any]) -> dict[str, Any]: # noqa: N805
"""Migrate deprecated --parent-scoped-naming to --naming-strategy."""
if values.get("parent_scoped_naming") and not values.get("naming_strategy"):
values["naming_strategy"] = NamingStrategy.ParentPrefixed
warnings.warn(
"--parent-scoped-naming is deprecated. Use --naming-strategy parent-prefixed instead.",
DeprecationWarning,
stacklevel=2,
)
return values
@model_validator(mode="before")
def validate_class_decorators(cls, values: dict[str, Any]) -> dict[str, Any]: # noqa: N805
"""Validate and split class decorators, adding @ prefix if missing."""
class_decorators = values.get("class_decorators")
if class_decorators is not None:
decorators = []
for raw_decorator in class_decorators.split(","):
stripped = raw_decorator.strip()
if stripped:
if not stripped.startswith("@"):
stripped = f"@{stripped}"
decorators.append(stripped)
values["class_decorators"] = decorators
return values
__validate_output_datetime_class_err: ClassVar[str] = (
'`--output-datetime-class` only allows "datetime" for '
f"`--output-model-type` {DataModelType.DataclassesDataclass.value}"
)
__validate_original_field_name_delimiter_err: ClassVar[str] = (
"`--original-field-name-delimiter` can not be used without `--snake-case-field`."
)
__validate_custom_file_header_err: ClassVar[str] = (
"`--custom_file_header_path` can not be used with `--custom_file_header`."
)
__validate_keyword_only_err: ClassVar[str] = (
f"`--keyword-only` requires `--target-python-version` {PythonVersion.PY_310.value} or higher."
)
__validate_all_exports_collision_strategy_err: ClassVar[str] = (
"`--all-exports-collision-strategy` can only be used with `--all-exports-scope=recursive`."
)
if is_pydantic_v2():
@model_validator() # pyright: ignore[reportArgumentType]
def validate_output_datetime_class(self: Self) -> Self: # pyright: ignore[reportRedeclaration]
"""Validate output datetime class compatibility."""
datetime_class_type: DatetimeClassType | None = self.output_datetime_class
if (
datetime_class_type
and datetime_class_type is not DatetimeClassType.Datetime
and self.output_model_type == DataModelType.DataclassesDataclass
):
raise Error(self.__validate_output_datetime_class_err)
return self
@model_validator() # pyright: ignore[reportArgumentType]
def validate_original_field_name_delimiter(self: Self) -> Self: # pyright: ignore[reportRedeclaration]
"""Validate original field name delimiter requires snake case."""
if self.original_field_name_delimiter is not None and not self.snake_case_field:
raise Error(self.__validate_original_field_name_delimiter_err)
return self
@model_validator() # pyright: ignore[reportArgumentType]
def validate_custom_file_header(self: Self) -> Self: # pyright: ignore[reportRedeclaration]
"""Validate custom file header options are mutually exclusive."""
if self.custom_file_header and self.custom_file_header_path:
raise Error(self.__validate_custom_file_header_err)
return self
@model_validator() # pyright: ignore[reportArgumentType]
def validate_keyword_only(self: Self) -> Self: # pyright: ignore[reportRedeclaration]
"""Validate keyword-only compatibility with target Python version."""
output_model_type: DataModelType = self.output_model_type
python_target: PythonVersion = self.target_python_version
if (
self.keyword_only
and output_model_type == DataModelType.DataclassesDataclass
and not python_target.has_kw_only_dataclass
):
raise Error(self.__validate_keyword_only_err)
return self
@model_validator() # pyright: ignore[reportArgumentType]
def validate_root(self: Self) -> Self: # pyright: ignore[reportRedeclaration]
"""Validate root model configuration."""
if self.use_annotated:
self.field_constraints = True
return self
@model_validator() # pyright: ignore[reportArgumentType]
def validate_all_exports_collision_strategy(self: Self) -> Self: # pyright: ignore[reportRedeclaration]
"""Validate all_exports_collision_strategy requires recursive scope."""
if self.all_exports_collision_strategy is not None and self.all_exports_scope != AllExportsScope.Recursive:
raise Error(self.__validate_all_exports_collision_strategy_err)
return self
from pydantic import field_validator as _field_validator # noqa: PLC0415
@_field_validator("input_model", mode="before")
@classmethod
def coerce_input_model_to_list(cls, v: str | list[str] | None) -> list[str] | None: # pyright: ignore[reportRedeclaration]
"""Convert string input_model to list for backwards compatibility."""
if isinstance(v, str):
return [v]
return v
@_field_validator("class_name_affix_scope", mode="before")
@classmethod
def validate_class_name_affix_scope(cls, v: str | ClassNameAffixScope | None) -> ClassNameAffixScope: # pyright: ignore[reportRedeclaration]
"""Convert string to ClassNameAffixScope enum."""
if v is None: # pragma: no cover
return ClassNameAffixScope.All
if isinstance(v, str):
return ClassNameAffixScope(v)
return v # pragma: no cover
else:
@model_validator() # pyright: ignore[reportArgumentType]
def validate_output_datetime_class(cls, values: dict[str, Any]) -> dict[str, Any]: # noqa: N805
"""Validate output datetime class compatibility."""
datetime_class_type: DatetimeClassType | None = values.get("output_datetime_class")
if (
datetime_class_type
and datetime_class_type is not DatetimeClassType.Datetime
and values.get("output_model_type") == DataModelType.DataclassesDataclass
):
raise Error(cls.__validate_output_datetime_class_err)
return values
@model_validator() # pyright: ignore[reportArgumentType]
def validate_original_field_name_delimiter(cls, values: dict[str, Any]) -> dict[str, Any]: # noqa: N805
"""Validate original field name delimiter requires snake case."""
if values.get("original_field_name_delimiter") is not None and not values.get("snake_case_field"):
raise Error(cls.__validate_original_field_name_delimiter_err)
return values
@model_validator() # pyright: ignore[reportArgumentType]
def validate_custom_file_header(cls, values: dict[str, Any]) -> dict[str, Any]: # noqa: N805
"""Validate custom file header options are mutually exclusive."""
if values.get("custom_file_header") and values.get("custom_file_header_path"):
raise Error(cls.__validate_custom_file_header_err)
return values
@model_validator() # pyright: ignore[reportArgumentType]
def validate_keyword_only(cls, values: dict[str, Any]) -> dict[str, Any]: # noqa: N805
"""Validate keyword-only compatibility with target Python version."""
output_model_type: DataModelType = cast("DataModelType", values.get("output_model_type"))
python_target: PythonVersion = cast("PythonVersion", values.get("target_python_version"))
if (
values.get("keyword_only")
and output_model_type == DataModelType.DataclassesDataclass
and not python_target.has_kw_only_dataclass
):
raise Error(cls.__validate_keyword_only_err)
return values
@model_validator() # pyright: ignore[reportArgumentType]
def validate_root(cls, values: dict[str, Any]) -> dict[str, Any]: # noqa: N805
"""Validate root model configuration."""
if values.get("use_annotated"):
values["field_constraints"] = True
return values
@model_validator() # pyright: ignore[reportArgumentType]
def validate_all_exports_collision_strategy(cls, values: dict[str, Any]) -> dict[str, Any]: # noqa: N805
"""Validate all_exports_collision_strategy requires recursive scope."""
if (
values.get("all_exports_collision_strategy") is not None
and values.get("all_exports_scope") != AllExportsScope.Recursive
):
raise Error(cls.__validate_all_exports_collision_strategy_err)
return values
@field_validator("input_model", mode="before") # pragma: no cover
@classmethod
def coerce_input_model_to_list(cls, v: str | list[str] | None) -> list[str] | None:
"""Convert string input_model to list for backwards compatibility."""
if isinstance(v, str):
return [v]
return v
@field_validator("class_name_affix_scope", mode="before") # pragma: no cover
@classmethod
def validate_class_name_affix_scope(cls, v: str | ClassNameAffixScope | None) -> ClassNameAffixScope:
"""Convert string to ClassNameAffixScope enum."""
if v is None:
return ClassNameAffixScope.All
if isinstance(v, str):
return ClassNameAffixScope(v)
return v
input: Optional[Union[Path, str]] = None # noqa: UP007, UP045
input_model: Optional[list[str]] = None # noqa: UP045
input_model_ref_strategy: Optional[InputModelRefStrategy] = None # noqa: UP045
input_file_type: InputFileType = InputFileType.Auto
output_model_type: DataModelType = DataModelType.PydanticBaseModel
output: Optional[Path] = None # noqa: UP045
check: bool = False
debug: bool = False
disable_warnings: bool = False
target_python_version: PythonVersion = PythonVersionMin
target_pydantic_version: Optional[TargetPydanticVersion] = None # noqa: UP045
base_class: str = ""
base_class_map: Optional[dict[str, str]] = None # noqa: UP045
additional_imports: Optional[list[str]] = None # noqa: UP045
class_decorators: Optional[list[str]] = None # noqa: UP045
custom_template_dir: Optional[Path] = None # noqa: UP045
extra_template_data: Optional[TextIOBase] = None # noqa: UP045
validation: bool = False
field_constraints: bool = False
snake_case_field: bool = False
strip_default_none: bool = False
aliases: Optional[TextIOBase] = None # noqa: UP045
default_values: Optional[TextIOBase] = None # noqa: UP045
disable_timestamp: bool = False
enable_version_header: bool = False
enable_command_header: bool = False
allow_population_by_field_name: bool = False
allow_extra_fields: bool = False
extra_fields: Optional[str] = None # noqa: UP045
use_generic_base_class: bool = False
use_default: bool = False
force_optional: bool = False
class_name: Optional[str] = None # noqa: UP045
class_name_prefix: Optional[str] = None # noqa: UP045
class_name_suffix: Optional[str] = None # noqa: UP045
class_name_affix_scope: ClassNameAffixScope = ClassNameAffixScope.All
use_standard_collections: bool = True
use_schema_description: bool = False
use_field_description: bool = False
use_field_description_example: bool = False
use_attribute_docstrings: bool = False
use_inline_field_description: bool = False
use_default_kwarg: bool = False
reuse_model: bool = False
reuse_scope: ReuseScope = ReuseScope.Module
shared_module_name: str = DEFAULT_SHARED_MODULE_NAME
encoding: str = DEFAULT_ENCODING
enum_field_as_literal: Optional[LiteralType] = None # noqa: UP045
enum_field_as_literal_map: Optional[dict[str, str]] = None # noqa: UP045
ignore_enum_constraints: bool = False
use_one_literal_as_default: bool = False
use_enum_values_in_discriminator: bool = False
set_default_enum_member: bool = False
use_subclass_enum: bool = False
use_specialized_enum: bool = True
strict_nullable: bool = False
use_generic_container_types: bool = False
use_union_operator: bool = True
enable_faux_immutability: bool = False
url: Optional[ParseResult] = None # noqa: UP045
disable_appending_item_suffix: bool = False
strict_types: list[StrictTypes] = []
empty_enum_field_name: Optional[str] = None # noqa: UP045
field_extra_keys: Optional[set[str]] = None # noqa: UP045
field_include_all_keys: bool = False
field_extra_keys_without_x_prefix: Optional[set[str]] = None # noqa: UP045
model_extra_keys: Optional[set[str]] = None # noqa: UP045
model_extra_keys_without_x_prefix: Optional[set[str]] = None # noqa: UP045
openapi_scopes: Optional[list[OpenAPIScope]] = [OpenAPIScope.Schemas] # noqa: UP045
include_path_parameters: bool = False
openapi_include_paths: Optional[list[str]] = None # noqa: UP045
graphql_no_typename: bool = False
wrap_string_literal: Optional[bool] = None # noqa: UP045
use_title_as_name: bool = False
use_operation_id_as_name: bool = False
use_unique_items_as_set: bool = False
use_tuple_for_fixed_items: bool = False
allof_merge_mode: AllOfMergeMode = AllOfMergeMode.Constraints
allof_class_hierarchy: AllOfClassHierarchy = AllOfClassHierarchy.IfNoConflict
http_headers: Optional[Sequence[tuple[str, str]]] = None # noqa: UP045
http_ignore_tls: bool = False
http_timeout: Optional[float] = None # noqa: UP045
use_annotated: bool = False
use_serialize_as_any: bool = False
use_non_positive_negative_number_constrained_types: bool = False
use_decimal_for_multiple_of: bool = False
original_field_name_delimiter: Optional[str] = None # noqa: UP045
use_double_quotes: bool = False
collapse_root_models: bool = False
collapse_root_models_name_strategy: Optional[CollapseRootModelsNameStrategy] = None # noqa: UP045
collapse_reuse_models: bool = False
skip_root_model: bool = False
use_type_alias: bool = False
use_root_model_type_alias: bool = False
special_field_name_prefix: Optional[str] = None # noqa: UP045
remove_special_field_name_prefix: bool = False
capitalise_enum_members: bool = False
keep_model_order: bool = False
custom_file_header: Optional[str] = None # noqa: UP045
custom_file_header_path: Optional[Path] = None # noqa: UP045
custom_formatters: Optional[list[str]] = None # noqa: UP045
custom_formatters_kwargs: Optional[TextIOBase] = None # noqa: UP045
use_pendulum: bool = False
use_standard_primitive_types: bool = False
http_query_parameters: Optional[Sequence[tuple[str, str]]] = None # noqa: UP045
treat_dot_as_module: Optional[bool] = None # noqa: UP045
use_exact_imports: bool = False
union_mode: Optional[UnionMode] = None # noqa: UP045
output_datetime_class: Optional[DatetimeClassType] = None # noqa: UP045
output_date_class: Optional[DateClassType] = None # noqa: UP045
keyword_only: bool = False
frozen_dataclasses: bool = False
dataclass_arguments: Optional[DataclassArguments] = None # noqa: UP045
no_alias: bool = False
use_frozen_field: bool = False
use_default_factory_for_optional_nested_models: bool = False
formatters: list[Formatter] | None = None
parent_scoped_naming: bool = False
naming_strategy: Optional[NamingStrategy] = None # noqa: UP045
duplicate_name_suffix: Optional[dict[str, str]] = None # noqa: UP045
disable_future_imports: bool = False
type_mappings: Optional[list[str]] = None # noqa: UP045
type_overrides: Optional[dict[str, str]] = None # noqa: UP045
read_only_write_only_model_type: Optional[ReadOnlyWriteOnlyModelType] = None # noqa: UP045
use_status_code_in_response_name: bool = False
all_exports_scope: Optional[AllExportsScope] = None # noqa: UP045
all_exports_collision_strategy: Optional[AllExportsCollisionStrategy] = None # noqa: UP045
field_type_collision_strategy: Optional[FieldTypeCollisionStrategy] = None # noqa: UP045
module_split_mode: Optional[ModuleSplitMode] = None # noqa: UP045
watch: bool = False
watch_delay: float = 0.5
def merge_args(self, args: Namespace) -> None:
"""Merge command-line arguments into config."""
set_args = {f: getattr(args, f) for f in self.get_fields() if getattr(args, f) is not None}
if set_args.get("output_model_type") == DataModelType.MsgspecStruct.value:
set_args["use_annotated"] = True
if set_args.get("use_annotated"):
set_args["field_constraints"] = True
parsed_args = Config.parse_obj(set_args)
for field_name in set_args:
setattr(self, field_name, getattr(parsed_args, field_name))
def _extract_additional_imports(extra_template_data: defaultdict[str, dict[str, Any]]) -> list[str]:
"""Extract additional_imports from extra_template_data entries."""
additional_imports: list[str] = []
for type_data in extra_template_data.values():
if "additional_imports" in type_data:
imports = type_data.pop("additional_imports")
if isinstance(imports, str):
if imports.strip():
additional_imports.append(imports.strip())
elif isinstance(imports, list):
additional_imports.extend(item.strip() for item in imports if isinstance(item, str) and item.strip())
return additional_imports
def _resolve_profile_extends(
profiles: dict[str, Any],
profile_name: str,
visited: set[str] | None = None,
) -> dict[str, Any]:
"""Resolve profile inheritance via extends key."""
if visited is None:
visited = set()
if profile_name in visited:
chain = " -> ".join(visited) + f" -> {profile_name}"
msg = f"Circular extends detected: {chain}"
raise Error(msg)
if profile_name not in profiles:
available = list(profiles.keys()) if profiles else "none"
msg = f"Extended profile '{profile_name}' not found in pyproject.toml. Available profiles: {available}"
raise Error(msg)
visited.add(profile_name)
profile = profiles[profile_name]
extends = profile.get("extends")
if not extends:
return dict(profile.items())
parents = [extends] if isinstance(extends, str) else extends
result: dict[str, Any] = {}
for parent in parents:
if parent == profile_name:
msg = f"Profile '{profile_name}' cannot extend itself"
raise Error(msg)
parent_config = _resolve_profile_extends(profiles, parent, visited.copy())
result.update(parent_config)
result.update({k: v for k, v in profile.items() if k != "extends"})
return result
def _get_pyproject_toml_config(source: Path, profile: str | None = None) -> dict[str, Any]:
"""Find and return the [tool.datamodel-codegen] section of the closest pyproject.toml if it exists."""
current_path = source
while current_path != current_path.parent:
if (current_path / "pyproject.toml").is_file():
pyproject_toml = load_toml(current_path / "pyproject.toml")
if "datamodel-codegen" in pyproject_toml.get("tool", {}):
tool_config = pyproject_toml["tool"]["datamodel-codegen"]
base_config: dict[str, Any] = {k: v for k, v in tool_config.items() if k != "profiles"}
if profile:
profiles = tool_config.get("profiles", {})
if profile not in profiles:
available = list(profiles.keys()) if profiles else "none"
msg = f"Profile '{profile}' not found in pyproject.toml. Available profiles: {available}"
raise Error(msg)
resolved_profile = _resolve_profile_extends(profiles, profile)
base_config.update(resolved_profile)
pyproject_config = {k.replace("-", "_"): v for k, v in base_config.items()}
if (
"capitalize_enum_members" in pyproject_config and "capitalise_enum_members" not in pyproject_config
): # pragma: no cover
pyproject_config["capitalise_enum_members"] = pyproject_config.pop("capitalize_enum_members")
return pyproject_config
if (current_path / ".git").exists():
break
current_path = current_path.parent
if profile:
msg = f"Profile '{profile}' requested but no [tool.datamodel-codegen] section found in pyproject.toml"
raise Error(msg)
return {}
TomlValue: TypeAlias = str | bool | list["TomlValue"] | tuple["TomlValue", ...]
def _format_toml_value(value: TomlValue) -> str:
"""Format a Python value as a TOML value string."""
if isinstance(value, bool):
return "true" if value else "false"
if isinstance(value, str):
return f'"{value}"'
formatted_items = [_format_toml_value(item) for item in value]
return f"[{', '.join(formatted_items)}]"
def generate_pyproject_config(args: Namespace) -> str:
"""Generate pyproject.toml [tool.datamodel-codegen] section from CLI arguments."""
lines: list[str] = ["[tool.datamodel-codegen]"]
args_dict: dict[str, object] = vars(args)
for key, value in sorted(args_dict.items()):
if value is None:
continue
if key in EXCLUDED_CONFIG_OPTIONS:
continue
toml_key = key.replace("_", "-")
toml_value = _format_toml_value(cast("TomlValue", value))
lines.append(f"{toml_key} = {toml_value}")
return "\n".join(lines) + "\n"
def _normalize_line_endings(text: str) -> str:
"""Normalize line endings to LF for cross-platform comparison."""
return text.replace("\r\n", "\n")
def _compare_single_file(
generated_path: Path,
actual_path: Path,
encoding: str,
) -> tuple[bool, list[str]]:
"""Compare generated file content with existing file.
Returns:
Tuple of (has_differences, diff_lines)
- has_differences: True if files differ or actual file doesn't exist
- diff_lines: List of diff lines for output
"""
generated_content = _normalize_line_endings(generated_path.read_text(encoding=encoding))
if not actual_path.exists():
return True, [f"MISSING: {actual_path} (file does not exist but should be generated)"]
actual_content = _normalize_line_endings(actual_path.read_text(encoding=encoding))
if generated_content == actual_content:
return False, []
diff_lines = list(
difflib.unified_diff(
actual_content.splitlines(keepends=True),
generated_content.splitlines(keepends=True),
fromfile=str(actual_path),
tofile=f"{actual_path} (expected)",
)
)
return True, diff_lines
def _compare_directories(
generated_dir: Path,
actual_dir: Path,
encoding: str,
) -> tuple[list[str], list[str], list[str]]:
"""Compare generated directory with existing directory."""
diffs: list[str] = []
generated_files = {path.relative_to(generated_dir) for path in generated_dir.rglob("*.py")}
actual_files: set[Path] = set()
if actual_dir.exists():
for path in actual_dir.rglob("*.py"):
if "__pycache__" not in path.parts:
actual_files.add(path.relative_to(actual_dir))
missing_files = [str(rel_path) for rel_path in sorted(generated_files - actual_files)]
extra_files = [str(rel_path) for rel_path in sorted(actual_files - generated_files)]
for rel_path in sorted(generated_files & actual_files):
generated_content = _normalize_line_endings((generated_dir / rel_path).read_text(encoding=encoding))
actual_content = _normalize_line_endings((actual_dir / rel_path).read_text(encoding=encoding))
if generated_content != actual_content:
diffs.extend(
difflib.unified_diff(
actual_content.splitlines(keepends=True),
generated_content.splitlines(keepends=True),
fromfile=str(rel_path),
tofile=f"{rel_path} (expected)",
)
)
return diffs, missing_files, extra_files
def _format_cli_value(value: str | list[str]) -> str:
"""Format a value for CLI argument."""
if isinstance(value, list):
return " ".join(f'"{v}"' if " " in v else v for v in value)
return f'"{value}"' if " " in value else value
def generate_cli_command(config: dict[str, TomlValue]) -> str:
"""Generate CLI command from pyproject.toml configuration."""
parts: list[str] = ["datamodel-codegen"]
for key, value in sorted(config.items()):
if key in EXCLUDED_CONFIG_OPTIONS:
continue
cli_key = key.replace("_", "-")
if isinstance(value, bool):
if value:
parts.append(f"--{cli_key}")
elif key in BOOLEAN_OPTIONAL_OPTIONS:
parts.append(f"--no-{cli_key}")
elif isinstance(value, list):
parts.extend((f"--{cli_key}", _format_cli_value(cast("list[str]", value))))
else:
parts.extend((f"--{cli_key}", _format_cli_value(str(value))))
return " ".join(parts) + "\n"
def _load_json_config(
file_handle: TextIOBase | None,
name: str,
validator: Callable[[Any], str | None],
) -> tuple[dict[str, Any] | None, str | None]:
"""Load and validate a JSON configuration file.
Args:
file_handle: The file handle to read from, or None.
name: The name of the config for error messages.
validator: A function that validates the loaded data and returns an error message or None.
Returns:
A tuple of (loaded_dict, error_message). If successful, error_message is None.
If file_handle is None, returns (None, None).
"""
if file_handle is None:
return None, None
with file_handle as data:
try:
result = json.load(data)
except json.JSONDecodeError as e:
return None, f"Unable to load {name}: {e}"
error = validator(result)
if error:
return None, f"Unable to load {name}: {error}"
return result, None
def run_generate_from_config( # noqa: PLR0913, PLR0917
config: Config,
input_: Path | str | ParseResult,
output: Path | None,
extra_template_data: dict[str, Any] | None,
aliases: dict[str, str] | None,
command_line: str | None,
custom_formatters_kwargs: dict[str, str] | None,
settings_path: Path | None = None,
default_value_overrides: dict[str, Any] | None = None,
) -> None:
"""Run code generation with the given config and parameters."""
result = generate(
input_=input_,
input_file_type=config.input_file_type,
output=output,
output_model_type=config.output_model_type,
target_python_version=config.target_python_version,
target_pydantic_version=config.target_pydantic_version,
base_class=config.base_class,
base_class_map=config.base_class_map,
additional_imports=config.additional_imports,
class_decorators=config.class_decorators,
custom_template_dir=config.custom_template_dir,
validation=config.validation,
field_constraints=config.field_constraints,
snake_case_field=config.snake_case_field,
strip_default_none=config.strip_default_none,
extra_template_data=extra_template_data, # pyright: ignore[reportArgumentType]
aliases=aliases,
disable_timestamp=config.disable_timestamp,
enable_version_header=config.enable_version_header,
enable_command_header=config.enable_command_header,
command_line=command_line,
allow_population_by_field_name=config.allow_population_by_field_name,
allow_extra_fields=config.allow_extra_fields,
extra_fields=config.extra_fields,
use_generic_base_class=config.use_generic_base_class,
apply_default_values_for_required_fields=config.use_default,
force_optional_for_required_fields=config.force_optional,
class_name=config.class_name,
class_name_prefix=config.class_name_prefix,
class_name_suffix=config.class_name_suffix,
class_name_affix_scope=config.class_name_affix_scope,
use_standard_collections=config.use_standard_collections,
use_schema_description=config.use_schema_description,
use_field_description=config.use_field_description,
use_field_description_example=config.use_field_description_example,
use_attribute_docstrings=config.use_attribute_docstrings,
use_inline_field_description=config.use_inline_field_description,
use_default_kwarg=config.use_default_kwarg,
reuse_model=config.reuse_model,
reuse_scope=config.reuse_scope,
shared_module_name=config.shared_module_name,
encoding=config.encoding,
enum_field_as_literal=config.enum_field_as_literal,
enum_field_as_literal_map=config.enum_field_as_literal_map,
ignore_enum_constraints=config.ignore_enum_constraints,
use_one_literal_as_default=config.use_one_literal_as_default,
use_enum_values_in_discriminator=config.use_enum_values_in_discriminator,
set_default_enum_member=config.set_default_enum_member,
use_subclass_enum=config.use_subclass_enum,
use_specialized_enum=config.use_specialized_enum,
strict_nullable=config.strict_nullable,
use_generic_container_types=config.use_generic_container_types,
enable_faux_immutability=config.enable_faux_immutability,
disable_appending_item_suffix=config.disable_appending_item_suffix,
strict_types=config.strict_types,
empty_enum_field_name=config.empty_enum_field_name,
field_extra_keys=config.field_extra_keys,
field_include_all_keys=config.field_include_all_keys,
field_extra_keys_without_x_prefix=config.field_extra_keys_without_x_prefix,
model_extra_keys=config.model_extra_keys,
model_extra_keys_without_x_prefix=config.model_extra_keys_without_x_prefix,
openapi_scopes=config.openapi_scopes,
include_path_parameters=config.include_path_parameters,
openapi_include_paths=config.openapi_include_paths,
graphql_no_typename=config.graphql_no_typename,
wrap_string_literal=config.wrap_string_literal,
use_title_as_name=config.use_title_as_name,
use_operation_id_as_name=config.use_operation_id_as_name,
use_unique_items_as_set=config.use_unique_items_as_set,
use_tuple_for_fixed_items=config.use_tuple_for_fixed_items,
allof_merge_mode=config.allof_merge_mode,
allof_class_hierarchy=config.allof_class_hierarchy,
http_headers=config.http_headers,
http_ignore_tls=config.http_ignore_tls,
http_timeout=config.http_timeout,
use_annotated=config.use_annotated,
use_serialize_as_any=config.use_serialize_as_any,
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,
original_field_name_delimiter=config.original_field_name_delimiter,
use_double_quotes=config.use_double_quotes,
collapse_root_models=config.collapse_root_models,
collapse_root_models_name_strategy=config.collapse_root_models_name_strategy,
collapse_reuse_models=config.collapse_reuse_models,
skip_root_model=config.skip_root_model,
use_type_alias=config.use_type_alias,
use_root_model_type_alias=config.use_root_model_type_alias,
use_union_operator=config.use_union_operator,
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,
keep_model_order=config.keep_model_order,
custom_file_header=config.custom_file_header,
custom_file_header_path=config.custom_file_header_path,
custom_formatters=config.custom_formatters,
custom_formatters_kwargs=custom_formatters_kwargs,
use_pendulum=config.use_pendulum,
use_standard_primitive_types=config.use_standard_primitive_types,