-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathpost_generate_fixes.py
More file actions
3326 lines (2866 loc) · 133 KB
/
Copy pathpost_generate_fixes.py
File metadata and controls
3326 lines (2866 loc) · 133 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
#!/usr/bin/env python3
# ruff: noqa: E501
"""
Post-generation fixes for generated Pydantic models.
This script applies necessary modifications to generated files that cannot be
handled by datamodel-code-generator directly:
1. Rewrites generated string enums to StrEnum
2. Adds model_validators to types requiring mutual exclusivity checks
3. Fixes self-referential RootModel type annotations
4. Fixes BrandManifest forward references
5. Adds deprecated=True to fields marked deprecated in JSON schema
6. Unwraps specified RootModel unions to plain Union type aliases (#155)
7. Widens canceled: Literal[True] = True on request types to | None = None (#641)
"""
from __future__ import annotations
import ast
import importlib.util
import json
import re
from copy import deepcopy
from pathlib import Path
from typing import Any
REPO_ROOT = Path(__file__).parent.parent
# Load ``resolve_bundle_key`` from its source file rather than via the
# ``adcp`` package — this script runs after datamodel-codegen produces a
# fresh ``generated_poc/`` tree, before the post-fixes that make it
# importable. ``adcp/__init__.py`` would crash on the unfixed models.
def _load_resolve_bundle_key():
src = REPO_ROOT / "src" / "adcp" / "validation" / "version.py"
spec = importlib.util.spec_from_file_location("_adcp_bundle_key", src)
assert spec is not None and spec.loader is not None
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod.resolve_bundle_key
resolve_bundle_key = _load_resolve_bundle_key()
_VERSION_FILE = REPO_ROOT / "src" / "adcp" / "ADCP_VERSION"
_BUNDLE_KEY = resolve_bundle_key(_VERSION_FILE.read_text().strip())
OUTPUT_DIR = REPO_ROOT / "src" / "adcp" / "types" / "generated_poc"
SCHEMA_DIR = REPO_ROOT / "schemas" / "cache" / _BUNDLE_KEY
_PROTOCOL_ENVELOPE_IMPORT = "from ..core.protocol_envelope import ProtocolEnvelope\n"
_VERSION_ENVELOPE_IMPORT = "from ..core.version_envelope import AdcpVersionEnvelope\n"
_STR_ENUM_MEMBER_ASSIGNMENT_IGNORE = " # type: ignore[assignment]"
_STR_ATTRIBUTE_NAMES = set(dir(str))
def _sync_protocol_envelope_import(source: str) -> str:
"""Keep the ProtocolEnvelope import aligned with restored response arms."""
uses_protocol_envelope = "ProtocolEnvelope" in source.replace(_PROTOCOL_ENVELOPE_IMPORT, "")
if not uses_protocol_envelope:
return source.replace(_PROTOCOL_ENVELOPE_IMPORT, "")
if _PROTOCOL_ENVELOPE_IMPORT in source:
return source
if _VERSION_ENVELOPE_IMPORT in source:
return source.replace(
_VERSION_ENVELOPE_IMPORT,
_PROTOCOL_ENVELOPE_IMPORT + _VERSION_ENVELOPE_IMPORT,
1,
)
future_import = "from __future__ import annotations\n\n"
if future_import in source:
return source.replace(future_import, future_import + _PROTOCOL_ENVELOPE_IMPORT, 1)
return _PROTOCOL_ENVELOPE_IMPORT + source
def add_model_validator_to_product():
"""Add model_validators to Product class.
NOTE: This function is now deprecated after PR #213 added explicit discriminator
to publisher_properties schema. Pydantic now generates proper discriminated union
variants (PublisherProperties, PublisherProperties4, PublisherProperties5) with
Literal discriminator fields, which Pydantic validates automatically.
Keeping function as no-op for backwards compatibility with older schemas.
"""
print(" product.py validation: no fixes needed (Pydantic handles discriminated unions)")
def _ignore_strenum_member_method_collisions(source: str) -> tuple[str, int]:
"""Suppress mypy for StrEnum members that intentionally shadow str methods."""
lines = source.splitlines()
updated: list[str] = []
class_indent: int | None = None
ignores_added = 0
for line in lines:
stripped = line.lstrip()
indent = len(line) - len(stripped)
class_match = re.match(r"class\s+\w+\(StrEnum\):", stripped)
if class_match is not None:
class_indent = indent
updated.append(line)
continue
if class_indent is not None and stripped and indent <= class_indent:
class_indent = None
if class_indent is not None and indent == class_indent + 4:
assignment_match = re.match(r"([A-Za-z_]\w*)\s*=", stripped)
if (
assignment_match is not None
and assignment_match.group(1) in _STR_ATTRIBUTE_NAMES
and _STR_ENUM_MEMBER_ASSIGNMENT_IGNORE not in line
):
line = f"{line}{_STR_ENUM_MEMBER_ASSIGNMENT_IGNORE}"
ignores_added += 1
updated.append(line)
return "\n".join(updated) + ("\n" if source.endswith("\n") else ""), ignores_added
def rewrite_generated_enums_to_strenum() -> None:
"""Make all generated schema enums inherit from StrEnum.
datamodel-code-generator emits plain ``Enum`` classes for string-valued
JSON Schema enums. The generated enum members should behave like their wire
values for equality, hashing, formatting, and ``str()`` without widening or
narrowing any model field annotations.
"""
files_changed = 0
classes_changed = 0
ignores_added = 0
for path in OUTPUT_DIR.rglob("*.py"):
source = path.read_text()
if (
"(Enum):" not in source
and "from enum import Enum" not in source
and "(StrEnum):" not in source
):
continue
updated = source.replace(
"from enum import Enum, IntEnum\n",
"from enum import IntEnum\nfrom adcp.types._str_enum import StrEnum\n",
)
updated = updated.replace(
"from enum import IntEnum, Enum\n",
"from enum import IntEnum\nfrom adcp.types._str_enum import StrEnum\n",
)
updated = updated.replace(
"from enum import Enum\n",
"from adcp.types._str_enum import StrEnum\n",
)
updated, changed = re.subn(r"\((?:str,\s*)?Enum\):", "(StrEnum):", updated)
updated, file_ignores_added = _ignore_strenum_member_method_collisions(updated)
if updated != source:
path.write_text(updated)
files_changed += 1
classes_changed += changed
ignores_added += file_ignores_added
print(
f" generated enums rewritten to StrEnum "
f"({classes_changed} classes across {files_changed} files, "
f"{ignores_added} member type ignore(s))"
)
def fix_preview_render_self_reference():
"""Fix self-referential RootModel in preview_render.py."""
preview_file = OUTPUT_DIR / "creative" / "preview_render.py"
if not preview_file.exists():
print(" preview_render.py not found (skipping)")
return
with open(preview_file) as f:
content = f.read()
# Check if already fixed
if "preview_render.PreviewRender1" not in content:
print(" preview_render.py already fixed or doesn't need fixing")
return
# Replace module-qualified names with direct class names
content = content.replace("preview_render.PreviewRender1", "PreviewRender1")
content = content.replace("preview_render.PreviewRender2", "PreviewRender2")
content = content.replace("preview_render.PreviewRender3", "PreviewRender3")
with open(preview_file, "w") as f:
f.write(content)
print(" preview_render.py self-references fixed")
def fix_brand_manifest_references():
"""Fix BrandManifest forward references in promoted_offerings.py.
datamodel-code-generator imports brand_manifest with an alias (_1 suffix)
but then references it without the alias in the type annotation.
This fix updates the type annotation to use the correct alias.
"""
promoted_offerings_file = OUTPUT_DIR / "core" / "promoted_offerings.py"
if not promoted_offerings_file.exists():
print(" promoted_offerings.py not found (skipping)")
return
with open(promoted_offerings_file) as f:
content = f.read()
# Check if already fixed
if "brand_manifest_1.BrandManifest" in content:
print(" promoted_offerings.py already fixed")
return
# Fix the import alias mismatch
# Line imports: from . import brand_manifest as brand_manifest_1
# But uses: brand_manifest.BrandManifest
# Need to change to: brand_manifest_1.BrandManifest
content = content.replace("brand_manifest.BrandManifest", "brand_manifest_1.BrandManifest")
with open(promoted_offerings_file, "w") as f:
f.write(content)
print(" promoted_offerings.py brand_manifest references fixed")
def fix_enum_defaults():
"""Fix enum default values in generated files.
datamodel-code-generator sometimes creates string defaults for enum fields
instead of enum member defaults, causing mypy errors.
Note: brand_manifest_ref.py was a stale file and has been removed.
The enum defaults in brand_manifest.py are already correct.
"""
brand_manifest_file = OUTPUT_DIR / "core" / "brand_manifest.py"
if not brand_manifest_file.exists():
print(" brand_manifest.py not found (skipping)")
else:
with open(brand_manifest_file) as f:
content = f.read()
# Check if already fixed (using enum member, not string)
if "FeedFormat.google_merchant_center" in content:
print(" brand_manifest.py enum defaults already correct")
else:
# Fix ProductCatalog.feed_format default if needed
content = content.replace(
'feed_format: FeedFormat | None = Field("google_merchant_center"',
"feed_format: FeedFormat | None = Field(FeedFormat.google_merchant_center",
)
# Fix BrandManifest.feed_format default if needed
content = content.replace(
'product_feed_format: FeedFormat | None = Field("google_merchant_center"',
"product_feed_format: FeedFormat | None = Field(FeedFormat.google_merchant_center",
)
with open(brand_manifest_file, "w") as f:
f.write(content)
print(" brand_manifest.py enum defaults fixed")
bundled_media_buys_file = OUTPUT_DIR / "bundled" / "media_buy" / "get_media_buys_response.py"
if bundled_media_buys_file.exists():
content = bundled_media_buys_file.read_text()
new_content = content.replace(
"] = 'ok'\n impairments: Annotated[\n",
"] = 'ok' # type: ignore[assignment]\n impairments: Annotated[\n",
1,
)
if new_content != content:
bundled_media_buys_file.write_text(new_content)
print(" bundled/media_buy/get_media_buys_response.py health enum default fixed")
def fix_preview_creative_request_discriminator():
"""Add discriminator to PreviewCreativeRequest union.
The schema uses request_type as a discriminator with const values 'single'
and 'batch', but datamodel-code-generator doesn't add the discriminator to
the Field annotation. This adds it explicitly for Pydantic to properly
validate the union.
"""
preview_request_file = OUTPUT_DIR / "creative" / "preview_creative_request.py"
if not preview_request_file.exists():
print(" preview_creative_request.py not found (skipping)")
return
with open(preview_request_file) as f:
content = f.read()
# Check if already fixed
if "discriminator='request_type'" in content:
print(" preview_creative_request.py discriminator already added")
return
# Add discriminator to the Field
content = content.replace(
"Field(\n description='Request to generate previews",
"Field(\n discriminator='request_type',\n description='Request to generate previews",
)
with open(preview_request_file, "w") as f:
f.write(content)
print(" preview_creative_request.py discriminator added")
def add_deprecated_field_metadata():
"""Add deprecated=True to fields marked deprecated in JSON schema.
datamodel-code-generator doesn't translate JSON Schema's "deprecated": true
to Pydantic's Field(deprecated=True). This function reads the schemas and
injects the metadata into the generated Python files.
"""
deprecated_fields_fixed = 0
# Walk through all schema files
for schema_file in SCHEMA_DIR.rglob("*.json"):
try:
with open(schema_file) as f:
schema = json.load(f)
except (json.JSONDecodeError, OSError):
continue
# Find deprecated fields in properties
properties = schema.get("properties", {})
deprecated_fields = [
field_name
for field_name, field_def in properties.items()
if isinstance(field_def, dict) and field_def.get("deprecated") is True
]
if not deprecated_fields:
continue
# Map schema file to generated Python file
relative_path = schema_file.relative_to(SCHEMA_DIR)
# Convert path: core/format.json -> core/format.py
py_path = OUTPUT_DIR / relative_path.with_suffix(".py")
# Handle kebab-case to snake_case conversion
py_path = py_path.parent / py_path.name.replace("-", "_")
if not py_path.exists():
continue
with open(py_path) as f:
content = f.read()
modified = False
for field_name in deprecated_fields:
field_block = _find_indented_field_block(content, field_name)
if field_block is None:
continue
field_start, field_end = field_block
field_section = content[field_start:field_end]
if "deprecated=True" in field_section.split("] = ")[0]:
continue # Already fixed
field_call_offset = field_section.find("Field(")
if field_call_offset == -1:
continue
insert_pos = field_start + field_call_offset + len("Field(")
# Check what comes after - if it's description=, add before it.
after_match = content[insert_pos : insert_pos + 50]
if after_match.strip().startswith("description="):
new_content = (
content[:insert_pos] + "deprecated=True,\n " + content[insert_pos:]
)
else:
new_content = content[:insert_pos] + "deprecated=True, " + content[insert_pos:]
if new_content != content:
content = new_content
modified = True
deprecated_fields_fixed += 1
if modified:
with open(py_path, "w") as f:
f.write(content)
if deprecated_fields_fixed > 0:
print(f" Added deprecated=True to {deprecated_fields_fixed} field(s)")
else:
print(" No deprecated fields needed fixing")
def apply_open_payload_config():
"""Apply ``x-adcp-open-payload`` to generated named models.
``datamodel-code-generator`` ignores custom schema keywords. Current
open-payload annotations are mostly anonymous object fields and already
generate ``dict[str, Any]`` because the schema object also carries
``additionalProperties: true``. When the annotation appears on a named
schema object, make the corresponding generated model explicitly
extension-tolerant so the custom keyword remains contract-bearing.
"""
updated_classes = 0
already_open = 0
anonymous_annotations = 0
for schema_file in SCHEMA_DIR.rglob("*.json"):
try:
schema = json.loads(schema_file.read_text())
except (json.JSONDecodeError, OSError):
continue
class_names, anonymous_count = _open_payload_class_names(schema)
anonymous_annotations += anonymous_count
if not class_names:
continue
relative_path = schema_file.relative_to(SCHEMA_DIR)
py_path = OUTPUT_DIR / relative_path.with_suffix(".py")
py_path = py_path.parent / py_path.name.replace("-", "_")
if not py_path.exists():
continue
content = py_path.read_text()
original = content
for class_name in class_names:
if class_name is None:
class_name = _first_generated_class_name(content)
if class_name is None:
continue
content, status = _set_class_extra_allow(content, class_name)
if status == "updated":
updated_classes += 1
elif status == "already":
already_open += 1
if content != original:
content = _ensure_configdict_import(content)
py_path.write_text(content)
if updated_classes:
print(f" Applied x-adcp-open-payload extra='allow' to {updated_classes} class(es)")
else:
print(" No named x-adcp-open-payload classes needed model_config changes")
if already_open:
print(f" {already_open} x-adcp-open-payload class(es) already allowed extras")
if anonymous_annotations:
print(
" "
f"{anonymous_annotations} anonymous x-adcp-open-payload annotation(s) "
"remain dict[str, Any] fields"
)
def _open_payload_class_names(schema: dict) -> tuple[list[str | None], int]:
"""Return generated class names for named open-payload schema objects.
``None`` is a sentinel for the root schema's first generated class when
the schema has no title. Anonymous property annotations are counted but do
not map to model classes; datamodel-code-generator emits those as mapping
fields.
"""
class_names: list[str | None] = []
anonymous_count = 0
def walk(obj: object, path: tuple[str, ...]) -> None:
nonlocal anonymous_count
if isinstance(obj, dict):
if obj.get("x-adcp-open-payload") is True:
title = obj.get("title")
if path == ():
class_names.append(_schema_title_to_class_name(title) if title else None)
elif isinstance(title, str) and title.strip():
class_names.append(_schema_title_to_class_name(title))
else:
anonymous_count += 1
for key, value in obj.items():
walk(value, (*path, key))
elif isinstance(obj, list):
for index, value in enumerate(obj):
walk(value, (*path, str(index)))
walk(schema, ())
return class_names, anonymous_count
def _schema_title_to_class_name(title: object) -> str:
words = re.findall(r"[A-Za-z0-9]+", str(title))
return "".join(word[:1].upper() + word[1:] for word in words)
def _first_generated_class_name(content: str) -> str | None:
match = re.search(r"^class ([A-Za-z_]\w*)\b", content, re.MULTILINE)
return match.group(1) if match else None
def _set_class_extra_allow(content: str, class_name: str) -> tuple[str, str]:
class_pattern = re.compile(
rf"(^class {re.escape(class_name)}\b[^\n]*:\n)(.*?)(?=^class |\Z)",
re.MULTILINE | re.DOTALL,
)
match = class_pattern.search(content)
if match is None:
return content, "missing"
header = match.group(1)
body = match.group(2)
config_pattern = re.compile(r"( model_config = ConfigDict\(\n)(.*?)( \)\n)", re.DOTALL)
config_match = config_pattern.search(body)
# Compact single-line form: ` model_config = ConfigDict(<args>)`. The
# open paren is not immediately followed by a newline, so the multi-line
# pattern above never matches it.
compact_pattern = re.compile(r"( model_config = ConfigDict\()([^\n]*?)(\)\n)")
compact_match = compact_pattern.search(body)
if config_match is not None:
config_body = config_match.group(2)
if re.search(r"extra=(['\"])allow\1", config_body):
return content, "already"
if re.search(r"extra=(['\"])(?:forbid|ignore)\1", config_body):
new_config_body = re.sub(
r"extra=(['\"])(?:forbid|ignore)\1",
"extra='allow'",
config_body,
count=1,
)
else:
new_config_body = " extra='allow',\n" + config_body
new_body = (
body[: config_match.start()]
+ config_match.group(1)
+ new_config_body
+ config_match.group(3)
+ body[config_match.end() :]
)
elif compact_match is not None:
config_args = compact_match.group(2)
if re.search(r"extra=(['\"])allow\1", config_args):
return content, "already"
if re.search(r"extra=(['\"])(?:forbid|ignore)\1", config_args):
new_config_args = re.sub(
r"extra=(['\"])(?:forbid|ignore)\1",
"extra='allow'",
config_args,
count=1,
)
elif config_args.strip():
new_config_args = "extra='allow', " + config_args
else:
new_config_args = "extra='allow'"
new_body = (
body[: compact_match.start()]
+ compact_match.group(1)
+ new_config_args
+ compact_match.group(3)
+ body[compact_match.end() :]
)
else:
new_body = " model_config = ConfigDict(\n extra='allow',\n )\n" + body
return (
content[: match.start()] + header + new_body + content[match.end() :],
"updated",
)
def _ensure_configdict_import(content: str) -> str:
if "ConfigDict" not in content or "from pydantic import" not in content:
return content
if re.search(r"^from pydantic import .*ConfigDict", content, re.MULTILINE):
return content
return re.sub(
r"^from pydantic import ([^\n]+)$",
lambda m: (
"from pydantic import "
+ ", ".join(sorted({*[part.strip() for part in m.group(1).split(",")], "ConfigDict"}))
),
content,
count=1,
flags=re.MULTILINE,
)
def _find_indented_field_block(content: str, field_name: str) -> tuple[int, int] | None:
"""Return absolute offsets for a generated four-space field block."""
cursor = 0
field_prefix = f" {field_name}:"
while cursor < len(content):
line_end = content.find("\n", cursor)
if line_end == -1:
line_end = len(content)
next_cursor = len(content)
else:
line_end += 1
next_cursor = line_end
if content.startswith(field_prefix, cursor):
block_end = next_cursor
scan = next_cursor
while scan < len(content):
next_end = content.find("\n", scan)
if next_end == -1:
next_end = len(content)
next_scan = len(content)
else:
next_end += 1
next_scan = next_end
line = content[scan:next_end]
if re.match(r"^ [a-zA-Z_]", line) or line.startswith("class "):
break
block_end = next_scan
scan = next_scan
return cursor, block_end
cursor = next_cursor
return None
def fix_constr_type_annotations():
"""Replace constr(pattern=...) with Annotated[str, StringConstraints(pattern=...)] in generated files.
datamodel-code-generator uses constr(pattern=...) as dict key types, but mypy's
Pydantic v2 plugin rejects this form. The correct form is Annotated[str, StringConstraints(...)].
"""
fixed_count = 0
for py_file in OUTPUT_DIR.rglob("*.py"):
with open(py_file) as f:
content = f.read()
if "constr(pattern=" not in content:
continue
original = content
# Replace constr(pattern=r'...') with Annotated[str, StringConstraints(pattern=r'...')]
content = re.sub(
r"constr\(pattern=(r'[^']*')\)",
r"Annotated[str, StringConstraints(pattern=\1)]",
content,
)
# Replace 'constr' in imports with 'StringConstraints'
content = re.sub(r"\bconstr\b", "StringConstraints", content)
if content != original:
with open(py_file, "w") as f:
f.write(content)
fixed_count += 1
if fixed_count > 0:
print(f" Replaced constr(pattern=...) with StringConstraints in {fixed_count} file(s)")
else:
print(" No constr(pattern=...) annotations needed fixing")
# Types to unwrap from RootModel to Union type alias.
# Only genuine discriminated unions (different field shapes per variant) belong here.
# "Validation-only" oneOf types (same fields, different required combos) are now
# handled at the schema level by flatten_validation_oneof() in generate_types.py,
# which produces a single BaseModel class — no RootModel or unwrapping needed.
# Removed from this set (now single classes): GetCreativeDeliveryRequest,
# GetSignalsRequest, ProvidePerformanceFeedbackRequest, SiSendMessageRequest,
# UpdateMediaBuyRequest.
# See: https://github.com/adcontextprotocol/adcp-client-python/issues/155
_UNWRAP_TO_UNION: set[str] = {
"AcquireRightsResponse",
"ComplyTestControllerRequest",
"ComplyTestControllerResponse",
"ActivateSignalResponse",
"BuildCreativeRequest",
"BuildCreativeResponse",
"CalibrateContentResponse",
"CreateContentStandardsResponse",
"CreateMediaBuyResponse",
"CreativeApprovalResponse",
"GetAccountFinancialsResponse",
"GetBrandIdentityResponse",
"GetContentStandardsResponse",
"GetCreativeFeaturesResponse",
"GetMediaBuyArtifactsResponse",
"GetPlanAuditLogsRequest",
"GetProductsRequest",
"GetRightsResponse",
"ListContentStandardsResponse",
"LogEventResponse",
"PreviewCreativeRequest",
"PreviewCreativeResponse",
"ProvidePerformanceFeedbackResponse",
"SyncAccountsResponse",
"SyncAudiencesResponse",
"SyncGovernanceResponse",
"SyncCatalogsResponse",
"SyncCreativesResponse",
"SyncEventSourcesResponse",
"UpdateContentStandardsResponse",
"UpdateMediaBuyResponse",
"UpdateRightsResponse",
"ValidateContentDeliveryResponse",
}
def unwrap_rootmodel_unions():
"""Unwrap specified RootModel unions to plain Union type aliases.
Consumers that subclass library types cannot extend RootModel subclasses
because Pydantic 2 forbids model_config overrides on RootModel.
Uses AST to find class definitions instead of regex, which avoids issues
with nested brackets in base class annotations.
Replaces:
class TypeName(RootModel[Variant1 | Variant2]):
root: Annotated[Variant1 | Variant2, Field(...)]
def __getattr__(self, name): ...
With:
TypeName = Variant1 | Variant2
Note: The types in _UNWRAP_TO_UNION are all Request/Response types whose
root: fields had no meaningful Field(description=..., examples=[...])
metadata. Value-type RootModels that carry rich metadata are intentionally
excluded and keep the RootModel wrapper + __getattr__ proxy.
"""
unwrapped_count = 0
for py_file in OUTPUT_DIR.rglob("*.py"):
with open(py_file) as f:
content = f.read()
if "RootModel[" not in content:
continue
try:
tree = ast.parse(content)
except SyntaxError:
continue
original = content
lines = content.split("\n")
# Collect classes to unwrap (process in reverse order to preserve line numbers)
replacements: list[tuple[int, int, str, str]] = (
[]
) # (start_line, end_line, name, union_types)
for node in ast.walk(tree):
if not isinstance(node, ast.ClassDef) or node.name not in _UNWRAP_TO_UNION:
continue
if not node.end_lineno:
continue
# Find the RootModel[...] base class using AST source segments
for base in node.bases:
base_src = ast.get_source_segment(content, base)
if not base_src or "RootModel[" not in base_src:
continue
# Extract union type from RootModel[...] using bracket depth
# to handle nested generics like RootModel[list[X] | Y]
bracket_start = base_src.index("RootModel[") + len("RootModel[")
depth = 1
pos = bracket_start
while pos < len(base_src) and depth > 0:
if base_src[pos] == "[":
depth += 1
elif base_src[pos] == "]":
depth -= 1
pos += 1
bracket_end = pos - 1 # position of the matching ]
union_types = base_src[bracket_start:bracket_end].strip()
replacements.append((node.lineno, node.end_lineno, node.name, union_types))
break
if not replacements:
continue
# Apply replacements in reverse line order to preserve indices
for start_line, end_line, type_name, union_types in sorted(replacements, reverse=True):
# Wrap multi-line unions in parentheses for valid syntax
if "\n" in union_types:
# Re-indent continuation lines to 4 spaces
union_lines = [ln.strip() for ln in union_types.split("\n")]
indented = union_lines[0] + "\n" + "\n".join(f" {ln}" for ln in union_lines[1:])
replacement = f"{type_name} = (\n {indented}\n)"
else:
replacement = f"{type_name} = {union_types}"
lines[start_line - 1 : end_line] = [replacement]
unwrapped_count += 1
content = "\n".join(lines)
if content != original:
# Remove RootModel from imports if no longer used as a base class
if not re.search(r"\(RootModel\[", content):
content = re.sub(r",\s*RootModel", "", content)
content = re.sub(r"RootModel,\s*", "", content)
# Remove unused Any import if no longer referenced in code body
import_line_end = content.find("\n", content.find("from typing import"))
after_imports = content[import_line_end:] if import_line_end > 0 else ""
if "Any" not in after_imports:
content = re.sub(r"Any,\s*", "", content)
content = re.sub(r",\s*Any", "", content)
with open(py_file, "w") as f:
f.write(content)
if unwrapped_count > 0:
print(f" Unwrapped {unwrapped_count} RootModel union(s) to type aliases")
else:
print(" No RootModel unions needed unwrapping")
def add_rootmodel_getattr_proxy():
"""Add __getattr__ delegation to RootModel union types.
RootModel wrappers around discriminated unions are opaque — accessing
attributes of the inner type requires .root.attribute_name. This adds
__getattr__ so attribute access delegates transparently to the wrapped type.
See: https://github.com/adcontextprotocol/adcp-client-python/issues/145
"""
fixed_count = 0
for py_file in OUTPUT_DIR.rglob("*.py"):
source = py_file.read_text()
if "RootModel[" not in source:
continue
# Already patched
if "def __getattr__" in source:
continue
# Ensure Any is imported before parsing AST (avoids line number shift)
if "from typing import Any" not in source and "Any," not in source:
if "from typing import " in source:
source = source.replace("from typing import ", "from typing import Any, ", 1)
else:
source = "from typing import Any\n" + source
insertions: list[int] = []
for match in re.finditer(r"^class ([A-Za-z_]\w*)\b", source, re.MULTILINE):
header_end = source.find(":\n", match.end())
if header_end == -1:
continue
header = source[match.start() : header_end]
if "RootModel[" not in header or "|" not in header:
continue
next_class = re.compile(r"^class ", re.MULTILINE).search(source, header_end + 2)
insertions.append(next_class.start() if next_class is not None else len(source))
if not insertions:
continue
# Insert __getattr__ methods (reverse order to preserve line numbers)
method = (
"\n"
" def __getattr__(self, name: str) -> Any:\n"
' """Proxy attribute access to the wrapped type."""\n'
" if name.startswith('_'):\n"
" raise AttributeError(name)\n"
" return getattr(self.root, name)\n\n"
)
for offset in sorted(insertions, reverse=True):
source = source[:offset].rstrip() + method + source[offset:]
py_file.write_text(source)
fixed_count += len(insertions)
if fixed_count > 0:
print(f" Added __getattr__ proxy to {fixed_count} RootModel union type(s)")
else:
print(" No RootModel union types needed __getattr__ proxy")
# Response-only list fields changed to Sequence[T] so adopters can narrow the
# element type without type: ignore[assignment] under strict mypy. Only
# response-side fields (received, never mutated) are safe to change; request-
# side list fields (packages/creatives on request types) stay as list[T]
# because adopters call .append() on them. See issue #624.
RESPONSE_SEQUENCE_FIELDS: list[tuple[str, str]] = [
("media_buy/update_media_buy_response.py", "affected_packages"),
("media_buy/get_media_buys_response.py", "media_buys"),
("media_buy/get_media_buys_response.py", "packages"),
("media_buy/get_media_buy_delivery_response.py", "media_buy_deliveries"),
]
def rewrite_response_list_to_sequence() -> None:
"""Change list[T] → Sequence[T] on response-only container fields.
list[T] is invariant so ``affected_packages: list[MyPkg]`` on a subclass
triggers mypy[assignment] against the parent's ``list[Pkg]``. Sequence[T]
is covariant, removing the error for adopters who extend element types.
"""
print("Rewriting response list fields to Sequence for covariant inheritance...")
for rel_path, field_name in RESPONSE_SEQUENCE_FIELDS:
target = OUTPUT_DIR / rel_path
if not target.exists():
print(f" {rel_path}: not found (skipping)")
continue
content = target.read_text()
# Idempotency: skip if field already uses Sequence
if re.search(rf"{re.escape(field_name)}: Annotated\[\s+Sequence\[", content):
print(f" {rel_path}: {field_name} already uses Sequence (skipping)")
continue
new_content = re.sub(
rf"({re.escape(field_name)}: Annotated\[\s+)list\[",
r"\1Sequence[",
content,
)
if new_content == content:
print(f" {rel_path}: {field_name} — list[ pattern not found (skipping)")
continue
# Add Sequence import from collections.abc in stdlib block.
# Anchor on the first stdlib import line (enum or typing) so Sequence
# lands in correct alphabetical position (c < e < t).
if "from collections.abc import Sequence" not in new_content:
new_content = re.sub(
r"^(from (?:enum|typing) import .+)$",
r"from collections.abc import Sequence\n\1",
new_content,
count=1,
flags=re.MULTILINE,
)
target.write_text(new_content)
print(f" {rel_path}: {field_name} → Sequence[...]")
def fix_list_field_shadowing():
"""Fix models where a field named 'list' shadows the builtin list type.
GetPropertyListResponse has a field named 'list' which shadows the builtin
list type in annotations like list[Identifier]. We add a _list = list alias
before the class and replace bare list[] usage in annotations.
"""
target = OUTPUT_DIR / "property" / "get_property_list_response.py"
if not target.exists():
return
content = target.read_text()
if "_list = list" in content:
return # Already fixed
# Add alias before the class definition
content = content.replace(
"\n\nclass GetPropertyListResponse(",
"\n\n_list = list # alias to avoid shadowing by field name\n\n\nclass GetPropertyListResponse(",
)
# Replace bare list[] in annotations (but not the 'list' field itself)
# Only replace list[ when used as a type annotation, not as a field name
import re
# Replace list[identifier...] and dict[str, list[identifier...]] patterns
content = re.sub(
r"(?<![._a-zA-Z])list\[identifier\.",
"_list[identifier.",
content,
)
target.write_text(content)
print(" Fixed list field shadowing in get_property_list_response.py")
def fix_reuse_model_discriminator_bug():
"""Strip bogus ``<field>: Literal['reuse']`` subclasses.
datamodel-code-generator bug: when ``--reuse-model`` deduplicates inlined
copies of the same discriminated union, codegen emits subclasses like
``class SignalIdN(Parent): source: Literal['reuse']``. Two such subclasses
collide on the literal ``'reuse'`` and pydantic rejects the union with
``Value 'reuse' for discriminator mapped to multiple choices``.
Workaround: delete each bogus subclass and rewrite references to its
parent. Remove once koxudaxi/datamodel-code-generator#3092 is fixed.
"""
print("Fixing Literal['reuse'] discriminator bug from --reuse-model...")
pattern = re.compile(
r"\n\s*class (\w+)\((\w+)\):\n\s*\w+: Literal\['reuse'\](?: = 'reuse')?\n",
)