Repository navigation
Expand file tree
/
Copy pathgenerate_data_types.py
More file actions
83 lines (72 loc) · 3.06 KB
/
Copy pathgenerate_data_types.py
File metadata and controls
83 lines (72 loc) · 3.06 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
"""Generate the TypeScript declarations and the values of the Literal types of data_types.py
The values (data_types.json) are the enums the JSON schemas of the microservices use for these
types, see generate_schemas.js
"""
import ast
import json
from pathlib import Path
DATA_TYPES_FILE = (
Path(__file__).parent / "src" / "opengeodeweb_microservice" / "database" / "data_types.py"
)
OUTPUT_FILE = DATA_TYPES_FILE.with_suffix(".d.ts")
VALUES_FILE = DATA_TYPES_FILE.with_suffix(".json")
MAX_LINE_LENGTH = 100
def _to_typescript(node: ast.expr, aliases: set[str]) -> list[str] | None:
"""Members of the union a Literal type expression is made of, None if it is not one"""
if isinstance(node, ast.BinOp) and isinstance(node.op, ast.BitOr):
left = _to_typescript(node.left, aliases)
right = _to_typescript(node.right, aliases)
return None if left is None or right is None else left + right
if isinstance(node, ast.Name):
return [node.id] if node.id in aliases else None
if (
isinstance(node, ast.Subscript)
and isinstance(node.value, ast.Name)
and node.value.id == "Literal"
):
values = node.slice.elts if isinstance(node.slice, ast.Tuple) else [node.slice]
strings = [
value.value
for value in values
if isinstance(value, ast.Constant) and isinstance(value.value, str)
]
if len(strings) == len(values):
return [f'"{string}"' for string in strings]
return None
def _declaration(name: str, members: list[str]) -> str:
"""Formatted as oxfmt does: on one line when it fits"""
one_line = f"export type {name} = {' | '.join(members)};\n"
if len(one_line) <= MAX_LINE_LENGTH + 1:
return one_line
union = "\n".join(f" | {member}" for member in members)
return f"export type {name} =\n{union};\n"
def generate() -> tuple[str, dict[str, list[str]]]:
"""The TypeScript declarations, and the values of each type (its aliases expanded)"""
tree = ast.parse(DATA_TYPES_FILE.read_text())
aliases: set[str] = set()
declarations = []
values: dict[str, list[str]] = {}
for statement in tree.body:
if not (
isinstance(statement, ast.Assign)
and len(statement.targets) == 1
and isinstance(statement.targets[0], ast.Name)
):
continue
members = _to_typescript(statement.value, aliases)
if members is None:
continue
name = statement.targets[0].id
aliases.add(name)
declarations.append(_declaration(name, members))
values[name] = [
value
for member in members
for value in (values[member] if member in values else [json.loads(member)])
]
header = f"// Generated by {Path(__file__).name} from {DATA_TYPES_FILE.name}: do not edit\n\n"
return header + "\n".join(declarations), values
if __name__ == "__main__":
typescript, type_values = generate()
OUTPUT_FILE.write_text(typescript)
VALUES_FILE.write_text(json.dumps(type_values, indent=2) + "\n")