-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy path_pydantic.py
More file actions
6130 lines (5464 loc) · 219 KB
/
Copy path_pydantic.py
File metadata and controls
6130 lines (5464 loc) · 219 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
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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SPDX-PackageName: gel-python
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright Gel Data Inc. and the contributors.
from __future__ import annotations
from typing import (
TYPE_CHECKING,
Any,
Literal,
NamedTuple,
Protocol,
TypedDict,
TypeVar,
cast,
)
from typing_extensions import TypeAliasType
import contextlib
import dataclasses
import enum
import functools
import hashlib
import itertools
import json
import graphlib
import logging
import operator
import os.path
import pathlib
import tempfile
import textwrap
import uuid
from collections import defaultdict
from collections.abc import (
Callable,
Mapping,
)
from contextlib import contextmanager
import gel
from gel import abstract
from gel._internal import _cache
from gel._internal import _dataclass_extras
from gel._internal import _dirsync
from gel._internal import _reflection as reflection
from gel._internal import _version as _ver_utils
from gel._internal._collections_extras import ImmutableChainMap
from gel._internal._namespace import ident, dunder
from gel._internal._qbmodel import _abstract as _qbmodel
from gel._internal._qbmodel._abstract import _syntax as _qbsyntax
from gel._internal._reflection._enums import SchemaPart, TypeModifier
from gel._internal._schemapath import SchemaPath
from gel._internal._polyfills import _strenum
from .._generator import C, AbstractCodeGenerator
from .._module import ImportTime, CodeSection, GeneratedModule
if TYPE_CHECKING:
import argparse
import io
from collections.abc import (
Collection,
Generator,
Iterable,
Iterator,
Sequence,
Set as AbstractSet,
)
from gel._internal._reflection._callables import CallableParamKey
from gel._internal._reflection._types import Indirection
COMMENT = """\
#
# Automatically generated from Gel schema.
#
# Do not edit directly as re-generating this file will overwrite any changes.
#
# fmt: off
# ruff: noqa
# flake8: noqa
# pylint: skip-file\
"""
def get_init_new_docstring(name: str) -> str:
return f"""\
\"\"\"Create a new {name} object from keyword arguments.
Call `db.save()` on the returned object to persist it in the database.
\"\"\"\
"""
def get_init_for_update_docsting(name: str) -> str:
return f"""\
\"\"\"Update an existing {name} object with the matching `id`.
All keyword arguments except `id` are optional. When provided, they
will update the corresponding fields of the existing object.
Call `db.save()` on the returned object to persist changes in the database.
\"\"\"\
"""
def get_single_link_for_proxy_docsting(
*,
source_type: str,
link_name: str,
target_type: str,
) -> str:
return f"""\
\"\"\"Wrap {target_type} to add link properties of {source_type}.{link_name}.
This is useful to add link properties when setting the link, e.g.:
obj = {source_type.replace("::", ".")}(...)
obj.{link_name} = {source_type.replace("::", ".")}.link(
{target_type.replace("::", ".")}(...),
link_prop=value,
...
)
\"\"\"\
"""
def get_multi_link_for_proxy_docsting(
*,
source_type: str,
link_name: str,
target_type: str,
) -> str:
return f"""\
\"\"\"Wrap {target_type} to add link properties of {source_type}.{link_name}.
This is useful to add link properties when setting the link, e.g.:
obj = {source_type.replace("::", ".")}(...)
obj.{link_name}.append(
{source_type.replace("::", ".")}.link(
{target_type.replace("::", ".")}(...),
link_prop=value,
...
)
)
\"\"\"\
"""
logger = logging.getLogger(__name__)
class IntrospectedModule(TypedDict):
object_types: dict[str, reflection.ObjectType]
scalar_types: dict[str, reflection.ScalarType]
functions: list[reflection.Function]
globals: list[reflection.Global]
@dataclasses.dataclass(kw_only=True, frozen=True)
class Schema:
types: Mapping[str, reflection.AnyType]
casts: reflection.CastMatrix
operators: reflection.OperatorMatrix
functions: list[reflection.Function]
globals: list[reflection.Global]
@dataclasses.dataclass(kw_only=True, frozen=True)
class GeneratedState:
db: reflection.BranchState
client_version: str
class StdSourceMethod(_strenum.StrEnum):
COPY = "copy"
REEXPORT = "reexport"
class PydanticModelsGenerator(AbstractCodeGenerator):
_output: pathlib.Path | None = None
_source_std_from: pathlib.Path | None
_source_std_method: StdSourceMethod | None
_std_only: bool
def _apply_cli_config(self, args: argparse.Namespace) -> None:
super()._apply_cli_config(args)
if args.output is not None:
self._output = pathlib.Path(args.output)
if std_from := getattr(args, "source_std_from", None):
self._source_std_from = pathlib.Path(std_from)
else:
self._source_std_from = None
if std_method := getattr(args, "source_std_method", None):
assert isinstance(std_method, str)
self._source_std_method = StdSourceMethod(std_method)
else:
self._source_std_method = None
self._std_only = bool(getattr(args, "std_only", False))
def _apply_env_output(self, value: Any) -> None:
if not isinstance(value, str):
raise ValueError('"output" must be a string')
self._output = self._project_dir / value
def run(self) -> None:
try:
self._client.ensure_connected()
except gel.EdgeDBError:
logger.exception("could not connect to Gel instance")
self.abort(61)
models_root = self._output
# First, detect FastAPI-style well-known project structure in cwd
if not models_root:
for subdir in map(pathlib.Path, ["app", "api"]):
if subdir.is_dir():
models_root = subdir / "models"
break
if not models_root:
for app_file in map(pathlib.Path, ["app.py", "api.py"]):
if app_file.is_file():
models_root = pathlib.Path("models")
break
# Or else, defaults to "models" directory in the project root
if not models_root:
models_root = self._project_dir / "models"
self._project_dir.mkdir(exist_ok=True)
tmp_models_root = tempfile.TemporaryDirectory(
prefix=".~tmp.models.",
dir=self._project_dir,
)
file_state = self._get_last_state(models_root)
with tmp_models_root, self._client:
db_state = reflection.fetch_branch_state(self._client)
this_client_ver = _ver_utils.get_project_version_key()
std_schema: Schema | None = None
std_manifest: set[pathlib.Path] | None = None
std_gen = SchemaGenerator(
self._client,
reflection.SchemaPart.STD,
)
outdir = pathlib.Path(tmp_models_root.name)
need_dirsync = False
sync_sources: list[pathlib.Path] = []
sync_method: Literal["copy", "move"] = "move"
if self._source_std_from is not None:
std_state = self._get_last_state(self._source_std_from)
if (
std_state is not None
and std_state.db.server_version == db_state.server_version
and std_state.client_version == this_client_ver
):
std_schema = self._load_std_schema_cache(
db_state.server_version,
)
std_manifest = std_gen.dry_run_manifest()
if std_schema is not None:
if self._source_std_method is StdSourceMethod.COPY:
sync_sources.append(self._source_std_from)
sync_method = "copy"
else:
std_gen.reexport(
self._source_std_from,
models_root,
outdir=outdir,
)
if std_manifest is None or std_schema is None:
if (
file_state is not None
and file_state.db.server_version == db_state.server_version
and file_state.client_version == this_client_ver
and not self._no_cache
):
std_schema = self._load_std_schema_cache(
db_state.server_version,
)
if std_schema is not None:
std_manifest = std_gen.dry_run_manifest()
else:
std_schema, std_manifest = std_gen.run(outdir)
self._save_std_schema_cache(
std_schema, db_state.server_version
)
need_dirsync = True
sync_sources.append(outdir)
if not self._std_only:
if (
file_state is None
or file_state.db.server_version != db_state.server_version
or file_state.db.top_migration != db_state.top_migration
or file_state.client_version != this_client_ver
or self._no_cache
):
usr_gen = SchemaGenerator(
self._client,
reflection.SchemaPart.USER,
std_schema=std_schema,
)
usr_gen.run(outdir)
need_dirsync = True
if outdir not in sync_sources:
sync_sources.append(outdir)
if need_dirsync:
for fn in list(std_manifest):
# Also keep the directories
std_manifest.update(fn.parents)
_dirsync.dirsync(
sync_sources,
models_root,
keep=std_manifest,
ignore={"_state.json"},
method=sync_method,
)
self._write_state(
GeneratedState(db=db_state, client_version=this_client_ver),
models_root,
)
if not self._quiet:
self.print_msg(
f"{C.GREEN}{C.BOLD}Done{C.ENDC}, generated models in:"
f" {C.CYAN}{pathlib.Path(models_root).absolute()}{C.ENDC}",
)
def _cache_key(self, suf: str, sv: reflection.ServerVersion) -> str:
ver_key = _ver_utils.get_project_version_key()
cache_key = f"gm-c-{ver_key}-s-{sv.major}.{sv.minor}"
return f"{cache_key}-{suf}"
def _save_std_schema_cache(
self, schema: Schema, sv: reflection.ServerVersion
) -> None:
_cache.save_json(
self._cache_key("std.json", sv),
dataclasses.asdict(schema),
cache_dir=self._cache_dir,
extra_key=self._extra_cache_key,
)
def _load_std_schema_cache(
self, sv: reflection.ServerVersion
) -> Schema | None:
schema_data = _cache.load_json(
self._cache_key("std.json", sv),
cache_dir=self._cache_dir,
extra_key=self._extra_cache_key,
)
if schema_data is None:
return None
if not isinstance(schema_data, dict):
return None
try:
return _dataclass_extras.coerce_to_dataclass(Schema, schema_data)
except Exception:
return None
def _get_last_state(
self, models_root: str | pathlib.Path
) -> GeneratedState | None:
state_json = pathlib.Path(models_root) / "_state.json"
try:
with open(state_json, encoding="utf8") as f:
state_data = json.load(f)
except (OSError, ValueError, TypeError):
return None
try:
server_version = state_data["db"]["server_version"]
top_migration = state_data["db"]["top_migration"]
client_version = state_data["client_version"]
except KeyError:
return None
if (
not isinstance(server_version, list)
or len(server_version) != 2
or not all(isinstance(part, int) for part in server_version)
):
return None
if not isinstance(client_version, str) or not client_version:
return None
if top_migration is not None and not isinstance(top_migration, str):
return None
return GeneratedState(
db=reflection.BranchState(
server_version=reflection.ServerVersion(*server_version),
top_migration=top_migration,
),
client_version=client_version,
)
def _write_state(
self,
state: GeneratedState,
outdir: pathlib.Path,
) -> None:
state_json = outdir / "_state.json"
try:
with open(state_json, mode="w", encoding="utf8") as f:
json.dump(dataclasses.asdict(state), f)
except (OSError, ValueError, TypeError):
return None
class ModuleAspect(enum.Enum):
MAIN = enum.auto()
SHAPES = enum.auto()
LATE = enum.auto()
class SchemaGenerator:
def __init__(
self,
client: abstract.ReadOnlyExecutor,
schema_part: reflection.SchemaPart,
*,
source_from: str | None = None,
std_schema: Schema | None = None,
) -> None:
self._client = client
self._schema_part = schema_part
self._basemodule = "models"
self._modules: dict[SchemaPath, IntrospectedModule] = {}
self._std_modules: list[SchemaPath] = []
self._types: Mapping[str, reflection.Type] = {}
self._casts: reflection.CastMatrix
self._operators: reflection.OperatorMatrix
self._functions: list[reflection.Function]
self._globals: list[reflection.Global]
self._named_tuples: dict[str, reflection.NamedTupleType] = {}
self._wrapped_types: set[str] = set()
self._std_schema = std_schema
self._source_from = source_from
if schema_part is not SchemaPart.STD and std_schema is None:
raise ValueError(
"must pass std_schema when reflecting user schemas"
)
def iter_modpaths(
self,
*,
aspects: Iterable[ModuleAspect] = ModuleAspect,
) -> Iterator[tuple[SchemaPath, ModuleAspect, bool]]:
part = self._schema_part
modules: dict[SchemaPath, bool] = dict.fromkeys(
(
SchemaPath(mod)
for mod in reflection.fetch_modules(self._client, part)
),
False,
)
for mod in [*modules]:
if mod.parent:
modules[mod.parent] = True
for mod, has_submodules in modules.items():
modpath = get_modpath(mod, ModuleAspect.MAIN)
as_pkg = mod_is_package(modpath, part) or has_submodules
if not aspects:
yield modpath, ModuleAspect.MAIN, as_pkg
else:
for aspect in aspects:
modpath = get_modpath(mod, aspect)
yield modpath, aspect, as_pkg
common_modpath = get_common_types_modpath(self._schema_part)
as_pkg = mod_is_package(common_modpath, part)
yield common_modpath, ModuleAspect.MAIN, as_pkg
def dry_run_manifest(self) -> set[pathlib.Path]:
return {
mod_filename(modpath, as_pkg=is_pkg)
for modpath, _, is_pkg in self.iter_modpaths()
}
def reexport(
self,
srcdir: pathlib.Path,
dstdir: pathlib.Path,
outdir: pathlib.Path,
) -> None:
common = pathlib.Path(os.path.commonpath((srcdir, dstdir)))
srcpath = SchemaPath.from_segments(*srcdir.relative_to(common).parts)
dstpath = SchemaPath.from_segments(*dstdir.relative_to(common).parts)
for modpath, _, is_pkg in self.iter_modpaths(
aspects=(ModuleAspect.MAIN,)
):
for aspect in ModuleAspect:
aspect_mod = get_modpath(modpath, aspect)
fname = mod_filename(aspect_mod, as_pkg=is_pkg)
if not (srcdir / fname).exists():
continue
genmod = GeneratedModule(COMMENT, BASE_IMPL)
rel_imp = _resolve_rel_import(
src_mod=dstpath / modpath,
src_aspect_mod=dstpath / aspect_mod,
src_is_pkg=is_pkg,
src_aspect=aspect,
dst_mod=srcpath / modpath,
dst_aspect_mod=srcpath / aspect_mod,
dst_aspect=aspect,
)
assert rel_imp is not None
genmod.import_star(rel_imp.module)
srcmod_all = genmod.import_qual_name(
rel_imp.module,
"__all__",
suggested_module_alias=rel_imp.module_alias,
)
list_ = genmod.import_name(
"builtins", "list", import_time=ImportTime.typecheck
)
str_ = genmod.import_name(
"builtins", "str", import_time=ImportTime.typecheck
)
genmod.write(f"__all__: {list_}[{str_}] = []")
genmod.write(f"__all__.extend({srcmod_all})")
tgt_file = outdir / fname
tgt_file.parent.mkdir(parents=True, exist_ok=True)
with open(tgt_file, "w", encoding="utf8") as f:
genmod.output(f)
def run(self, outdir: pathlib.Path) -> tuple[Schema, set[pathlib.Path]]:
schema = self.introspect_schema()
written: set[pathlib.Path] = set()
written.update(self._generate_common_types(outdir))
modules: dict[SchemaPath, GeneratedSchemaModule] = {}
order = sorted(
self._modules.items(),
key=operator.itemgetter(0),
reverse=True,
)
for modname, content in order:
if not content:
# skip apparently empty modules
continue
module = GeneratedSchemaModule(
modname,
all_types=self._types,
all_casts=self._casts,
all_operators=self._operators,
all_globals=self._globals,
modules=self._modules,
schema_part=self._schema_part,
)
module.process(content)
module.write_submodules(
[
k
for k, v in modules.items()
if k.is_relative_to(modname)
and len(k.parts) == len(modname.parts) + 1
and v.has_content()
]
)
written.update(module.write_files(outdir))
modules[modname] = module
if self._schema_part is not reflection.SchemaPart.STD:
all_modules = list(self._modules)
all_modules += [m for m in self._std_modules if len(m.parts) == 1]
module = GeneratedSchemaModule(
SchemaPath(),
all_types=self._types,
all_casts=self._casts,
all_operators=self._operators,
all_globals=self._globals,
modules=all_modules,
schema_part=self._schema_part,
)
module.write_submodules(
[m for m in all_modules if len(m.parts) == 1]
)
default_module = modules.get(SchemaPath("default"))
if default_module is not None:
module.reexport_module(default_module)
written.update(module.write_files(outdir))
return schema, written
def introspect_schema(self) -> Schema:
for mod in reflection.fetch_modules(self._client, self._schema_part):
self._modules[SchemaPath(mod)] = {
"scalar_types": {},
"object_types": {},
"functions": [],
"globals": [],
}
this_part = self._schema_part
std_part = reflection.SchemaPart.STD
self._types = reflection.fetch_types(self._client, this_part)
these_types = self._types
self._casts = reflection.fetch_casts(self._client, this_part)
self._operators = reflection.fetch_operators(self._client, this_part)
these_funcs = reflection.fetch_functions(self._client, this_part)
self._functions = these_funcs
these_globals = reflection.fetch_globals(self._client, this_part)
self._globals = these_globals
if self._schema_part is not std_part:
assert self._std_schema is not None
std_types = self._std_schema.types
self._types = ImmutableChainMap(std_types, these_types)
std_casts = self._std_schema.casts
self._casts = self._casts.chain(std_casts)
std_operators = self._std_schema.operators
self._operators = self._operators.chain(std_operators)
self._functions = these_funcs + self._std_schema.functions
self._globals = these_globals + self._std_schema.globals
self._std_modules = [
SchemaPath(mod)
for mod in reflection.fetch_modules(self._client, std_part)
]
else:
self._std_modules = list(self._modules)
for t in these_types.values():
if reflection.is_object_type(t):
name = t.schemapath
self._modules[name.parent]["object_types"][name.name] = t
elif reflection.is_scalar_type(t):
name = t.schemapath
self._modules[name.parent]["scalar_types"][name.name] = t
elif reflection.is_named_tuple_type(t):
self._named_tuples[t.id] = t
for f in these_funcs:
name = f.schemapath
self._modules[name.parent]["functions"].append(f)
for g in these_globals:
name = g.schemapath
self._modules[name.parent]["globals"].append(g)
return Schema(
types=cast("Mapping[str, reflection.AnyType]", self._types),
casts=self._casts,
operators=self._operators,
functions=self._functions,
globals=self._globals,
)
def get_comment_preamble(self) -> str:
return COMMENT
def _generate_common_types(
self, outdir: pathlib.Path
) -> set[pathlib.Path]:
mod = get_common_types_modpath(self._schema_part)
module = GeneratedGlobalModule(
mod,
all_types=self._types,
all_casts=self._casts,
all_operators=self._operators,
all_globals=self._globals,
modules=self._modules,
schema_part=self._schema_part,
)
module.process(self._named_tuples)
return module.write_files(outdir)
class Import(NamedTuple):
module: str
module_alias: str | None
@functools.cache
def get_modpath(
modpath: SchemaPath,
aspect: ModuleAspect,
) -> SchemaPath:
if aspect is ModuleAspect.MAIN:
pass
elif aspect is ModuleAspect.SHAPES:
modpath = SchemaPath("__shapes__") / modpath
elif aspect is ModuleAspect.LATE:
modpath = SchemaPath("__shapes__") / "__late__" / modpath
return modpath
def get_common_types_modpath(
schema_part: reflection.SchemaPart,
) -> SchemaPath:
mod = SchemaPath("__types__")
if schema_part is reflection.SchemaPart.STD:
mod = SchemaPath("std") / mod
return mod
def mod_is_package(
mod: SchemaPath,
schema_part: reflection.SchemaPart,
) -> bool:
return not mod.parts or (
schema_part is reflection.SchemaPart.STD and len(mod.parts) == 1
)
def mod_filename(
modpath: SchemaPath,
*,
as_pkg: bool,
) -> pathlib.Path:
if as_pkg:
# This is a prefix in another module, thus it is part of a nested
# module structure.
dirpath = modpath
filename = "__init__.py"
else:
# This is a leaf module, so we just need to create a corresponding
# <mod>.py file.
dirpath = modpath.parent
filename = f"{modpath.name}.py"
return dirpath.as_pathlib_path() / filename
def _resolve_rel_import(
*,
src_mod: SchemaPath,
src_aspect_mod: SchemaPath,
src_aspect: ModuleAspect,
src_is_pkg: bool,
dst_mod: SchemaPath,
dst_aspect_mod: SchemaPath,
dst_aspect: ModuleAspect,
) -> Import | None:
if dst_aspect_mod == src_aspect_mod and dst_aspect is src_aspect:
# It's this module, no need to import
return None
else:
if dst_mod == src_mod and src_aspect is ModuleAspect.MAIN:
module_alias = "base"
else:
module_alias = "_".join(dst_mod.parts)
if dst_aspect is ModuleAspect.SHAPES:
module_alias += "_shapes"
elif dst_aspect is ModuleAspect.LATE:
module_alias += "_late"
src_pkg = src_aspect_mod if src_is_pkg else src_aspect_mod.parent
common_parts = dst_aspect_mod.common_parts(src_pkg)
import_tail = dst_aspect_mod.parts[len(common_parts) :]
relative_depth = len(src_pkg.parts) - len(common_parts) + 1
if not import_tail:
relative_depth += 1
dots = "." * relative_depth
if not import_tail:
# Pure ancestor import
py_mod = f"{dots}{dst_mod.name}"
else:
py_mod = dots + ".".join(import_tail)
return Import(
module=py_mod,
module_alias=module_alias,
)
def _map_name(
transform: Callable[[str], str],
classnames: Iterable[str],
) -> list[str]:
result = []
for classname in classnames:
mod, _, name = classname.rpartition(".")
name = transform(name)
result.append(f"{mod}.{name}" if mod else name)
return result
def _indirection_key(path: Indirection) -> tuple[str, ...]:
return tuple(s if isinstance(s, str) else f"{s[0]}[{s[1]}]" for s in path)
BASE_IMPL = "gel.models.pydantic"
CORE_OBJECTS = frozenset(
{
"std::BaseObject",
"std::Object",
"std::FreeObject",
}
)
GENERIC_TYPES = frozenset(
{
SchemaPath("std", "anytype"),
SchemaPath("std", "anyobject"),
SchemaPath("std", "anytuple"),
SchemaPath("std", "anynamedtuple"),
SchemaPath("std", "array"),
SchemaPath("std", "tuple"),
SchemaPath("std", "range"),
SchemaPath("std", "multirange"),
}
)
PSEUDO_TYPES = frozenset(("anytuple", "anyobject", "anytype"))
# Deprecated Pydantic attributes, allow shadowing
SHADOWED_PYDANTIC_ATTRIBUTES = frozenset(
{
"dict",
"json",
"parse_obj",
"parse_row",
"parse_file",
"from_orm",
"construct",
"copy",
"schema",
"schema_json",
"validate",
"update_forward_refs",
"_iter",
"_copy_and_set_values",
"_get_value",
"_calculate_keys",
}
)
def _filter_pointers(
pointers: Iterable[tuple[reflection.Pointer, reflection.ObjectType]],
filters: Iterable[
Callable[[reflection.Pointer, reflection.ObjectType], bool]
] = (),
*,
exclude_id: bool = True,
exclude_type: bool = True,
) -> list[tuple[reflection.Pointer, reflection.ObjectType]]:
excluded = set()
if exclude_id:
excluded.add("id")
if exclude_type:
excluded.add("__type__")
if excluded:
filters = [lambda ptr, obj: ptr.name not in excluded, *filters]
else:
filters = list(filters)
filters.append(
lambda ptr, obj: (
obj.schemapath.parts[0] != "schema"
or not ptr.name.startswith("is_")
or not ptr.is_computed
)
)
return [
(ptr, objtype)
for ptr, objtype in pointers
if all(f(ptr, objtype) for f in filters)
]
PointerFilter = TypeAliasType(
"PointerFilter",
Callable[[reflection.Pointer, reflection.ObjectType], bool],
)
PointerCardinalityCallback = TypeAliasType(
"PointerCardinalityCallback",
Callable[
[reflection.Pointer, reflection.ObjectType],
reflection.Cardinality,
],
)
def _get_object_type_body(
objtype: reflection.ObjectType,
filters: Iterable[PointerFilter] = (),
) -> list[reflection.Pointer]:
return [
p
for p, _ in _filter_pointers(
((ptr, objtype) for ptr in objtype.pointers),
filters,
)
]
class BaseGeneratedModule:
def __init__(
self,
modname: SchemaPath,
*,
all_types: Mapping[str, reflection.Type],
all_casts: reflection.CastMatrix,
all_operators: reflection.OperatorMatrix,
all_globals: list[reflection.Global],
modules: Collection[SchemaPath],
schema_part: reflection.SchemaPart,
) -> None:
super().__init__()
self._modpath = modname
self._types = all_types
self._types_by_name: dict[str, reflection.Type] = {}
self._casts = all_casts
self._operators = all_operators
self._globals = all_globals
schema_obj_type = None
for t in all_types.values():
self._types_by_name[t.name] = t
if t.name == "schema::ObjectType":
assert reflection.is_object_type(t)
schema_obj_type = t
if schema_obj_type is None:
raise RuntimeError(
"schema::ObjectType type not found in schema reflection"
)
self._schema_object_type = schema_obj_type
self._modules = frozenset(modules)
self._submodules = sorted(
m
for m in self._modules
if m.is_relative_to(modname)
and len(m.parts) == len(modname.parts) + 1
)
self._schema_part = schema_part
self._is_package = self.mod_is_package(modname, schema_part)
self._py_files = {
ModuleAspect.MAIN: GeneratedModule(
COMMENT,
BASE_IMPL,
code_preamble=(
'__gel_default_shape__ = "Default"'
if self._schema_part is reflection.SchemaPart.USER
else None
),
),
ModuleAspect.SHAPES: GeneratedModule(COMMENT, BASE_IMPL),
ModuleAspect.LATE: GeneratedModule(COMMENT, BASE_IMPL),
}
self._current_py_file = self._py_files[ModuleAspect.MAIN]
self._current_aspect = ModuleAspect.MAIN
self._type_import_cache: dict[
tuple[str, ModuleAspect, ModuleAspect, bool, ImportTime],
str,
] = {}
self.__post_init__()
def __post_init__(self) -> None:
pass
def get_mod_schema_part(
self,
mod: SchemaPath,
) -> reflection.SchemaPart:
if (
self._schema_part is reflection.SchemaPart.STD
or mod not in self._modules