forked from sauldom102/gql_schema_codegen
-
Notifications
You must be signed in to change notification settings - Fork 1
/
schema.py
356 lines (287 loc) · 11.8 KB
/
schema.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
import json
import os
import re
import subprocess
from typing import Dict, List, Optional, Set
import yaml
from graphql import (build_client_schema, build_schema,
get_introspection_query, print_schema)
from graphqlclient import GraphQLClient
from ..block import (Block, BlockField, BlockFieldInfo, BlockInfo,
get_inheritance_tree)
from ..constants import (BLOCK_PATTERN, DIRECTIVE_PATTERN,
DIRECTIVE_USAGE_PATTERN, FIELD_PATTERN,
RESOLVER_TYPES, SCALAR_PATTERN, UNION_PATTERN)
from ..constants.block_fields import all_block_fields
from ..dependency import (Dependency, DependencyGroup,
update_interface_dependencies)
from ..scalar import ScalarInfo, ScalarType
from ..union import UnionInfo, UnionType
class Schema:
_string: Optional[str] = None
_blocks: List[Block] = []
_cleaned_string: Optional[str] = None
_unions: List[UnionType] = []
_scalars: List[ScalarType] = []
ignore_types: List[str] = []
generate_empty_params_types = False
path: Optional[str] = None
url: Optional[str] = None
_config_file_content = None
config_file: Optional[str] = None
_special_blocks: Set[str] = set()
_import_blocks: Optional[str] = None
_only_blocks: bool = False
def __init__(self, **kwargs) -> None:
if "path" in kwargs and type(kwargs["path"]) is str:
self.path = kwargs["path"]
if "url" in kwargs and type(kwargs["url"]) is str:
self.url = kwargs["url"]
if "config_file" in kwargs and type(kwargs["config_file"]) is str:
self.config_file = kwargs["config_file"]
self._special_blocks = kwargs.get("blocks", self._special_blocks)
self._import_blocks = kwargs.get("import_blocks", self._import_blocks)
self._only_blocks = kwargs.get("only_blocks", self._only_blocks)
update_interface_dependencies(self.config_file_content)
self.dependency_group = DependencyGroup()
@property
def config_file_content(self) -> Optional[dict[str, str]]:
if (
self._config_file_content is None
and self.config_file
and os.path.exists(self.config_file)
):
with open(self.config_file, "r") as f:
return yaml.safe_load(f)
return self._config_file_content
@property
def custom_scalars(self) -> dict[str, str]:
if type(self.config_file_content) is dict:
data = self.config_file_content.get("scalars")
if type(data) is dict:
return data
return {}
def generate_type_file(self, to_path: str):
with open(f"{to_path}", "w") as f:
f.write(self.file_representation)
return self.file_representation
def get_sdl(self):
if self.url:
client = GraphQLClient(self.url)
query_intros = get_introspection_query(descriptions=False)
intros_result = client.execute(query_intros, variables=None)
intros = json.loads(intros_result)
client_schema = build_client_schema(intros.get("data", None))
sdl = print_schema(client_schema)
return sdl
return None
@property
def is_schema_path(self):
return bool(self.path and os.path.isdir(self.path))
@property
def marged_schema_from_dir(self):
INSTALLATION_COMMAND = "npm list -g graphql-schema-utilities ||npm i --global graphql-schema-utilities"
if self.is_schema_path and self.path:
try:
subprocess.call(
INSTALLATION_COMMAND, shell=True, stdout=subprocess.DEVNULL
)
except:
pass
glob_paths = [
os.path.join(self.path, "**/*.gql"),
os.path.join(self.path, "**/*.graphql"),
]
joined_glob_paths = ",".join(glob_paths)
MERGE_COMMAND = f'graphql-schema-utilities -s "{{{joined_glob_paths}}}"'
output = subprocess.run(
MERGE_COMMAND, shell=True, text=True, capture_output=True
)
return output.stdout
def read_schema(self):
if self.is_schema_path:
return self.marged_schema_from_dir
if self.path:
with open(self.path, "r") as f:
return f.read()
if self.url:
return self.get_sdl()
return None
@property
def string(self):
if not self._string:
self._string = self.read_schema()
return self._string
@staticmethod
def clean_string(string: str):
cleaned = re.sub(r"\s+#.+\n", "\n", string)
cleaned = re.sub(r'\n?"{3}[^"]+"{3}\n?', "", cleaned)
# remove empty lines
cleaned = re.sub(r"[\s\t]+\n", "\n", cleaned, flags=re.MULTILINE)
# remove lines with directives
cleaned = re.sub(DIRECTIVE_PATTERN, "", cleaned)
cleaned = re.sub(DIRECTIVE_USAGE_PATTERN, "", cleaned)
cleaned = re.sub(r"\s=\s\{\}", "", cleaned)
return cleaned
@property
def cleaned_string(self):
if not self._cleaned_string:
if self.string:
self._cleaned_string = Schema.clean_string(self.string)
else:
self._cleaned_string = ""
return self._cleaned_string
@staticmethod
def get_fields_from_block(fields: str):
return map(
lambda it: it.groupdict(),
re.finditer(FIELD_PATTERN, Schema.clean_string(fields)),
)
def get_blocks(self):
return map(
lambda it: it.groupdict(),
re.finditer(BLOCK_PATTERN, self.cleaned_string, re.MULTILINE),
)
def get_unions(self):
return map(
lambda it: it.groupdict(),
re.finditer(UNION_PATTERN, self.cleaned_string, re.MULTILINE),
)
def get_scalars(self):
return map(
lambda it: it.groupdict(),
re.finditer(SCALAR_PATTERN, self.cleaned_string, re.MULTILINE),
)
@property
def blocks(self):
if not self._blocks:
blocks: List[Block] = []
_blocks = list(self.get_blocks())
for block in _blocks:
block_fields: List[BlockField] = []
block_type = block["type"]
block_name = block["name"]
all_block_fields[block_name] = set()
for field in self.get_fields_from_block(block["fields"]):
all_block_fields[block_name].add(field["name"])
info = BlockFieldInfo(
name=field["name"],
parent_type=block_type,
parent_name=block_name,
params=field["params"],
is_field_from_params=False,
value_type=field["value_type"],
)
f = BlockField(info, dependency_group=self.dependency_group)
block_fields.append(f)
block_info = BlockInfo(
type=block_type,
name=block["name"],
fields=block_fields,
implements=block["implements"],
)
b = Block(block_info, dependency_group=self.dependency_group)
if self._import_blocks and block_type in self._special_blocks:
self.dependency_group.add_dependency(
Dependency(self._import_blocks, b.display_name)
)
elif self._only_blocks and block_type not in self._special_blocks:
continue
else:
blocks.append(b)
self._blocks = list(
filter(lambda b: b.name not in self.ignore_types, blocks)
)
return self._blocks
@property
def sorted_blocks(self):
# first populate inheritance tree. this is VERY dirty for now but we
# should refactor this soon. We are calling b.heading_file_line for all
# blocks here as this is what populates the tree, and we only do this
# once
all_blocks: Dict[str, Block] = {}
for b in self.blocks:
all_blocks[b.name] = b
_ = b.heading_file_line
inheritanceTree = get_inheritance_tree()
sorted_bl: List[Block] = []
# first add enums - these have no dependencies
sorted_bl.extend(list(filter(lambda x: x.type == "enum", self.blocks)))
types_order = ["interface", "type", "param_type", "input"]
for t in types_order:
interfaces = list(filter(lambda x: x.type == t, self.blocks))
to_add = {b.name for b in interfaces}
blocks: List[Block] = []
# add nodes in a BFS manner to ensure we don't break dependencies
queue: List[str] = ["root"]
visited: Set[str] = set(["root"])
while queue:
node = queue.pop(0)
if node in to_add:
blocks.append(all_blocks[node])
for child_node in inheritanceTree.get(node, []):
if child_node not in visited:
visited.add(child_node)
queue.append(child_node)
sorted_bl.extend(blocks)
return sorted_bl
@property
def unions(self):
if not self._unions:
self._unions = []
for u in self.get_unions():
union_info = UnionInfo(name=u["name"], types=u["types"])
self._unions.append(
UnionType(union_info, dependency_group=self.dependency_group)
)
return self._unions
@property
def scalars(self):
if not self._scalars:
self._scalars = []
for u in self.get_scalars():
scalar_info = ScalarInfo(
name=u["name"], value=self.custom_scalars.get(u["name"])
)
scalar = ScalarType(scalar_info, dependency_group=self.dependency_group)
if self._import_blocks and "scalar" in self._special_blocks:
# hack to adjust dependency group
scalar.file_representation
self.dependency_group.add_dependency(
Dependency(self._import_blocks, scalar_info.name)
)
else:
self._scalars.append(scalar)
if self._only_blocks and "scalar" not in self._special_blocks:
return []
return self._scalars
@property
def import_lines(self):
return self.dependency_group.import_lines
@property
def file_representation(self):
lines: List[str] = ["\n" * 2]
if len(self.scalars) > 0:
for s in self.scalars:
lines.extend([s.file_representation] + ["\n"])
lines.append("\n" * 2)
if len(self.unions) > 0:
self.dependency_group.add_dependency(
Dependency(imported_from="typing", dependency="Union")
)
for u in self.unions:
lines.extend([u.file_representation] + ["\n" * 2])
for b in self.sorted_blocks:
lines.extend([b.file_representation] + ["\n" * 3])
if b.name in RESOLVER_TYPES:
for f in b.fields:
field: BlockField = f
if field.param_block and (
len(field.param_block.fields) > 0
or self.generate_empty_params_types
):
lines.extend([field.param_block.file_representation, "\n" * 3])
if field.result_definition:
lines.extend([field.result_definition, "\n" * 3])
lines.insert(0, self.import_lines)
return "".join(lines)