forked from edgedb/edgedb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
setup.py
1003 lines (829 loc) · 30.8 KB
/
setup.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
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
#
# This source file is part of the EdgeDB open source project.
#
# Copyright 2008-present MagicStack Inc. and the EdgeDB authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import binascii
import importlib
import os
import os.path
import pathlib
import platform
import shutil
import subprocess
import textwrap
import setuptools
from setuptools import extension as setuptools_extension
from setuptools.command import build as setuptools_build
from setuptools.command import build_ext as setuptools_build_ext
import distutils
import Cython.Build
import parsing
import setuptools_rust
RUST_VERSION = '1.59.0' # Also update docs/internal/dev.rst
EDGEDBCLI_REPO = 'https://github.com/edgedb/edgedb-cli'
# This can be a branch, tag, or commit
EDGEDBCLI_COMMIT = 'master'
EDGEDBGUI_REPO = 'https://github.com/edgedb/edgedb-studio.git'
# This can be a branch, tag, or commit
EDGEDBGUI_COMMIT = 'main'
EXT_CFLAGS: list[str] = []
if flag := os.getenv('EDGEDB_OPT_CFLAG'):
EXT_CFLAGS += [flag]
else:
EXT_CFLAGS += ['-O2']
EXT_LDFLAGS: list[str] = []
ROOT_PATH = pathlib.Path(__file__).parent.resolve()
EXT_INC_DIRS = [(ROOT_PATH / 'edb' / 'server' / 'pgproto').as_posix()]
if platform.uname().system != 'Windows':
EXT_CFLAGS.extend([
'-std=c99', '-fsigned-char', '-Wall', '-Wsign-compare', '-Wconversion'
])
def _compile_build_meta(build_lib, version, pg_config, runstate_dir,
shared_dir, version_suffix):
from edb.common import verutils
parsed_version = verutils.parse_version(version)
vertuple = list(parsed_version._asdict().values())
vertuple[2] = int(vertuple[2])
if version_suffix:
vertuple[4] = tuple(version_suffix.split('.'))
vertuple = tuple(vertuple)
pg_config_path = pathlib.Path(pg_config)
if not pg_config_path.is_absolute():
pg_config_path = f"_ROOT / {str(pg_config_path)!r}"
else:
pg_config_path = repr(str(pg_config_path))
if runstate_dir:
runstate_dir_path = pathlib.Path(runstate_dir)
if not runstate_dir_path.is_absolute():
runstate_dir_path = f"_ROOT / {str(runstate_dir_path)!r}"
else:
runstate_dir_path = repr(str(runstate_dir_path))
else:
runstate_dir_path = "None # default to <data-dir>"
shared_dir_path = pathlib.Path(shared_dir)
if not shared_dir_path.is_absolute():
shared_dir_path = f"_ROOT / {str(shared_dir_path)!r}"
else:
shared_dir_path = repr(str(shared_dir_path))
content = textwrap.dedent('''\
#
# This source file is part of the EdgeDB open source project.
#
# Copyright 2008-present MagicStack Inc. and the EdgeDB authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
#
# THIS FILE HAS BEEN AUTOMATICALLY GENERATED.
#
import pathlib
_ROOT = pathlib.Path(__file__).parent
PG_CONFIG_PATH = {pg_config_path}
RUNSTATE_DIR = {runstate_dir_path}
SHARED_DATA_DIR = {shared_dir_path}
VERSION = {version!r}
''').format(
version=vertuple,
pg_config_path=pg_config_path,
runstate_dir_path=runstate_dir_path,
shared_dir_path=shared_dir_path,
)
directory = pathlib.Path(build_lib) / 'edb'
if not directory.exists():
directory.mkdir(parents=True)
with open(directory / '_buildmeta.py', 'w+t') as f:
f.write(content)
def _get_env_with_openssl_flags():
env = dict(os.environ)
cflags = env.get('EDGEDB_BUILD_OPENSSL_CFLAGS')
ldflags = env.get('EDGEDB_BUILD_OPENSSL_LDFLAGS')
if not (cflags or ldflags) and platform.system() == 'Darwin':
try:
openssl_prefix = pathlib.Path(subprocess.check_output(
['brew', '--prefix', 'openssl'], text=True
).strip())
except (FileNotFoundError, subprocess.CalledProcessError):
openssl_prefix = None
else:
pc_path = str(openssl_prefix / 'lib' / 'pkgconfig')
if 'PKG_CONFIG_PATH' in env:
env['PKG_CONFIG_PATH'] += f':{pc_path}'
else:
env['PKG_CONFIG_PATH'] = pc_path
try:
cflags = subprocess.check_output(
['pkg-config', '--cflags', 'openssl'], text=True, env=env
).strip()
ldflags = subprocess.check_output(
['pkg-config', '--libs', 'openssl'], text=True, env=env
).strip()
except FileNotFoundError:
# pkg-config is not installed
if openssl_prefix:
cflags = f'-I{openssl_prefix / "include"!s}'
ldflags = f'-L{openssl_prefix / "lib"!s}'
else:
return env
except subprocess.CalledProcessError:
# Cannot find flags with pkg-config
return env
if cflags:
if 'CPPFLAGS' in env:
env['CPPFLAGS'] += f' {cflags}'
elif 'CFLAGS' in env:
env['CFLAGS'] += f' {cflags}'
else:
env['CPPFLAGS'] = cflags
if ldflags:
if 'LDFLAGS' in env:
env['LDFLAGS'] += f' {ldflags}'
else:
env['LDFLAGS'] = ldflags
return env
def _compile_postgres(build_base, *,
force_build=False, fresh_build=True,
run_configure=True, build_contrib=True,
produce_compile_commands_json=False):
proc = subprocess.run(
['git', 'submodule', 'status', 'postgres'],
stdout=subprocess.PIPE,
universal_newlines=True,
check=True,
cwd=ROOT_PATH,
)
status = proc.stdout
if status[0] == '-':
print('postgres submodule not initialized, '
'run `git submodule init; git submodule update`')
exit(1)
source_stamp = _get_pg_source_stamp()
postgres_build = (build_base / 'postgres').resolve()
postgres_src = ROOT_PATH / 'postgres'
postgres_build_stamp = postgres_build / 'stamp'
if postgres_build_stamp.exists():
with open(postgres_build_stamp, 'r') as f:
build_stamp = f.read()
else:
build_stamp = None
is_outdated = source_stamp != build_stamp
if is_outdated or force_build:
system = platform.system()
if system == 'Darwin':
uuidlib = 'e2fs'
elif system == 'Linux':
uuidlib = 'e2fs'
else:
raise NotImplementedError('unsupported system: {}'.format(system))
if fresh_build and postgres_build.exists():
shutil.rmtree(postgres_build)
build_dir = postgres_build / 'build'
if not build_dir.exists():
build_dir.mkdir(parents=True)
if not run_configure:
run_configure = not (build_dir / 'Makefile').exists()
if run_configure or fresh_build or is_outdated:
env = _get_env_with_openssl_flags()
subprocess.run([
str(postgres_src / 'configure'),
'--prefix=' + str(postgres_build / 'install'),
'--with-openssl',
'--with-uuid=' + uuidlib,
], check=True, cwd=str(build_dir), env=env)
if produce_compile_commands_json:
make = ['bear', '--', 'make']
else:
make = ['make']
subprocess.run(
make + ['MAKELEVEL=0', '-j', str(max(os.cpu_count() - 1, 1))],
cwd=str(build_dir), check=True)
if build_contrib or fresh_build or is_outdated:
subprocess.run(
make + [
'-C', 'contrib', 'MAKELEVEL=0', '-j',
str(max(os.cpu_count() - 1, 1))
],
cwd=str(build_dir), check=True)
subprocess.run(
['make', 'MAKELEVEL=0', 'install'],
cwd=str(build_dir), check=True)
if build_contrib or fresh_build or is_outdated:
subprocess.run(
['make', '-C', 'contrib', 'MAKELEVEL=0', 'install'],
cwd=str(build_dir), check=True)
with open(postgres_build_stamp, 'w') as f:
f.write(source_stamp)
if produce_compile_commands_json:
shutil.copy(
build_dir / "compile_commands.json",
postgres_src / "compile_commands.json",
)
def _check_rust():
import packaging.version
try:
rustc_ver = (
subprocess.check_output(["rustc", '-V'], text=True).split()[1]
.rstrip("-nightly")
)
if (
packaging.version.parse(rustc_ver)
< packaging.version.parse(RUST_VERSION)
):
raise RuntimeError(
f'please upgrade Rust to {RUST_VERSION} to compile '
f'edgedb from source')
except FileNotFoundError:
raise RuntimeError(
f'please install rustc >= {RUST_VERSION} to compile '
f'edgedb from source (see https://rustup.rs/)')
def _get_git_rev(repo, ref):
output = subprocess.check_output(
['git', 'ls-remote', repo, ref],
universal_newlines=True,
).strip()
if output:
rev, _ = output.split()
rev = rev.strip()
else:
rev = ''
# The name can be a branch or tag, so we attempt to look it up
# with ls-remote. If we don't find anything, we assume it's a
# commit hash.
return rev if rev else ref
def _get_pg_source_stamp():
output = subprocess.check_output(
['git', 'submodule', 'status', 'postgres'],
universal_newlines=True,
cwd=ROOT_PATH,
)
revision, _, _ = output[1:].partition(' ')
# I don't know why we needed the first empty char, but we don't want to
# force everyone to rebuild postgres either
source_stamp = output[0] + revision
return source_stamp
def _compile_cli(build_base, build_temp):
_check_rust()
rust_root = build_base / 'cli'
env = dict(os.environ)
env['CARGO_TARGET_DIR'] = str(build_temp / 'rust' / 'cli')
env['PSQL_DEFAULT_PATH'] = build_base / 'postgres' / 'install' / 'bin'
git_ref = env.get("EDGEDBCLI_GIT_REV") or EDGEDBCLI_COMMIT
git_rev = _get_git_rev(EDGEDBCLI_REPO, git_ref)
subprocess.run(
[
'cargo', 'install',
'--verbose', '--verbose',
'--git', EDGEDBCLI_REPO,
'--rev', git_rev,
'--bin', 'edgedb',
'--root', rust_root,
'--features=dev_mode',
'--locked',
'--debug',
],
env=env,
check=True,
)
cli_dest = ROOT_PATH / 'edb' / 'cli' / 'edgedb'
# Delete the target first, to avoid "Text file busy" errors during
# the copy if the CLI is currently running.
try:
cli_dest.unlink()
except FileNotFoundError:
pass
shutil.copy(
rust_root / 'bin' / 'edgedb',
cli_dest,
)
class build(setuptools_build.build):
user_options = setuptools_build.build.user_options
sub_commands = (
setuptools_build.build.sub_commands
+ [
("build_metadata", lambda self: True),
("build_parsers", lambda self: True),
("build_postgres", lambda self: True),
("build_cli", lambda self: True),
("build_ui", lambda self: True),
]
)
class build_metadata(setuptools.Command):
build_lib: str
user_options = [
('pg-config=', None, 'path to pg_config to use with this build'),
('runstatedir=', None, 'directory to use for the runtime state'),
('shared-dir=', None, 'directory to use for shared data'),
('version-suffix=', None, 'dot-separated local version suffix'),
]
def initialize_options(self):
self.build_lib = None
self.editable_mode = False
self.pg_config = None
self.runstatedir = None
self.shared_dir = None
self.version_suffix = None
def finalize_options(self):
self.set_undefined_options("build_py", ("build_lib", "build_lib"))
if self.pg_config is None:
self.pg_config = os.environ.get("EDGEDB_BUILD_PG_CONFIG")
if self.runstatedir is None:
self.runstatedir = os.environ.get("EDGEDB_BUILD_RUNSTATEDIR")
if self.shared_dir is None:
self.shared_dir = os.environ.get("EDGEDB_BUILD_SHARED_DIR")
if self.version_suffix is None:
self.version_suffix = os.environ.get("EDGEDB_BUILD_VERSION_SUFFIX")
def has_build_metadata(self) -> bool:
return bool(
self.pg_config
or self.runstatedir
or self.shared_dir
or self.version_suffix
)
def get_outputs(self) -> list[str]:
if self.has_build_metadata():
return [
str(pathlib.Path(self.build_lib) / 'edb' / '_buildmeta.py'),
]
else:
return []
def run(self, *args, **kwargs):
if self.has_build_metadata():
_compile_build_meta(
self.build_lib,
self.distribution.metadata.version,
self.pg_config,
self.runstatedir,
self.shared_dir,
self.version_suffix,
)
class ci_helper(setuptools.Command):
description = "echo specified hash or build info for CI"
user_options = [
('type=', None,
'one of: cli, rust, ext, parsers, postgres, bootstrap, '
'build_temp, build_lib'),
]
def run(self):
import edb as _edb
from edb.buildmeta import hash_dirs, get_cache_src_dirs
build = self.get_finalized_command('build')
pkg_dir = pathlib.Path(_edb.__path__[0])
if self.type == 'parsers':
parser_hash = hash_dirs(
[(pkg_dir / 'edgeql/parser/grammar', '.py')],
extra_files=[pkg_dir / 'edgeql-parser/src/keywords.rs'],
)
print(binascii.hexlify(parser_hash).decode())
elif self.type == 'postgres':
print(_get_pg_source_stamp().strip())
elif self.type == 'bootstrap':
bootstrap_hash = hash_dirs(
get_cache_src_dirs(),
extra_files=[pkg_dir / 'server/bootstrap.py'],
)
print(binascii.hexlify(bootstrap_hash).decode())
elif self.type == 'rust':
rust_hash = hash_dirs([
(pkg_dir / 'edgeql-parser', '.rs'),
(pkg_dir / 'edgeql-rust', '.rs'),
(pkg_dir / 'graphql-rewrite', '.rs'),
], extra_files=[
pkg_dir / 'edgeql-parser/Cargo.toml',
pkg_dir / 'edgeql-rust/Cargo.toml',
pkg_dir / 'graphql-rewrite/Cargo.toml',
])
print(binascii.hexlify(rust_hash).decode())
elif self.type == 'ext':
ext_hash = hash_dirs([
(pkg_dir, '.pyx'),
(pkg_dir, '.pyi'),
(pkg_dir, '.pxd'),
(pkg_dir, '.pxi'),
])
print(binascii.hexlify(ext_hash).decode())
elif self.type == 'cli':
print(_get_git_rev(EDGEDBCLI_REPO, EDGEDBCLI_COMMIT))
elif self.type == 'ui':
print(_get_git_rev(EDGEDBGUI_REPO, EDGEDBGUI_COMMIT))
elif self.type == 'build_temp':
print(pathlib.Path(build.build_temp).resolve())
elif self.type == 'build_lib':
print(pathlib.Path(build.build_lib).resolve())
else:
raise RuntimeError(
f'Illegal --type={self.type}; can only be: '
'cli, rust, ext, postgres, bootstrap, parsers,'
'build_temp or build_lib'
)
def initialize_options(self):
self.type = None
def finalize_options(self):
pass
class build_postgres(setuptools.Command):
description = "build postgres"
user_options = [
('configure', None, 'run ./configure'),
('build-contrib', None, 'build contrib'),
('fresh-build', None, 'rebuild from scratch'),
('compile-commands', None, 'produce compile-commands.json using bear'),
]
editable_mode: bool
def initialize_options(self):
self.editable_mode = False
self.configure = False
self.build_contrib = False
self.fresh_build = False
self.compile_commands = False
def finalize_options(self):
pass
def run(self, *args, **kwargs):
if os.environ.get("EDGEDB_BUILD_PACKAGE"):
return
build = self.get_finalized_command('build')
_compile_postgres(
pathlib.Path(build.build_base).resolve(),
force_build=True,
fresh_build=self.fresh_build,
run_configure=self.configure,
build_contrib=self.build_contrib,
produce_compile_commands_json=self.compile_commands,
)
class build_ext(setuptools_build_ext.build_ext):
user_options = setuptools_build_ext.build_ext.user_options + [
('cython-annotate', None,
'Produce a colorized HTML version of the Cython source.'),
('cython-directives=', None,
'Cython compiler directives'),
]
def initialize_options(self):
# initialize_options() may be called multiple times on the
# same command object, so make sure not to override previously
# set options.
if getattr(self, '_initialized', False):
return
super(build_ext, self).initialize_options()
if os.environ.get('EDGEDB_DEBUG'):
self.cython_always = True
self.cython_annotate = True
self.cython_directives = "linetrace=True"
self.define = 'PG_DEBUG,CYTHON_TRACE,CYTHON_TRACE_NOGIL'
self.debug = True
else:
self.cython_always = False
self.cython_annotate = None
self.cython_directives = None
self.debug = False
self.build_mode = os.environ.get('BUILD_EXT_MODE', 'both')
def finalize_options(self):
# finalize_options() may be called multiple times on the
# same command object, so make sure not to override previously
# set options.
if getattr(self, '_initialized', False):
return
if self.build_mode not in {'both', 'py-only', 'rust-only', 'skip'}:
raise RuntimeError(f'Illegal BUILD_EXT_MODE={self.build_mode}; '
f'can only be "both", "py-only" or "skip".')
if self.build_mode not in {'both', 'py-only'}:
super(build_ext, self).finalize_options()
return
directives = {
'language_level': '3'
}
if self.cython_directives:
for directive in self.cython_directives.split(','):
k, _, v = directive.partition('=')
if v.lower() == 'false':
v = False
if v.lower() == 'true':
v = True
directives[k] = v
self.distribution.ext_modules[:] = Cython.Build.cythonize(
self.distribution.ext_modules,
compiler_directives=directives,
annotate=self.cython_annotate,
include_path=["edb/server/pgproto/"])
super(build_ext, self).finalize_options()
def run(self):
if self.build_mode != 'skip':
super().run()
else:
distutils.log.info(f'Skipping build_ext because '
f'BUILD_EXT_MODE={self.build_mode}')
class build_cli(setuptools.Command):
description = "build the EdgeDB CLI"
user_options: list[str] = []
editable_mode: bool
def initialize_options(self):
self.editable_mode = False
def finalize_options(self):
pass
def run(self, *args, **kwargs):
if os.environ.get("EDGEDB_BUILD_PACKAGE"):
return
build = self.get_finalized_command('build')
_compile_cli(
pathlib.Path(build.build_base).resolve(),
pathlib.Path(build.build_temp).resolve(),
)
class build_ui(setuptools.Command):
description = "build EdgeDB UI"
user_options: list[str] = []
editable_mode: bool
build_lib: str
def initialize_options(self):
self.editable_mode = False
self.build_lib = None
def finalize_options(self):
self.set_undefined_options("build_py", ("build_lib", "build_lib"))
def run(self, *args, **kwargs):
from edb import buildmeta
from edb.common import devmode
try:
buildmeta.get_build_metadata_value("SHARED_DATA_DIR")
except buildmeta.MetadataError:
# buildmeta path resolution needs this
devmode.enable_dev_mode()
build = self.get_finalized_command('build')
self._build_ui(pathlib.Path(build.build_base).resolve())
def _build_ui(self, build_base: pathlib.Path) -> None:
from edb import buildmeta
git_ref = os.environ.get("EDGEDB_UI_GIT_REV") or EDGEDBGUI_COMMIT
git_rev = _get_git_rev(EDGEDBGUI_REPO, git_ref)
ui_root = build_base / 'edgedb-studio'
if not ui_root.exists():
subprocess.run(
[
'git',
'clone',
'--recursive',
EDGEDBGUI_REPO,
ui_root,
],
check=True
)
else:
subprocess.run(
['git', 'fetch', '--all'],
check=True,
cwd=ui_root,
)
subprocess.run(
['git', 'reset', '--hard', git_rev],
check=True,
cwd=ui_root,
)
dest = buildmeta.get_shared_data_dir_path() / 'ui'
if dest.exists():
shutil.rmtree(dest)
# install deps
subprocess.run(['yarn'], check=True, cwd=ui_root)
# run build
env = dict(os.environ)
# With CI=true (set in GH CI) `yarn build` fails if there are any
# warnings. We don't need this check in our build so we're disabling
# this behavior.
env['CI'] = ''
subprocess.run(
['yarn', 'build'],
check=True,
cwd=ui_root / 'web',
env=env
)
shutil.copytree(ui_root / 'web' / 'build', dest)
class build_parsers(setuptools.Command):
description = "build the parsers"
build_lib: str
target_root: pathlib.Path
editable_mode: bool
inplace: bool
user_options = [
('inplace', None,
'ignore build-lib and put compiled parsers into the source directory '
'alongside your pure Python modules')]
sources = [
"edb.edgeql.parser.grammar.single",
"edb.edgeql.parser.grammar.block",
"edb.edgeql.parser.grammar.sdldocument",
]
def initialize_options(self):
self.editable_mode = False
self.inplace = None
self.build_lib = None
self.target_root = None
def finalize_options(self):
self.set_undefined_options("build_py", ("build_lib", "build_lib"))
if self.editable_mode:
self.inplace = True
if self.inplace:
self.target_root = ROOT_PATH
else:
self.target_root = pathlib.Path(self.build_lib)
def get_output_mapping(self) -> dict[str, str]:
return {
str(self.target_root / src.parent / f"{src.stem}.pickle"): str(src)
for src in self._get_source_files()
}
def get_outputs(self) -> list[str]:
return list(self.get_output_mapping())
def get_source_files(self) -> list[str]:
return [str(src) for src in self._get_source_files()]
def run(self, *args, **kwargs):
for src, dst in zip(self.sources, self.get_outputs()):
spec_mod = importlib.import_module(src)
parsing.Spec(spec_mod, pickleFile=dst, verbose=True)
def _get_source_files(self) -> list[pathlib.Path]:
return [
pathlib.Path(src.replace(".", "/") + ".py")
for src in self.sources
]
class build_rust(setuptools_rust.build.build_rust):
def run(self):
_check_rust()
build_ext = self.get_finalized_command("build_ext")
if build_ext.build_mode not in {'both', 'rust-only'}:
distutils.log.info(
f'Skipping build_rust because '
f'BUILD_EXT_MODE={build_ext.build_mode}'
)
return
self.plat_name = build_ext.plat_name
copy_list = []
if not build_ext.inplace:
for ext in self.distribution.rust_extensions:
# Always build in-place because later stages of the build
# may depend on the modules having been built
dylib_path = pathlib.Path(
build_ext.get_ext_fullpath(ext.name))
build_ext.inplace = True
target_path = pathlib.Path(
build_ext.get_ext_fullpath(ext.name))
build_ext.inplace = False
copy_list.append((dylib_path, target_path))
# Workaround a bug in setuptools-rust: it uses
# shutil.copyfile(), which is not safe w.r.t mmap,
# so if the target module has been previously loaded
# bad things will happen.
if target_path.exists():
target_path.unlink()
target_path.parent.mkdir(parents=True, exist_ok=True)
os.environ['CARGO_TARGET_DIR'] = str(
pathlib.Path(build_ext.build_temp) / 'rust' / 'extensions',
)
super().run()
for src, dst in copy_list:
shutil.copyfile(src, dst)
def _version():
from edb import buildmeta
return buildmeta.get_version_from_scm(ROOT_PATH)
_entry_points = {
'edgedb-server = edb.server.main:main',
'edgedb = edb.cli:rustcli',
'edb = edb.tools.edb:edbcommands',
}
setuptools.setup(
version=_version(),
entry_points={
"console_scripts": _entry_points,
},
cmdclass={
'build': build,
'build_metadata': build_metadata,
'build_ext': build_ext,
'build_rust': build_rust,
'build_postgres': build_postgres,
'build_cli': build_cli,
'build_parsers': build_parsers,
'build_ui': build_ui,
'ci_helper': ci_helper,
},
ext_modules=[
setuptools_extension.Extension(
"edb.common.turbo_uuid",
["edb/server/pgproto/uuid.pyx"],
extra_compile_args=EXT_CFLAGS,
extra_link_args=EXT_LDFLAGS,
include_dirs=EXT_INC_DIRS,
),
setuptools_extension.Extension(
"edb.server.cache.stmt_cache",
["edb/server/cache/stmt_cache.pyx"],
extra_compile_args=EXT_CFLAGS,
extra_link_args=EXT_LDFLAGS,
include_dirs=EXT_INC_DIRS,
),
setuptools_extension.Extension(
"edb.protocol.protocol",
["edb/protocol/protocol.pyx"],
extra_compile_args=EXT_CFLAGS,
extra_link_args=EXT_LDFLAGS,
include_dirs=EXT_INC_DIRS,
),
setuptools_extension.Extension(
"edb.server.pgproto.pgproto",
["edb/server/pgproto/pgproto.pyx"],
extra_compile_args=EXT_CFLAGS,
extra_link_args=EXT_LDFLAGS,
include_dirs=EXT_INC_DIRS,
),
setuptools_extension.Extension(
"edb.server.dbview.dbview",
["edb/server/dbview/dbview.pyx"],
extra_compile_args=EXT_CFLAGS,
extra_link_args=EXT_LDFLAGS,
include_dirs=EXT_INC_DIRS,
),
setuptools_extension.Extension(
"edb.server.protocol.binary",
["edb/server/protocol/binary.pyx"],
extra_compile_args=EXT_CFLAGS,
extra_link_args=EXT_LDFLAGS,
include_dirs=EXT_INC_DIRS,
),
setuptools_extension.Extension(
"edb.server.protocol.args_ser",
["edb/server/protocol/args_ser.pyx"],
extra_compile_args=EXT_CFLAGS,
extra_link_args=EXT_LDFLAGS,
include_dirs=EXT_INC_DIRS,
),
setuptools_extension.Extension(
"edb.server.protocol.execute",
["edb/server/protocol/execute.pyx"],
extra_compile_args=EXT_CFLAGS,
extra_link_args=EXT_LDFLAGS,
include_dirs=EXT_INC_DIRS,
),
setuptools_extension.Extension(
"edb.server.protocol.notebook_ext",
["edb/server/protocol/notebook_ext.pyx"],
extra_compile_args=EXT_CFLAGS,
extra_link_args=EXT_LDFLAGS,
include_dirs=EXT_INC_DIRS,
),
setuptools_extension.Extension(
"edb.server.protocol.ui_ext",
["edb/server/protocol/ui_ext.pyx"],
extra_compile_args=EXT_CFLAGS,
extra_link_args=EXT_LDFLAGS,
include_dirs=EXT_INC_DIRS,
),
setuptools_extension.Extension(
"edb.server.protocol.edgeql_ext",
["edb/server/protocol/edgeql_ext.pyx"],
extra_compile_args=EXT_CFLAGS,
extra_link_args=EXT_LDFLAGS,
include_dirs=EXT_INC_DIRS,
),
setuptools_extension.Extension(
"edb.server.protocol.frontend",
["edb/server/protocol/frontend.pyx"],
extra_compile_args=EXT_CFLAGS,
extra_link_args=EXT_LDFLAGS,
include_dirs=EXT_INC_DIRS,
),
setuptools_extension.Extension(
"edb.server.protocol.protocol",
["edb/server/protocol/protocol.pyx"],
extra_compile_args=EXT_CFLAGS,
extra_link_args=EXT_LDFLAGS,
include_dirs=EXT_INC_DIRS,
),
setuptools_extension.Extension(
"edb.server.pgcon.pgcon",
["edb/server/pgcon/pgcon.pyx"],
extra_compile_args=EXT_CFLAGS,
extra_link_args=EXT_LDFLAGS,
include_dirs=EXT_INC_DIRS,
),
setuptools_extension.Extension(
"edb.graphql.extension",
["edb/graphql/extension.pyx"],
extra_compile_args=EXT_CFLAGS,
extra_link_args=EXT_LDFLAGS,
include_dirs=EXT_INC_DIRS,
),
],
rust_extensions=[
setuptools_rust.RustExtension(
"edb._edgeql_rust",
path="edb/edgeql-rust/Cargo.toml",
binding=setuptools_rust.Binding.RustCPython,
),
setuptools_rust.RustExtension(
"edb._graphql_rewrite",
path="edb/graphql-rewrite/Cargo.toml",
binding=setuptools_rust.Binding.RustCPython,