-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcli.py
79 lines (64 loc) · 2.43 KB
/
cli.py
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
"""CLI to convert pydantic class to AWS Glue schema."""
import json
import logging
import sys
from argparse import ArgumentParser
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
from pydantic_glue import convert
logging.basicConfig(format="{asctime} - {levelname} - {message}", level=logging.INFO, style="{", stream=sys.stdout)
log = logging.getLogger(__name__)
@dataclass
class Arguments:
"""CLI Arguments."""
module_file: str
class_name: str
output_file: str
log_result: bool
json_schema_by_alias: bool
def parse_args(argv: list[str]) -> Arguments:
"""Parse CLI arguments."""
parser = ArgumentParser()
parser.add_argument("-f", dest="source_file", required=True, type=str, help="Path to the python file")
parser.add_argument("-c", dest="class_name", required=True, type=str, help="Python class name")
parser.add_argument("-o", dest="output_file", required=False, type=str, help="Path to the output file")
parser.add_argument(
"-l", dest="log_result", action="store_true", default=False, help="Flag if need to print result in log"
)
parser.add_argument(
"--schema-by-name",
dest="json_schema_by_alias",
action="store_false",
default=True,
help="Flag to not use name for json schema generation",
)
args = parser.parse_args(argv)
return Arguments(
module_file=args.source_file.removesuffix(".py"),
class_name=args.class_name,
output_file=args.output_file,
log_result=args.log_result,
json_schema_by_alias=args.json_schema_by_alias,
)
def cli() -> None:
"""CLI entry point."""
args = parse_args(sys.argv[1:])
sys.path.append(Path(args.module_file).parent.as_posix())
imported = __import__(Path(args.module_file).name)
model = getattr(imported, args.class_name)
input_schema = json.dumps(model.model_json_schema(by_alias=args.json_schema_by_alias))
converted = convert(input_schema)
output = json.dumps(
{
"//": f"Generated by pydantic-glue at {datetime.now(tz=timezone.utc)}. DO NOT EDIT",
"columns": dict(converted),
},
indent=2,
)
if args.log_result or not args.output_file:
log.info(f"Generated file content:\n{output}")
if args.output_file:
ouf = Path(args.output_file)
ouf.parent.mkdir(parents=True, exist_ok=True)
ouf.write_text(output)