|
1 | 1 | import json
|
| 2 | +import logging |
2 | 3 | import os
|
3 | 4 | import sys
|
4 |
| -from datetime import datetime |
| 5 | +from argparse import ArgumentParser |
| 6 | +from datetime import datetime, timezone |
| 7 | +from pathlib import Path |
5 | 8 |
|
6 | 9 | from pydantic_glue import convert
|
7 | 10 |
|
| 11 | +logging.basicConfig(format="{asctime} - {levelname} - {message}", level=logging.INFO, style="{", stream=sys.stdout) |
| 12 | +log = logging.getLogger(__name__) |
| 13 | + |
8 | 14 |
|
9 | 15 | def cli() -> None:
|
10 |
| - if len(sys.argv) != 3: |
11 |
| - print(f"Usage: {sys.argv[0]} <module file> <class name>", file=sys.stderr) |
12 |
| - sys.exit(1) |
| 16 | + parser = ArgumentParser() |
| 17 | + parser.add_argument("-f", dest="source_file", required=True, type=str, help="Path to the python file") |
| 18 | + parser.add_argument("-c", dest="class_name", required=True, type=str, help="Python class name") |
| 19 | + parser.add_argument("-o", dest="output_file", required=False, type=str, help="Path to the output file") |
| 20 | + parser.add_argument( |
| 21 | + "-l", dest="log_result", action="store_true", default=False, help="Flag if need to print result in log" |
| 22 | + ) |
| 23 | + args = parser.parse_args(sys.argv[1:]) |
13 | 24 |
|
14 |
| - module_file = sys.argv[1].replace(".py", "") |
15 |
| - class_name = sys.argv[2] |
| 25 | + module_file = args.source_file.removesuffix(".py") |
16 | 26 |
|
17 | 27 | sys.path.append(os.path.dirname(module_file))
|
18 | 28 |
|
19 | 29 | imported = __import__(os.path.basename(module_file))
|
20 |
| - imported = getattr(imported, class_name) |
| 30 | + imported = getattr(imported, args.class_name) |
21 | 31 | input_schema = json.dumps(imported.model_json_schema())
|
22 | 32 | converted = convert(input_schema)
|
23 |
| - output = { |
24 |
| - "//": f"Generated by pydantic-glue at {datetime.now()}. DO NOT EDIT", |
25 |
| - "columns": {k: v for (k, v) in converted}, |
26 |
| - } |
| 33 | + output = json.dumps( |
| 34 | + { |
| 35 | + "//": f"Generated by pydantic-glue at {datetime.now(tz=timezone.utc)}. DO NOT EDIT", |
| 36 | + "columns": {k: v for (k, v) in converted}, |
| 37 | + }, |
| 38 | + indent=2, |
| 39 | + ) |
| 40 | + |
| 41 | + if args.log_result or not args.output_file: |
| 42 | + log.info(f"Generated file content:\n{output}") |
27 | 43 |
|
28 |
| - print(json.dumps(output, indent=2)) |
| 44 | + if args.output_file: |
| 45 | + ouf = Path(args.output_file) |
| 46 | + ouf.parent.mkdir(parents=True, exist_ok=True) |
| 47 | + ouf.write_text(output) |
0 commit comments