Debian Codegraph @

Platforms/emscripten/__main__.py

raw
1 #!/usr/bin/env python3
2
3 import argparse
4 import contextlib
5 import functools
6 import hashlib
7 import json
8 import os
9 import shutil
10 import subprocess
11 import sys
12 import sysconfig
13 import tempfile
14 from pathlib import Path
15 from textwrap import dedent
16 from urllib.request import urlopen
17
18 import tomllib
19
20 try:
21 from os import process_cpu_count as cpu_count
22 except ImportError:
23 from os import cpu_count
24
25
26 EMSCRIPTEN_DIR = Path(__file__).parent
27 CHECKOUT = EMSCRIPTEN_DIR.parent.parent
28 CONFIG_FILE = EMSCRIPTEN_DIR / "config.toml"
29
30 DEFAULT_CROSS_BUILD_DIR = CHECKOUT / "cross-build"
31 HOST_TRIPLE = "wasm32-emscripten"
32
33
34 @functools.cache
35 def load_config_toml():
36 with CONFIG_FILE.open("rb") as file:
37 return tomllib.load(file)
38
39
40 @functools.cache
41 def required_emscripten_version():
42 return load_config_toml()["emscripten-version"]
43
44
45 @functools.cache
46 def emsdk_cache_root(emsdk_cache):
47 required_version = required_emscripten_version()
48 return Path(emsdk_cache).absolute() / required_version
49
50
51 @functools.cache
52 def emsdk_activate_path(emsdk_cache):
53 return emsdk_cache_root(emsdk_cache) / "emsdk/emsdk_env.sh"
54
55
56 def get_build_paths(cross_build_dir=None, emsdk_cache=None):
57 """Compute all build paths from the given cross-build directory."""
58 if cross_build_dir is None:
59 cross_build_dir = DEFAULT_CROSS_BUILD_DIR
60 cross_build_dir = Path(cross_build_dir).absolute()
61 host_triple_dir = cross_build_dir / HOST_TRIPLE
62 prefix_dir = host_triple_dir / "prefix"
63 if emsdk_cache:
64 prefix_dir = emsdk_cache_root(emsdk_cache) / "prefix"
65
66 return {
67 "cross_build_dir": cross_build_dir,
68 "native_build_dir": cross_build_dir / "build",
69 "host_triple_dir": host_triple_dir,
70 "host_build_dir": host_triple_dir / "build",
71 "host_dir": host_triple_dir / "build" / "python",
72 "prefix_dir": prefix_dir,
73 }
74
75
76 LOCAL_SETUP = CHECKOUT / "Modules" / "Setup.local"
77 LOCAL_SETUP_MARKER = b"# Generated by Platforms/wasm/emscripten.py\n"
78
79
80 @functools.cache
81 def validate_emsdk_version(emsdk_cache):
82 """Validate that the emsdk cache contains the required emscripten version."""
83 if emsdk_cache is None:
84 print("Build will use EMSDK from current environment.")
85 return
86 required_version = required_emscripten_version()
87 emsdk_env = emsdk_activate_path(emsdk_cache)
88 if not emsdk_env.is_file():
89 print(
90 f"Required emscripten version {required_version} not found in {emsdk_cache}",
91 file=sys.stderr,
92 )
93 sys.exit(1)
94 print(f"โœ… Emscripten version {required_version} found in {emsdk_cache}")
95
96
97 def parse_env(text):
98 result = {}
99 for line in text.splitlines():
100 key, val = line.split("=", 1)
101 result[key] = val
102 return result
103
104
105 @functools.cache
106 def get_emsdk_environ(emsdk_cache):
107 """Returns os.environ updated by sourcing emsdk_env.sh"""
108 if not emsdk_cache:
109 return os.environ
110 env_text = subprocess.check_output(
111 [
112 "bash",
113 "-c",
114 f"EMSDK_QUIET=1 source {emsdk_activate_path(emsdk_cache)} && env",
115 ],
116 text=True,
117 )
118 return parse_env(env_text)
119
120
121 def updated_env(updates, emsdk_cache):
122 """Create a new dict representing the environment to use.
123
124 The changes made to the execution environment are printed out.
125 """
126 env_defaults = {}
127 # https://reproducible-builds.org/docs/source-date-epoch/
128 git_epoch_cmd = ["git", "log", "-1", "--pretty=%ct"]
129 try:
130 epoch = subprocess.check_output(
131 git_epoch_cmd, encoding="utf-8"
132 ).strip()
133 env_defaults["SOURCE_DATE_EPOCH"] = epoch
134 except subprocess.CalledProcessError:
135 pass # Might be building from a tarball.
136 # This layering lets SOURCE_DATE_EPOCH from os.environ takes precedence.
137 environment = env_defaults | get_emsdk_environ(emsdk_cache) | updates
138 env_diff = {}
139 for key, value in environment.items():
140 if os.environ.get(key) != value:
141 env_diff[key] = value
142
143 print("๐ŸŒŽ Environment changes:")
144 for key in sorted(env_diff.keys()):
145 print(f" {key}={env_diff[key]}")
146
147 return environment
148
149
150 def subdir(path_key, *, clean_ok=False):
151 """Decorator to change to a working directory.
152
153 path_key is a key into context.build_paths, used to resolve the working
154 directory at call time.
155 """
156
157 def decorator(func):
158 @functools.wraps(func)
159 def wrapper(context):
160 working_dir = context.build_paths[path_key]
161 try:
162 tput_output = subprocess.check_output(
163 ["tput", "cols"], encoding="utf-8"
164 )
165 terminal_width = int(tput_output.strip())
166 except subprocess.CalledProcessError:
167 terminal_width = 80
168 print("โŽฏ" * terminal_width)
169 print("๐Ÿ“", working_dir)
170 if (
171 clean_ok
172 and getattr(context, "clean", False)
173 and working_dir.exists()
174 ):
175 print("๐Ÿšฎ Deleting directory (--clean)...")
176 shutil.rmtree(working_dir)
177
178 working_dir.mkdir(parents=True, exist_ok=True)
179
180 with contextlib.chdir(working_dir):
181 return func(context, working_dir)
182
183 return wrapper
184
185 return decorator
186
187
188 def call(command, *, quiet, **kwargs):
189 """Execute a command.
190
191 If 'quiet' is true, then redirect stdout and stderr to a temporary file.
192 """
193 print("โฏ", " ".join(map(str, command)))
194 if not quiet:
195 stdout = None
196 stderr = None
197 else:
198 stdout = tempfile.NamedTemporaryFile(
199 "w",
200 encoding="utf-8",
201 delete=False,
202 prefix="cpython-emscripten-",
203 suffix=".log",
204 )
205 stderr = subprocess.STDOUT
206 print(f"๐Ÿ“ Logging output to {stdout.name} (--quiet)...")
207
208 subprocess.check_call(command, **kwargs, stdout=stdout, stderr=stderr)
209
210
211 def build_platform():
212 """The name of the build/host platform."""
213 # Can also be found via `config.guess`.`
214 return sysconfig.get_config_var("BUILD_GNU_TYPE")
215
216
217 def build_python_path(context):
218 """The path to the build Python binary."""
219 native_build_dir = context.build_paths["native_build_dir"]
220 binary = native_build_dir / "python"
221 if not binary.is_file():
222 binary = binary.with_suffix(".exe")
223 if not binary.is_file():
224 raise FileNotFoundError(
225 f"Unable to find `python(.exe)` in {native_build_dir}"
226 )
227
228 return binary
229
230
231 def install_emscripten(context):
232 emsdk_cache = context.emsdk_cache
233 if emsdk_cache is None:
234 print("install-emscripten requires --emsdk-cache", file=sys.stderr)
235 sys.exit(1)
236 version = required_emscripten_version()
237 emsdk_target = emsdk_cache_root(emsdk_cache) / "emsdk"
238 if emsdk_target.exists():
239 if not context.quiet:
240 print(f"Emscripten version {version} already installed")
241 return
242 if not context.quiet:
243 print(f"Installing emscripten version {version}")
244 emsdk_target.mkdir(parents=True)
245 call(
246 [
247 "git",
248 "clone",
249 "https://github.com/emscripten-core/emsdk.git",
250 emsdk_target,
251 ],
252 quiet=context.quiet,
253 )
254 call([emsdk_target / "emsdk", "install", version], quiet=context.quiet)
255 call([emsdk_target / "emsdk", "activate", version], quiet=context.quiet)
256 if not context.quiet:
257 print(f"Installed emscripten version {version}")
258
259
260 @subdir("native_build_dir", clean_ok=True)
261 def configure_build_python(context, working_dir):
262 """Configure the build/host Python."""
263 if LOCAL_SETUP.exists():
264 print(f"๐Ÿ‘ {LOCAL_SETUP} exists ...")
265 else:
266 print(f"๐Ÿ“ Touching {LOCAL_SETUP} ...")
267 LOCAL_SETUP.write_bytes(LOCAL_SETUP_MARKER)
268
269 configure = [os.path.relpath(CHECKOUT / "configure", working_dir)]
270 if context.args:
271 configure.extend(context.args)
272
273 call(configure, quiet=context.quiet)
274
275
276 @subdir("native_build_dir")
277 def make_build_python(context, working_dir):
278 """Make/build the build Python."""
279 call(["make", "--jobs", str(cpu_count()), "all"], quiet=context.quiet)
280
281 binary = build_python_path(context)
282 cmd = [
283 binary,
284 "-c",
285 "import sys; "
286 "print(f'{sys.version_info.major}.{sys.version_info.minor}')",
287 ]
288 version = subprocess.check_output(cmd, encoding="utf-8").strip()
289
290 print(f"๐ŸŽ‰ {binary} {version}")
291
292
293 def check_shasum(file: str, expected_shasum: str):
294 with open(file, "rb") as f:
295 digest = hashlib.file_digest(f, "sha256")
296 if digest.hexdigest() != expected_shasum:
297 raise RuntimeError(f"Unexpected shasum for {file}")
298
299
300 def download_and_unpack(working_dir: Path, url: str, expected_shasum: str):
301 with tempfile.NamedTemporaryFile(
302 suffix=".tar.gz", delete_on_close=False
303 ) as tmp_file:
304 with urlopen(url) as response:
305 shutil.copyfileobj(response, tmp_file)
306 tmp_file.close()
307 check_shasum(tmp_file.name, expected_shasum)
308 shutil.unpack_archive(tmp_file.name, working_dir)
309
310
311 def should_build_library(prefix, name, config, quiet):
312 cached_config = prefix / (name + ".json")
313 if not cached_config.exists():
314 if not quiet:
315 print(
316 f"No cached build of {name} version {config['version']} found, building"
317 )
318 return True
319
320 try:
321 with cached_config.open("rb") as f:
322 cached_config = json.load(f)
323 except json.JSONDecodeError:
324 if not quiet:
325 print(f"Cached data for {name} invalid, rebuilding")
326 return True
327 if config == cached_config:
328 if not quiet:
329 print(
330 f"Found cached build of {name} version {config['version']}, not rebuilding"
331 )
332 return False
333
334 if not quiet:
335 print(
336 f"Found cached build of {name} version {config['version']} but it's out of date, rebuilding"
337 )
338 return True
339
340
341 def write_library_config(prefix, name, config, quiet):
342 cached_config = prefix / (name + ".json")
343 with cached_config.open("w") as f:
344 json.dump(config, f)
345 if not quiet:
346 print(f"Succeded building {name}, wrote config to {cached_config}")
347
348
349 @subdir("host_build_dir", clean_ok=True)
350 def make_emscripten_libffi(context, working_dir):
351 validate_emsdk_version(context.emsdk_cache)
352 prefix = context.build_paths["prefix_dir"]
353 libffi_config = load_config_toml()["dependencies"]["libffi"]
354 with open(EMSCRIPTEN_DIR / "make_libffi.sh", "rb") as f:
355 libffi_config["make_libffi_shasum"] = hashlib.file_digest(f, "sha256").hexdigest()
356 if not should_build_library(
357 prefix, "libffi", libffi_config, context.quiet
358 ):
359 return
360
361 if context.check_up_to_date:
362 print("libffi out of date, expected to be up to date", file=sys.stderr)
363 sys.exit(1)
364
365 url = libffi_config["url"]
366 version = libffi_config["version"]
367 shasum = libffi_config["shasum"]
368 libffi_dir = working_dir / f"libffi-{version}"
369 shutil.rmtree(libffi_dir, ignore_errors=True)
370 download_and_unpack(
371 working_dir,
372 url.format(version=version),
373 shasum,
374 )
375 call(
376 [EMSCRIPTEN_DIR / "make_libffi.sh"],
377 env=updated_env({"PREFIX": prefix}, context.emsdk_cache),
378 cwd=libffi_dir,
379 quiet=context.quiet,
380 )
381 write_library_config(prefix, "libffi", libffi_config, context.quiet)
382
383
384 @subdir("host_build_dir", clean_ok=True)
385 def make_mpdec(context, working_dir):
386 validate_emsdk_version(context.emsdk_cache)
387 prefix = context.build_paths["prefix_dir"]
388 mpdec_config = load_config_toml()["dependencies"]["mpdec"]
389 if not should_build_library(prefix, "mpdec", mpdec_config, context.quiet):
390 return
391
392 if context.check_up_to_date:
393 print("libmpdec out of date, expected to be up to date", file=sys.stderr)
394 sys.exit(1)
395
396 url = mpdec_config["url"]
397 version = mpdec_config["version"]
398 shasum = mpdec_config["shasum"]
399 mpdec_dir = working_dir / f"mpdecimal-{version}"
400 shutil.rmtree(mpdec_dir, ignore_errors=True)
401 download_and_unpack(
402 working_dir,
403 url.format(version=version),
404 shasum,
405 )
406 call(
407 [
408 "emconfigure",
409 mpdec_dir / "configure",
410 "CFLAGS=-fPIC",
411 "--prefix",
412 prefix,
413 "--disable-shared",
414 ],
415 cwd=mpdec_dir,
416 quiet=context.quiet,
417 env=updated_env({}, context.emsdk_cache),
418 )
419 call(
420 ["make", "install"],
421 cwd=mpdec_dir,
422 quiet=context.quiet,
423 )
424 write_library_config(prefix, "mpdec", mpdec_config, context.quiet)
425
426
427 def make_dependencies(context):
428 make_emscripten_libffi(context)
429 make_mpdec(context)
430
431
432 def calculate_node_path():
433 node_version = os.environ.get("PYTHON_NODE_VERSION", None)
434 if node_version is None:
435 node_version = load_config_toml()["node-version"]
436
437 subprocess.run(
438 [
439 "bash",
440 "-c",
441 f"source ~/.nvm/nvm.sh && nvm install {node_version}",
442 ],
443 check=True,
444 )
445
446 res = subprocess.run(
447 [
448 "bash",
449 "-c",
450 f"source ~/.nvm/nvm.sh && nvm which {node_version}",
451 ],
452 text=True,
453 capture_output=True,
454 check=True,
455 )
456 return res.stdout.strip()
457
458
459 @subdir("host_dir", clean_ok=True)
460 def configure_emscripten_python(context, working_dir):
461 """Configure the emscripten/host build."""
462 validate_emsdk_version(context.emsdk_cache)
463 host_runner = context.host_runner
464 if host_runner is None:
465 host_runner = calculate_node_path()
466
467 paths = context.build_paths
468 config_site = os.fsdecode(EMSCRIPTEN_DIR / "config.site-wasm32-emscripten")
469
470 emscripten_build_dir = working_dir.relative_to(CHECKOUT)
471
472 python_build_dir = paths["native_build_dir"] / "build"
473 lib_dirs = list(python_build_dir.glob("lib.*"))
474 assert len(lib_dirs) == 1, (
475 f"Expected a single lib.* directory in {python_build_dir}"
476 )
477 lib_dir = os.fsdecode(lib_dirs[0])
478 pydebug = lib_dir.endswith("-pydebug")
479 python_version = lib_dir.removesuffix("-pydebug").rpartition("-")[-1]
480 sysconfig_data = (
481 f"{emscripten_build_dir}/build/lib.emscripten-wasm32-{python_version}"
482 )
483 if pydebug:
484 sysconfig_data += "-pydebug"
485 pkg_config_path_dir = (paths["prefix_dir"] / "lib/pkgconfig/").resolve()
486 env_additions = {
487 "CONFIG_SITE": config_site,
488 "HOSTRUNNER": host_runner,
489 "EM_PKG_CONFIG_PATH": str(pkg_config_path_dir),
490 }
491 build_python = os.fsdecode(build_python_path(context))
492 configure = [
493 "emconfigure",
494 os.path.relpath(CHECKOUT / "configure", working_dir),
495 "CFLAGS=-DPY_CALL_TRAMPOLINE -sUSE_BZIP2",
496 "PKG_CONFIG=pkg-config",
497 f"--host={HOST_TRIPLE}",
498 f"--build={build_platform()}",
499 f"--with-build-python={build_python}",
500 "--without-pymalloc",
501 "--disable-shared",
502 "--disable-ipv6",
503 "--enable-big-digits=30",
504 "--enable-wasm-dynamic-linking",
505 f"--prefix={paths['prefix_dir']}",
506 ]
507 if pydebug:
508 configure.append("--with-pydebug")
509 if context.args:
510 configure.extend(context.args)
511 call(
512 configure,
513 env=updated_env(env_additions, context.emsdk_cache),
514 quiet=context.quiet,
515 )
516
517 shutil.copy(
518 EMSCRIPTEN_DIR / "node_entry.mjs", working_dir / "node_entry.mjs"
519 )
520
521 shutil.copy(
522 EMSCRIPTEN_DIR / "streams.mjs", working_dir / "streams.mjs"
523 )
524
525 node_entry = working_dir / "node_entry.mjs"
526 exec_script = working_dir / "python.sh"
527 exec_script.write_text(
528 dedent(
529 f"""\
530 #!/bin/sh
531
532 # Macs come with FreeBSD coreutils which doesn't have the -s option
533 # so feature detect and work around it.
534 if which grealpath > /dev/null 2>&1; then
535 # It has brew installed gnu core utils, use that
536 REALPATH="grealpath -s"
537 elif which realpath > /dev/null 2>&1 && realpath --version > /dev/null 2>&1 && realpath --version | grep GNU > /dev/null 2>&1; then
538 # realpath points to GNU realpath so use it.
539 REALPATH="realpath -s"
540 else
541 # Shim for macs without GNU coreutils
542 abs_path () {{
543 echo "$(cd "$(dirname "$1")" || exit; pwd)/$(basename "$1")"
544 }}
545 REALPATH=abs_path
546 fi
547
548 # Before node 24, --experimental-wasm-jspi uses different API,
549 # After node 24 JSPI is on by default.
550 ARGS=$({host_runner} -e "$(cat <<"EOF"
551 const major_version = Number(process.version.split(".")[0].slice(1));
552 if (major_version === 24) {{
553 process.stdout.write("--experimental-wasm-jspi");
554 }}
555 EOF
556 )")
557
558 # We compute our own path, not following symlinks and pass it in so that
559 # node_entry.mjs can set sys.executable correctly.
560 # Intentionally allow word splitting on NODEFLAGS.
561 exec {host_runner} $NODEFLAGS $ARGS {node_entry} --this-program="$($REALPATH "$0")" "$@"
562 """
563 )
564 )
565 exec_script.chmod(0o755)
566 print(f"๐Ÿƒโ€โ™€๏ธ Created {exec_script} ... ")
567 sys.stdout.flush()
568
569
570 @subdir("host_dir")
571 def make_emscripten_python(context, working_dir):
572 """Run `make` for the emscripten/host build."""
573 call(
574 ["make", "--jobs", str(cpu_count()), "all"],
575 env=updated_env({}, context.emsdk_cache),
576 quiet=context.quiet,
577 )
578
579 exec_script = working_dir / "python.sh"
580 subprocess.check_call([exec_script, "--version"])
581
582
583 def run_emscripten_python(context):
584 """Run the built emscripten Python."""
585 host_dir = context.build_paths["host_dir"]
586 exec_script = host_dir / "python.sh"
587 if not exec_script.is_file():
588 print("Emscripten not built", file=sys.stderr)
589 sys.exit(1)
590
591 args = context.args
592 # Strip the "--" separator if present
593 if args and args[0] == "--":
594 args = args[1:]
595
596 if context.test:
597 args = load_config_toml()["test-args"] + args
598 elif context.pythoninfo:
599 args = load_config_toml()["pythoninfo-args"] + args
600
601 os.execv(str(exec_script), [str(exec_script), *args])
602
603
604 def build_target(context):
605 """Build one or more targets."""
606 steps = []
607 if context.target in {"build", "all"}:
608 steps.extend([
609 configure_build_python,
610 make_build_python,
611 ])
612 if context.target in {"host", "all"}:
613 steps.extend([
614 make_emscripten_libffi,
615 make_mpdec,
616 configure_emscripten_python,
617 make_emscripten_python,
618 ])
619
620 for step in steps:
621 step(context)
622
623
624 def clean_contents(context):
625 """Delete all files created by this script."""
626 if context.target in {"all", "build"}:
627 build_dir = context.build_paths["native_build_dir"]
628 if build_dir.exists():
629 print(f"๐Ÿงน Deleting {build_dir} ...")
630 shutil.rmtree(build_dir)
631
632 if context.target in {"all", "host"}:
633 host_triple_dir = context.build_paths["host_triple_dir"]
634 if host_triple_dir.exists():
635 print(f"๐Ÿงน Deleting {host_triple_dir} ...")
636 shutil.rmtree(host_triple_dir)
637
638 if LOCAL_SETUP.exists():
639 with LOCAL_SETUP.open("rb") as file:
640 if file.read(len(LOCAL_SETUP_MARKER)) == LOCAL_SETUP_MARKER:
641 print(f"๐Ÿงน Deleting generated {LOCAL_SETUP} ...")
642
643
644 def add_cross_build_dir_option(subcommand):
645 subcommand.add_argument(
646 "--cross-build-dir",
647 action="store",
648 default=os.environ.get("CROSS_BUILD_DIR"),
649 dest="cross_build_dir",
650 help=(
651 "Path to the cross-build directory "
652 f"(default: {DEFAULT_CROSS_BUILD_DIR}). "
653 "Can also be set with the CROSS_BUILD_DIR environment variable.",
654 ),
655 )
656
657
658 def main():
659 parser = argparse.ArgumentParser()
660 subcommands = parser.add_subparsers(dest="subcommand")
661
662 install_emscripten_cmd = subcommands.add_parser(
663 "install-emscripten",
664 help="Install the appropriate version of Emscripten",
665 )
666
667 build = subcommands.add_parser("build", help="Build everything")
668 build.add_argument(
669 "target",
670 nargs="?",
671 default="all",
672 choices=["all", "host", "build"],
673 help=(
674 "What should be built. 'build' for just the build platform, or "
675 "'host' for the host platform, or 'all' for both. Defaults to 'all'."
676 ),
677 )
678
679 configure_build = subcommands.add_parser(
680 "configure-build-python", help="Run `configure` for the build Python"
681 )
682
683 make_mpdec_cmd = subcommands.add_parser(
684 "make-mpdec",
685 help="Clone mpdec repo, configure and build it for emscripten",
686 )
687
688 make_libffi_cmd = subcommands.add_parser(
689 "make-libffi",
690 help="Clone libffi repo, configure and build it for emscripten",
691 )
692
693 make_dependencies_cmd = subcommands.add_parser(
694 "make-dependencies",
695 help="Build all static library dependencies",
696 )
697
698 for cmd in [make_mpdec_cmd, make_libffi_cmd, make_dependencies_cmd]:
699 cmd.add_argument(
700 "--check-up-to-date",
701 action="store_true",
702 default=False,
703 help=("If passed, will fail if dependency is out of date"),
704 )
705
706 make_build = subcommands.add_parser(
707 "make-build-python", help="Run `make` for the build Python"
708 )
709
710 configure_host = subcommands.add_parser(
711 "configure-host",
712 help=(
713 "Run `configure` for the host/emscripten "
714 "(pydebug builds are inferred from the build Python)"
715 ),
716 )
717
718 make_host = subcommands.add_parser(
719 "make-host", help="Run `make` for the host/emscripten"
720 )
721
722 run = subcommands.add_parser(
723 "run",
724 help="Run the built emscripten Python",
725 )
726 run.add_argument(
727 "--test",
728 action="store_true",
729 default=False,
730 help=(
731 "Add the default test arguments to the beginning of the command. "
732 "Default arguments loaded from Platforms/emscripten/config.toml"
733 ),
734 )
735 run.add_argument(
736 "--pythoninfo",
737 action="store_true",
738 default=False,
739 help="Run -m test.pythoninfo",
740 )
741 run.add_argument(
742 "args",
743 nargs=argparse.REMAINDER,
744 help=(
745 "Arguments to pass to the emscripten Python "
746 "(use '--' to separate from run options)",
747 ),
748 )
749 add_cross_build_dir_option(run)
750
751 clean = subcommands.add_parser(
752 "clean", help="Delete files and directories created by this script"
753 )
754 clean.add_argument(
755 "target",
756 nargs="?",
757 default="host",
758 choices=["all", "host", "build"],
759 help=(
760 "What should be cleaned. 'build' for just the build platform, or "
761 "'host' for the host platform, or 'all' for both. Defaults to 'host'."
762 ),
763 )
764
765 for subcommand in (
766 install_emscripten_cmd,
767 build,
768 configure_build,
769 make_libffi_cmd,
770 make_mpdec_cmd,
771 make_dependencies_cmd,
772 make_build,
773 configure_host,
774 make_host,
775 clean,
776 ):
777 subcommand.add_argument(
778 "--quiet",
779 action="store_true",
780 default="QUIET" in os.environ,
781 dest="quiet",
782 help=(
783 "Redirect output from subprocesses to a log file. "
784 "Can also be set with the QUIET environment variable."
785 ),
786 )
787 add_cross_build_dir_option(subcommand)
788 subcommand.add_argument(
789 "--emsdk-cache",
790 action="store",
791 default=os.environ.get("EMSDK_CACHE"),
792 dest="emsdk_cache",
793 help=(
794 "Path to emsdk cache directory. If provided, validates that "
795 "the required emscripten version is installed. "
796 "Can also be set with the EMSDK_CACHE environment variable."
797 ),
798 )
799
800 for subcommand in configure_build, configure_host:
801 subcommand.add_argument(
802 "--clean",
803 action="store_true",
804 default=False,
805 dest="clean",
806 help="Delete any relevant directories before building",
807 )
808
809 for subcommand in build, configure_build, configure_host:
810 subcommand.add_argument(
811 "args", nargs="*", help="Extra arguments to pass to `configure`"
812 )
813
814 for subcommand in build, configure_host:
815 subcommand.add_argument(
816 "--host-runner",
817 action="store",
818 default=None,
819 dest="host_runner",
820 help="Command template for running the emscripten host "
821 "(default: use nvm to install the node version specified in config.toml)",
822 )
823
824 context = parser.parse_args()
825 context.emsdk_cache = getattr(context, "emsdk_cache", None)
826 context.cross_build_dir = getattr(context, "cross_build_dir", None)
827 context.check_up_to_date = getattr(context, "check_up_to_date", False)
828
829 if context.emsdk_cache:
830 context.emsdk_cache = Path(context.emsdk_cache).absolute()
831
832 context.build_paths = get_build_paths(
833 context.cross_build_dir, context.emsdk_cache
834 )
835
836 dispatch = {
837 "install-emscripten": install_emscripten,
838 "make-libffi": make_emscripten_libffi,
839 "make-mpdec": make_mpdec,
840 "make-dependencies": make_dependencies,
841 "configure-build-python": configure_build_python,
842 "make-build-python": make_build_python,
843 "configure-host": configure_emscripten_python,
844 "make-host": make_emscripten_python,
845 "build": build_target,
846 "run": run_emscripten_python,
847 "clean": clean_contents,
848 }
849
850 if not context.subcommand:
851 # No command provided, display help and exit
852 print(
853 "Expected one of",
854 ", ".join(sorted(dispatch.keys())),
855 file=sys.stderr,
856 )
857 parser.print_help(sys.stderr)
858 sys.exit(1)
859 dispatch[context.subcommand](context)
860
861
862 if __name__ == "__main__":
863 main()