|
3 | 3 | import os
|
4 | 4 | import sys
|
5 | 5 | from argparse import ArgumentParser
|
| 6 | +from dataclasses import dataclass |
6 | 7 | from datetime import datetime, timezone
|
7 | 8 | from pathlib import Path
|
8 | 9 |
|
|
12 | 13 | log = logging.getLogger(__name__)
|
13 | 14 |
|
14 | 15 |
|
15 |
| -def cli() -> None: |
| 16 | +@dataclass |
| 17 | +class Arguments: |
| 18 | + module_file: str |
| 19 | + class_name: str |
| 20 | + output_file: str |
| 21 | + log_result: bool |
| 22 | + json_schema_by_alias: bool |
| 23 | + |
| 24 | + |
| 25 | +def parse_args(argv: list[str]) -> Arguments: |
16 | 26 | parser = ArgumentParser()
|
17 | 27 | parser.add_argument("-f", dest="source_file", required=True, type=str, help="Path to the python file")
|
18 | 28 | parser.add_argument("-c", dest="class_name", required=True, type=str, help="Python class name")
|
19 | 29 | parser.add_argument("-o", dest="output_file", required=False, type=str, help="Path to the output file")
|
20 | 30 | parser.add_argument(
|
21 | 31 | "-l", dest="log_result", action="store_true", default=False, help="Flag if need to print result in log"
|
22 | 32 | )
|
23 |
| - args = parser.parse_args(sys.argv[1:]) |
| 33 | + parser.add_argument( |
| 34 | + "--schema-by-name", |
| 35 | + dest="json_schema_by_alias", |
| 36 | + action="store_false", |
| 37 | + default=True, |
| 38 | + help="Flag to not use name for json schema generation", |
| 39 | + ) |
| 40 | + args = parser.parse_args(argv) |
| 41 | + |
| 42 | + return Arguments( |
| 43 | + module_file=args.source_file.removesuffix(".py"), |
| 44 | + class_name=args.class_name, |
| 45 | + output_file=args.output_file, |
| 46 | + log_result=args.log_result, |
| 47 | + json_schema_by_alias=args.json_schema_by_alias, |
| 48 | + ) |
24 | 49 |
|
25 |
| - module_file = args.source_file.removesuffix(".py") |
26 | 50 |
|
27 |
| - sys.path.append(os.path.dirname(module_file)) |
| 51 | +def cli() -> None: |
| 52 | + args = parse_args(sys.argv[1:]) |
| 53 | + sys.path.append(os.path.dirname(args.module_file)) |
| 54 | + imported = __import__(os.path.basename(args.module_file)) |
28 | 55 |
|
29 |
| - imported = __import__(os.path.basename(module_file)) |
30 |
| - imported = getattr(imported, args.class_name) |
31 |
| - input_schema = json.dumps(imported.model_json_schema()) |
| 56 | + model = getattr(imported, args.class_name) |
| 57 | + input_schema = json.dumps(model.model_json_schema(by_alias=args.json_schema_by_alias)) |
32 | 58 | converted = convert(input_schema)
|
| 59 | + |
33 | 60 | output = json.dumps(
|
34 | 61 | {
|
35 | 62 | "//": f"Generated by pydantic-glue at {datetime.now(tz=timezone.utc)}. DO NOT EDIT",
|
|
0 commit comments