|
4 | 4 | - Discriminator field names: datamodel-codegen sometimes emits the JSON property name (camelCase) |
5 | 5 | instead of the Python field name (snake_case) in `Field(discriminator='...')` annotations, |
6 | 6 | particularly when the discriminator is on a schema referenced inside array items. |
| 7 | +- Duplicate ErrorType enum: ErrorResponse.yaml inlines the ErrorType enum (due to a Spectral |
| 8 | + nested-$ref limitation), causing datamodel-codegen to generate a duplicate `Type(StrEnum)` |
| 9 | + class alongside the canonical `ErrorType(StrEnum)`. This script removes the duplicate and |
| 10 | + rewires references to use `ErrorType`. |
7 | 11 | """ |
8 | 12 |
|
9 | 13 | from __future__ import annotations |
@@ -31,15 +35,32 @@ def fix_discriminators(content: str) -> str: |
31 | 35 | return content |
32 | 36 |
|
33 | 37 |
|
| 38 | +def deduplicate_error_type_enum(content: str) -> str: |
| 39 | + """Remove the duplicate `Type` enum and rewire references to `ErrorType`.""" |
| 40 | + # Remove the entire `class Type(StrEnum): ...` block up to the next class definition. |
| 41 | + content = re.sub( |
| 42 | + r'\nclass Type\(StrEnum\):.*?(?=\nclass )', |
| 43 | + '\n', |
| 44 | + content, |
| 45 | + flags=re.DOTALL, |
| 46 | + ) |
| 47 | + # Replace standalone `Type` references in type annotations with `ErrorType`. |
| 48 | + # Only target annotation contexts (`: Type`, `| Type`, `[Type`). |
| 49 | + content = re.sub(r'(?<=: )Type\b|(?<=\| )Type\b|(?<=\[)Type\b', 'ErrorType', content) |
| 50 | + # Collapse triple+ blank lines left by the removal. |
| 51 | + return re.sub(r'\n{3,}', '\n\n\n', content) |
| 52 | + |
| 53 | + |
34 | 54 | def main() -> None: |
35 | 55 | content = MODELS_PATH.read_text() |
36 | 56 | fixed = fix_discriminators(content) |
| 57 | + fixed = deduplicate_error_type_enum(fixed) |
37 | 58 |
|
38 | 59 | if fixed != content: |
39 | 60 | MODELS_PATH.write_text(fixed) |
40 | | - print(f'Fixed discriminator values in {MODELS_PATH}') |
| 61 | + print(f'Fixed generated models in {MODELS_PATH}') |
41 | 62 | else: |
42 | | - print('No discriminator fixes needed') |
| 63 | + print('No fixes needed') |
43 | 64 |
|
44 | 65 |
|
45 | 66 | if __name__ == '__main__': |
|
0 commit comments