diff --git a/.bazelrc b/.bazelrc index 9ba431d..4136985 100644 --- a/.bazelrc +++ b/.bazelrc @@ -47,9 +47,16 @@ build:buildbuddy-rbe --remote_executor=grpcs://elide-dev.buildbuddy.io build:elide-unified --@rules_elide//elide:unified_jvm_compile build:labsjdk --java_runtime_version=labsjdk_25 + +common:dev --repo_env=RULES_MX_LIVE=1 +build:dev --config=elide-processors +build:dev --config=labsjdk + build:native-image-linux --extra_toolchains=//tools/cc:elide_cc_linux_amd64 build:source-native-image --config=labsjdk build:source-native-image --tool_java_runtime_version=labsjdk_25 build:source-native-image --config=elide-processors build:source-native-image --extra_toolchains=//graal:source_native_image_toolchain + +try-import %workspace%/user.bazelrc diff --git a/.gitignore b/.gitignore index 6712f8c..f371fa5 100644 --- a/.gitignore +++ b/.gitignore @@ -2,4 +2,5 @@ __pycache__/ +/user.bazelrc /.graal-dev/ diff --git a/graal/README.md b/graal/README.md index 4c6a134..0f475ea 100644 --- a/graal/README.md +++ b/graal/README.md @@ -12,31 +12,30 @@ tools/buildbuddy test --config=buildbuddy-rbe --config=elide-processors //graal/ ## Work on sibling checkouts -Use `tools/graal-dev` from the `rules_mx` checkout. It looks for a sibling `graal` checkout and optional `graaljs` and `graalpython` checkouts. If your source checkouts live in a separate parent directory, pass it with `--workspace`. +Keep `rules_mx`, `graal`, and any `graaljs` and `graalpython` checkouts beside each other. Run Bazel from `rules_mx` with `--config=dev`. Bazel locates the sibling checkouts and selects the Elide processor toolchain and Labs JDK 25. Add `common --config=dev` to your local `user.bazelrc` to use the checkouts with plain `bazel` commands. ```sh -tools/graal-dev test --config=elide-processors @graal//sdk:org.graalvm.word.test.org.graalvm.word.test.WordTests -tools/graal-dev run --config=elide-processors @graal//graal-js:js -- -e 'print(6 * 7)' -tools/graal-dev test --config=elide-processors @graal//graal-js:regression/direct_eval -tools/graal-dev run --config=elide-processors --config=labsjdk @graal//graalpython:python -- -c 'import sys; print(sys.version)' -tools/graal-dev test --config=elide-processors --config=labsjdk @graal//graalpython:zlib/ChecksumTestCase.test_crc32start +bazel run --config=dev @graal//graal-js:js -- -e 'print(6 * 7)' +bazel test --config=dev @graal//graal-js:regression/direct_eval +bazel test --config=dev @graal//graalpython:zlib/ChecksumTestCase.test_crc32start +bazel build --config=dev @graal//graalpython:GRAALPY_JVM_STANDALONE_RELEASE_ARCHIVE ``` Use a reverse-dependency query to select tests from the packages and targets you want to check. This example finds GraalJS regressions and the Truffle SimpleLanguage Fibonacci test affected by an edit to the Truffle API. ```sh -tools/graal-dev query 'kind(".*_test rule", rdeps(@graal//graal-js:all + @graal//truffle:sl.test.Fibonacci, @graal//truffle:com.oracle.truffle.api))' +bazel query --config=dev 'kind(".*_test rule", rdeps(@graal//graal-js:all + @graal//truffle:sl.test.Fibonacci, @graal//truffle:com.oracle.truffle.api))' ``` -The command generates the local BUILD overlays from mx and Gazelle and symlinks source files into the same Bazel repository. Edits to existing sources are visible to Bazel immediately. Adding, removing, or renaming a file and changing mx suite metadata refresh the generated graph. Use `--sync` after changing Java imports or other source content that changes Gazelle’s dependency analysis. The checkouts need to match the Bazel input pins in `rules_mx`. CI qualifies Graal at `21dea4d`, GraalJS at `747d45b`, and GraalPy at `11344f3`. +Bazel generates BUILD files from mx and Gazelle on first use. Edits to existing source files flow directly into compilation and tests. File additions, removals, renames, and changes to mx suite metadata refresh the graph. After editing Java imports that change Gazelle’s dependency analysis, refresh it with `bazel fetch --config=dev --force --repo=@graal`. The checkouts need to match the Bazel input pins in `rules_mx`. CI qualifies Graal at `21dea4d`, GraalJS at `747d45b`, and GraalPy at `11344f3`. The live GraalPy launcher uses Labs JDK 25 and bundles the standard library, GraalPy core library, headers, platform versions, and source-built zlib. The first two upstream zlib checks are individually selectable. -Build `@graal//graalpython:GRAALPY_JVM_STANDALONE_RELEASE_ARCHIVE` with `--config=elide-processors --config=labsjdk` for an installable tarball. It bundles the pinned JDK, package-relative launchers, frozen bytecode from the upstream freezer, native POSIX and zlib support, and the C API extensions built with the upstream CMake project. The installed launcher uses the bundled runtime in the `jvm/` and `modules/` directories. `@graal//graalpython:jvm_standalone_test` extracts the archive into a path containing spaces and tests frozen imports, native modules, and upstream zlib checks. +The GraalPy JVM standalone tarball bundles the pinned JDK, package-relative launchers, frozen bytecode from the upstream freezer, native POSIX and zlib support, and the C API extensions built with the upstream CMake project. The installed launcher uses the bundled runtime in the `jvm/` and `modules/` directories. `@graal//graalpython:jvm_standalone_test` extracts the archive into a path containing spaces and tests frozen imports, native modules, and upstream zlib checks. The JVM archive uses a classpath launcher and compiles from the checked-in PEG parser. Native Image and GraalOS standalones, native bzip2 and LZMA, and the virtualenv seeder remain separate work. -Pass `--buildbuddy` before the Bazel command to use the existing BuildBuddy wrapper. The generated repository lives under `.graal-dev/` or the path supplied by `--state-dir`. +For BuildBuddy, use `tools/buildbuddy test --config=dev --config=buildbuddy-rbe` with the same target labels. If your source checkouts live under a different parent, set `common:dev --repo_env=RULES_MX_CHECKOUTS=/path/to/parent` in `user.bazelrc`. ## Current coverage diff --git a/graal/extensions.bzl b/graal/extensions.bzl index 6fedc16..c2037c5 100644 --- a/graal/extensions.bzl +++ b/graal/extensions.bzl @@ -1,6 +1,7 @@ -"""Select the Graal source archive that the checked-in overlays are applied to.""" +"""Expose Graal sources from a pinned archive or live sibling checkouts.""" load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") +load(":live_repository.bzl", "graal_live_repository") # Generated by tools/generate-graal from the source in //graal:source.json. OVERLAYS = [ @@ -56,6 +57,9 @@ def _graal_impl(ctx): if len(module.tags.source) > 1: fail("Declare graal.source() at most once") selected = module.tags.source[0] + if ctx.getenv("RULES_MX_LIVE") == "1": + graal_live_repository(name = "graal", patches = OVERLAYS) + return ctx.extension_metadata(reproducible = True) if selected: source = struct( urls = selected.urls, @@ -94,5 +98,5 @@ write_file(name = "mx-source.json", out = "source-info.json", content = ["{}"], graal = module_extension( implementation = _graal_impl, tag_classes = {"source": _source}, - doc = "Provides @graal: a Graal source archive with BUILD overlays.", + doc = "Provides @graal from a pinned archive or live sibling checkouts.", ) diff --git a/graal/live_repository.bzl b/graal/live_repository.bzl new file mode 100644 index 0000000..db148cd --- /dev/null +++ b/graal/live_repository.bzl @@ -0,0 +1,62 @@ +"""Materialize the mx and Gazelle graph for live GraalVM checkouts.""" + +def _live_repository_impl(ctx): + checkout_parent = ctx.getenv("RULES_MX_CHECKOUTS") or str(ctx.workspace_root.dirname) + if not checkout_parent.startswith("/"): + checkout_parent = str(ctx.workspace_root) + "/" + checkout_parent + python = ctx.which("python3") + bazel = ctx.which("bazel") or ctx.which("bazelisk") + if not python or not bazel: + fail("Live Graal checkout discovery requires python3 and Bazel on PATH") + + helper = ctx.path(ctx.attr._helper) + for label in ctx.attr._graph_inputs + ctx.attr.patches: + ctx.watch(label) + patches = [ctx.path(label) for label in ctx.attr.patches] + inventory = ctx.execute([python, helper, "scan", checkout_parent] + patches) + if inventory.return_code: + fail(inventory.stderr) + inputs = json.decode(inventory.stdout) + for file in inputs["watch_files"]: + ctx.watch(file) + for directory in inputs["watch_dirs"]: + ctx.path(directory).readdir() + + # Bazel runs the generator's tool targets in a separate output base so they + # can resolve and build while the main invocation is fetching @graal. + repo = ctx.path("") + tooling = repo.dirname.dirname.get_child("graal-graph") + ctx.file(".graph-inputs.json", inventory.stdout, executable = False) + ctx.report_progress("Generating BUILD files from live GraalVM checkouts") + result = ctx.execute( + [python, helper, "generate", repo, bazel, tooling] + patches, + timeout = 1800, + ) + if result.return_code: + fail(result.stderr) + ctx.delete(".graph-inputs.json") + +graal_live_repository = repository_rule( + implementation = _live_repository_impl, + attrs = { + "patches": attr.label_list(mandatory = True), + "_helper": attr.label(default = Label("//tools:graal_live_repository.py")), + "_graph_inputs": attr.label_list(default = [ + Label("//:MODULE.bazel"), + Label("//graal:libffi.json"), + Label("//graal:live_suites.json"), + Label("//graal:packed_sources.json"), + Label("//graal:sdk_llvm.json"), + Label("//graal:sdk_musl.json"), + Label("//graal:shaded_inputs.json"), + Label("//graal:suite_imports.json"), + Label("//graal:svm_inputs.json"), + Label("//graal:visualvm.json"), + Label("//mx:export.py"), + Label("//mx:labsjdk.json"), + Label("//mx:labsjdk21.json"), + Label("//mx/gazelle:graph.go"), + Label("//tools:generate-graal"), + ]), + }, +) diff --git a/tools/check-graal-dev b/tools/check-graal-dev index 4ba0fcf..f66544a 100755 --- a/tools/check-graal-dev +++ b/tools/check-graal-dev @@ -53,20 +53,17 @@ def main(config): source, _ = fetch_source(spec, download) source.rename(workspace / name) - dev = [ - ROOT / "tools/graal-dev", - "--workspace", - workspace, - "--state-dir", - workspace / "overlays", - ] - if "--config=buildbuddy-rbe" in config: - dev.append("--buildbuddy") - options = ["--config=elide-processors", "--config=labsjdk", *config] + remote = "--config=buildbuddy-rbe" in config + options = ["--config=dev", f"--repo_env=RULES_MX_CHECKOUTS={workspace}"] def invoke(command, *args, **kwargs): + bazel = "bazelisk" + flags = options + if command != "query": + bazel = ROOT / "tools/buildbuddy" if remote else bazel + flags = [*flags, *config] return subprocess.run( - [*dev, command, *options, *args], cwd=ROOT, check=True, **kwargs + [bazel, command, *flags, *args], cwd=ROOT, check=True, **kwargs ) def read_marker(launcher, marker): @@ -88,26 +85,31 @@ def main(config): raise return result.stdout.strip() - affected = subprocess.check_output( - [ - *dev, - "query", - f'kind(".*_test rule", rdeps(@graal//graal-js:all + filter(":zlib/", @graal//graalpython:all) + {FIBONACCI}, {TRUFFLE_LABEL}))', - ], - cwd=ROOT, + affected = invoke( + "query", + f'kind(".*_test rule", rdeps(@graal//graal-js:all + filter(":zlib/", @graal//graalpython:all) + {FIBONACCI}, {TRUFFLE_LABEL}))', + stdout=subprocess.PIPE, text=True, - ).splitlines() + ).stdout.splitlines() if set(affected) != REGRESSIONS: raise SystemExit( f"Unexpected test selection for the Truffle source edit {affected!r}" ) - configured = sorted((workspace / "overlays").glob("*.current")) - if len(configured) != 1: - raise SystemExit(f"Expected one live overlay. Found {configured!r}") + location = invoke( + "query", + "--output=location", + "@graal//:mx-source.json", + stdout=subprocess.PIPE, + text=True, + ).stdout + manifest = Path(location.split(": source file ", 1)[0].rsplit(":", 2)[0]) + configured = manifest.stat().st_mtime_ns for launcher, marker in LAUNCHERS.items(): baseline = read_marker(launcher, marker) if baseline != "before": - raise SystemExit(f"Unexpected baseline output from {launcher}: {baseline!r}") + raise SystemExit( + f"Unexpected baseline output from {launcher}: {baseline!r}" + ) invoke("test", "--test_output=errors", *affected) truffle = workspace / "graal" / TRUFFLE_SOURCE source = truffle.read_text() @@ -133,7 +135,7 @@ def main(config): raise SystemExit( f"{launcher} did not see the Truffle edit. Output was {changed!r}" ) - if sorted((workspace / "overlays").glob("*.current")) != configured: + if manifest.stat().st_mtime_ns != configured: raise SystemExit("Editing an existing Truffle source regenerated the graph") invoke("test", "--test_output=errors", *affected) events = workspace / "cached.json" @@ -158,8 +160,12 @@ def main(config): raise SystemExit( f"Expected cached results for the selected tests. Events {results!r}" ) - print("The Truffle edit reached GraalJS and GraalPy, and all selected tests were cached on repeat.") - invoke("test", "--test_output=errors", "@graal//graalpython:jvm_standalone_test") + print( + "The Truffle edit reached GraalJS and GraalPy, and all selected tests were cached on repeat." + ) + invoke( + "test", "--test_output=errors", "@graal//graalpython:jvm_standalone_test" + ) if __name__ == "__main__": diff --git a/tools/generate-graal b/tools/generate-graal index 11e20e7..3930c1b 100755 --- a/tools/generate-graal +++ b/tools/generate-graal @@ -18,6 +18,19 @@ import tempfile import urllib.request ROOT = Path(__file__).resolve().parents[1] + + +def bazel_command(command): + bazel = os.environ.get("RULES_MX_GRAPH_BAZEL", "bazelisk") + output_base = os.environ.get("RULES_MX_GRAPH_OUTPUT_BASE") + if output_base: + args = [bazel, "--output_base=" + output_base, command, "--repo_env=RULES_MX_LIVE=0"] + if command in {"build", "run"}: + args.append("--symlink_prefix=/") + return args + return [bazel, command] + + SVM_SUPPORT_JARS = ( "JVMTI_AGENT_BASE", "SVM_AGENT", @@ -2420,8 +2433,7 @@ def prepare_suite(suite, stage, peers=()): with (directory / "mx-graph.json").open("w") as graph: subprocess.run( [ - "bazelisk", - "run", + *bazel_command("run"), "--config=labsjdk", "//:mx", "--", @@ -2760,8 +2772,7 @@ def generate_build_files(suites, stage): return subprocess.run( [ - "bazelisk", - "run", + *bazel_command("run"), "//:gazelle", "--", "-repo_root=" + str(stage), @@ -2791,7 +2802,7 @@ def build_patch(directory, stage): def bazel_source(label): location = subprocess.check_output( - ["bazelisk", "query", "--output=location", label], cwd=ROOT, text=True + [*bazel_command("query"), "--output=location", label], cwd=ROOT, text=True ) return Path(location.split(": source file ", 1)[0].rsplit(":", 2)[0]) @@ -2834,13 +2845,18 @@ def fetch_source(pin, stage): return root / pin["strip_prefix"], digest.hexdigest() -def labsjdk_pin(source, current, selector, repository): - """Pin labsjdk-ce-latest from the selected source's common.json.""" +def labsjdk_pin(source, current, selector, repository, *, update): + """Resolve a Labs JDK version declared in the source's common.json.""" version = json.loads((source / "common.json").read_text())["jdks"][selector][ "version" ] if current.get("version") == version: return current + if not update: + raise SystemExit( + f"{source} requires {version}, but rules_mx pins {current['version']}. " + "Use a compatible Graal checkout or update the rules_mx input pins." + ) jdk, jvmci = version.split("-jvmci-") request = urllib.request.Request( f"https://api.github.com/repos/graalvm/{repository}/releases/tags/jvmci-{jvmci}", @@ -2926,6 +2942,7 @@ def main(): if args.archive and args.strip_prefix is None: parser.error("--archive requires --strip-prefix") output = args.output.resolve() + live = bool(os.environ.get("RULES_MX_GRAPH_OUTPUT_BASE")) # Keep a downloaded tree outside the stage so mx sees one copy of each suite. with ( tempfile.TemporaryDirectory() as temp, @@ -2956,7 +2973,7 @@ def main(): emit( labsjdk if output == ROOT / "graal" else output / filename, json.dumps( - labsjdk_pin(source, current, selector, repository), + labsjdk_pin(source, current, selector, repository, update=not live), indent=2, sort_keys=True, ) @@ -2964,6 +2981,10 @@ def main(): args.check, "Regenerate the Labs JDK pin with tools/generate-graal", ) + if live: + # Bootstrap Gazelle before staging the sources so its cold build and + # the staged tree do not need temporary disk space at the same time. + subprocess.run([*bazel_command("build"), "//:gazelle"], cwd=ROOT, check=True) mx_suite = bazel_source("@graal_mx//:mx.mx/suite.py") shutil.copyfile(mx_suite, stage / "mx-suite.py") for family in ("gcc", "msvc"): diff --git a/tools/graal-dev b/tools/graal_live_repository.py similarity index 50% rename from tools/graal-dev rename to tools/graal_live_repository.py index 83dada7..440c5c4 100755 --- a/tools/graal-dev +++ b/tools/graal_live_repository.py @@ -1,14 +1,13 @@ #!/usr/bin/env python3 -"""Run Bazel against live sibling GraalVM checkouts.""" +"""Inventory live GraalVM checkouts and materialize Bazel's source repository.""" -import argparse -import hashlib import json import os from pathlib import Path import re import shutil import subprocess +import sys import tempfile ROOT = Path(__file__).resolve().parents[1] @@ -33,16 +32,6 @@ def checkout_files(checkout): ) -def overlay_paths(): - return [ - OVERLAYS / name - for name in re.findall( - r'Label\("//graal:([^"]+\.patch)"\)', - (OVERLAYS / "extensions.bzl").read_text(), - ) - ] - - def changed_paths(patch): # The checked-in overlays have simple unified-diff paths. Only copy existing # patched files so git apply never sees a writable path into either checkout. @@ -53,53 +42,46 @@ def changed_paths(patch): def apply_patch(root, patch): + env = {**os.environ, "GIT_CEILING_DIRECTORIES": str(root.parent)} result = subprocess.run( ["git", "apply", "--unidiff-zero", "--reverse", "--check", str(patch)], cwd=root, capture_output=True, + env=env, ) if result.returncode: subprocess.run( - ["git", "apply", "--unidiff-zero", str(patch)], cwd=root, check=True + ["git", "apply", "--unidiff-zero", str(patch)], + cwd=root, + check=True, + env=env, ) -def graph_digest(sources, fixes, checkouts): - digest = hashlib.sha256() - for checkout in checkouts: - digest.update(os.fsencode(checkout) + b"\0") - if (checkout / ".git").exists(): - digest.update( - subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=checkout) - ) - for path, source in sorted(sources.items()): - digest.update(os.fsencode(path) + b"\0") - if path.name in {"common.json", "BUILD", "BUILD.bazel"} or any( - part.startswith("mx.") for part in path.parts - ): - digest.update(source.read_bytes()) - for patch in fixes: - digest.update(patch.read_bytes()) - for path in changed_paths(patch): - if path not in sources: - raise SystemExit( - f"{patch.name} requires {path} in the selected checkout" - ) - digest.update(sources[path].read_bytes()) - graph_tools = [ - "tools/generate-graal", - "mx/export.py", - "mx/gazelle/graph.go", - "MODULE.bazel", +def git_inputs(checkout): + if not (checkout / ".git").exists(): + return [] + ref = subprocess.run( + ["git", "symbolic-ref", "-q", "HEAD"], + cwd=checkout, + capture_output=True, + text=True, + ).stdout.strip() + names = ["HEAD", "index", "packed-refs"] + if ref: + names.append(ref) + return [ + checkout / path + for path in subprocess.check_output( + [ + "git", + "rev-parse", + *[flag for name in names for flag in ("--git-path", name)], + ], + cwd=checkout, + text=True, + ).splitlines() ] - for path in [ - Path(__file__), - *(ROOT / tool for tool in graph_tools), - *sorted(OVERLAYS.glob("*.json")), - *sorted((ROOT / "mx").glob("labsjdk*.json")), - ]: - digest.update(path.read_bytes()) - return digest.hexdigest() def provenance(checkout): @@ -139,18 +121,26 @@ def check_input_pins(generated): ) -def create_repository(workspace, state, force_sync): - graal = (workspace / "graal").resolve(strict=True) +def scan(workspace, patches): + graal = (workspace / "graal").resolve() + if not (graal / "truffle/mx.truffle/suite.py").is_file(): + raise SystemExit(f"Expected a Graal checkout at {workspace / 'graal'}") checkouts = [graal] - peer_flags = [] + peer_paths = {} sources = {path: graal / path for path in checkout_files(graal)} + watch_files = {workspace / "graal"} + watch_dirs = {graal} for suite, spec in json.loads((OVERLAYS / "live_suites.json").read_text()).items(): - checkout = (workspace / spec["checkout"]).resolve() + entry = workspace / spec["checkout"] + checkout = entry.resolve() directory = Path(spec["path"]) - if not (checkout / directory / f"mx.{suite}/suite.py").is_file(): + metadata = entry / directory / f"mx.{suite}/suite.py" + watch_files.update([entry, metadata]) + if not metadata.is_file(): continue checkouts.append(checkout) - peer_flags.extend(["--peer", f"{suite}={checkout / directory}"]) + peer_paths[suite] = str(checkout / directory) + watch_dirs.add(checkout / directory) sources.update( { Path(suite) / path.relative_to(directory): checkout / path @@ -158,104 +148,101 @@ def create_repository(workspace, state, force_sync): if path.is_relative_to(directory) } ) - patches = overlay_paths() - fixes = [patch for patch in patches if changed_paths(patch)] - key = graph_digest(sources, patches, checkouts) - state.mkdir(parents=True, exist_ok=True) - current = state / (key + ".current") - if current.is_dir() and not force_sync: - return current.resolve() + roots = tuple(watch_dirs) + for path, source in sources.items(): + for parent in source.parents: + if parent in roots: + break + watch_dirs.add(parent) + if path.name in {"common.json", "BUILD", "BUILD.bazel", ".gitignore"} or any( + part.startswith("mx.") for part in path.parts + ): + watch_files.add(source) + for checkout in checkouts: + watch_files.update(git_inputs(checkout)) + for patch in patches: + for path in changed_paths(patch): + watch_files.add(sources.get(path, graal / path)) + print( + json.dumps( + { + "graal": str(graal), + "peers": peer_paths, + "sources": {str(path): str(sources[path]) for path in sorted(sources)}, + "watch_files": sorted(map(str, watch_files)), + "watch_dirs": sorted(map(str, watch_dirs)), + } + ) + ) + - with tempfile.TemporaryDirectory(dir=state) as work: +def generate(repo, bazel, output_base, patches): + inputs = json.loads((repo / ".graph-inputs.json").read_text()) + graal = Path(inputs["graal"]) + sources = {Path(path): Path(source) for path, source in inputs["sources"].items()} + peer_flags = [ + arg + for suite, path in inputs["peers"].items() + for arg in ("--peer", f"{suite}={path}") + ] + with tempfile.TemporaryDirectory(dir=repo) as work: work = Path(work) generated = work / "generated" subprocess.run( [ROOT / "tools/generate-graal", graal, "--output", generated, *peer_flags], check=True, cwd=ROOT, + env={ + **os.environ, + "RULES_MX_GRAPH_BAZEL": bazel, + "RULES_MX_GRAPH_OUTPUT_BASE": output_base, + }, ) check_input_pins(generated) - repo = work / "repository" - repo.mkdir() - for patch in fixes: - for path in changed_paths(patch): + for patch in patches: + paths = changed_paths(patch) + for path in paths: + if path not in sources: + raise SystemExit(f"{patch.name} requires {path} in {graal}") target = repo / path if not target.exists(): target.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(sources[path], target) - apply_patch(repo, patch) + if paths: + apply_patch(repo, patch) for patch in sorted(generated.glob("*.patch")): apply_patch(repo, patch) root_files = { Path(name) - for name in ("BUILD", "BUILD.bazel", "REPO.bazel", "mx-source.json") + for name in ( + "BUILD", + "BUILD.bazel", + "MODULE.bazel", + "REPO.bazel", + "WORKSPACE", + "WORKSPACE.bazel", + "mx-source.json", + ) } for path, source in sources.items(): target = repo / path if not target.exists() and path not in root_files: target.parent.mkdir(parents=True, exist_ok=True) target.symlink_to(source) - (repo / "REPO.bazel").write_text( - "# Local overlay generated by tools/graal-dev.\n" - ) + (repo / "REPO.bazel").write_text("# Local overlay generated by rules_mx.\n") (repo / "BUILD.bazel").write_text('exports_files(["mx-source.json"])\n') (repo / "mx-source.json").write_text( json.dumps(provenance(graal), indent=2) + "\n" ) - destination = state / (key + "-" + work.name) - repo.rename(destination) - pointer = work / "current" - pointer.symlink_to(destination, target_is_directory=True) - pointer.replace(current) - return destination def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument( - "--workspace", - type=Path, - default=ROOT.parent, - help="directory containing graal and optional graaljs and graalpython peers", - ) - parser.add_argument( - "--state-dir", - type=Path, - default=ROOT / ".graal-dev", - help="directory for generated local repositories", - ) - parser.add_argument( - "--sync", - action="store_true", - help="regenerate BUILD files for edits to imports or source discovery", - ) - parser.add_argument( - "--buildbuddy", - action="store_true", - help="invoke the BuildBuddy wrapper instead of Bazelisk", - ) - parser.add_argument( - "command", choices=["build", "test", "run", "query", "cquery", "aquery"] - ) - parser.add_argument("arguments", nargs=argparse.REMAINDER) - opts = parser.parse_args() - repo = create_repository( - opts.workspace.resolve(), opts.state_dir.resolve(), opts.sync - ) - use_buildbuddy = opts.buildbuddy and opts.command != "query" - bazel = str(ROOT / "tools/buildbuddy") if use_buildbuddy else shutil.which("bazelisk") - if not bazel: - parser.error("Bazelisk is required") - os.chdir(ROOT) - os.execv( - bazel, - [ - bazel, - opts.command, - "--override_repository=graal=" + str(repo), - *opts.arguments, - ], - ) + command, location, *arguments = sys.argv[1:] + if command == "scan": + scan(Path(location), [Path(path) for path in arguments]) + else: + bazel, output_base, *patches = arguments + generate(Path(location), bazel, output_base, [Path(path) for path in patches]) if __name__ == "__main__":