diff --git a/.gitignore b/.gitignore index d74ddb8a..250bdc41 100644 --- a/.gitignore +++ b/.gitignore @@ -268,6 +268,9 @@ notebooks/ local-jars/ .runtime-cache/ +# scripts/dev_overlay.py: the checkout's Python sources over a borrowed wheel, and the wheels downloaded for it +.dev-overlay/ + # test databases my_test_databases/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index db3d3bf5..5806273e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -38,13 +38,44 @@ Add a dependency (a Python extra, or anything bundled in a wheel) only when it i ### Prepare your environment -You need [uv](https://docs.astral.sh/uv/), Git, and Python 3.11 to 3.14. This repository is a package definition, not a uv project (`pyproject.toml` sets `managed = false`), so there is no environment to sync. You build a wheel, and `uv run --no-project --with ` makes a throwaway environment from it. Nothing is installed into your system Python. +You need [uv](https://docs.astral.sh/uv/), Git, and Python 3.11 to 3.14. This repository is a package definition, not a uv project (`pyproject.toml` sets `managed = false`), so there is no environment to sync. You build a wheel (or, for a change to Python files only, [borrow one](#change-python-code-without-building-a-wheel)), and `uv run --no-project --with ` makes a throwaway environment from it. Nothing is installed into your system Python. ```shell git clone git@github.com:ArcadeData/arcadedb-python.git cd arcadedb-python ``` +### Change Python code without building a wheel + +A change that touches only Python files (`src/arcadedb`, `tests`) needs no build. `scripts/dev_overlay.py` puts the Python sources of your checkout over a wheel that is already built, and runs a command against the result. The jars, the JRE, the native library and the generated files stay the wheel's. For the native wheel the script applies the rewrite of the wheel build (`nativize_sources` in `native/wheel/build_wheel.py`), so the Python text is what a built wheel would hold. + +Take a wheel that CI built from `main`. You need the [GitHub CLI](https://cli.github.com/), signed in. The artifact of `arcadedb-jvm` is `wheel-` (`linux-amd64`, `linux-arm64`, `darwin-arm64`, `windows-amd64`; kept 7 days) from `test-jvm.yml`, and the artifact of `arcadedb` is `native-wheel-` (`linux-x86_64`, `linux-aarch64`, `macos-arm64`, `windows-x64`; kept 30 days) from `test-native.yml`. + +```shell +gh run list -R ArcadeData/arcadedb-python --workflow test-jvm.yml --branch main --limit 5 +gh run download -R ArcadeData/arcadedb-python --name wheel-linux-amd64 --dir .dev-overlay/wheels +W="$(ls .dev-overlay/wheels/arcadedb_jvm-*.whl | head -1)" +uv run --no-project --with "$W[test]" python scripts/dev_overlay.py -m pytest tests/test_core.py -v +``` + +The native wheel has no `test` extra, so name what the test file needs: + +```shell +gh run list -R ArcadeData/arcadedb-python --workflow test-native.yml --branch main --limit 5 +gh run download -R ArcadeData/arcadedb-python --name native-wheel-linux-x86_64 --dir .dev-overlay/wheels +W="$(ls .dev-overlay/wheels/arcadedb-*.whl | head -1)" +uv run --no-project --with "$W" --with pytest --with numpy python scripts/dev_overlay.py -m pytest tests/test_core.py -v +``` + +Everything after the script name runs as `python ` with the overlay first on `PYTHONPATH`, and the overlay is made again on every run, so your next edit is picked up. A released wheel works too (`--with "arcadedb-jvm[test]=="`), as long as nothing the wheel is built from changed since the release; the script checks that and lists the files that changed. + +When the shortcut is valid: + +- Valid: a change to Python files only. +- Not valid: a change in `src/java` (the bridge jar), a change under `native/` (the C entry points, the native library, the wheel build), and a change that needs a newer engine than the wheel carries. Build the wheel for these. +- When the script prints a warning, the wheel is older than the files it is built from. The import or a test can then fail for a reason that is not in your change. Take a newer wheel. +- CI does not use the overlay. Every pull request still builds both wheels and runs the tests against them, so a green overlay run does not replace the checks. + ### Build and test `arcadedb-jvm` On Linux the build runs in Docker. On macOS and Windows it needs a JDK 25 or later. The jars come from the `arcadedata/arcadedb` Docker image. diff --git a/native/wheel/build_wheel.py b/native/wheel/build_wheel.py index 8f55c2b5..63c8033c 100644 --- a/native/wheel/build_wheel.py +++ b/native/wheel/build_wheel.py @@ -101,6 +101,66 @@ def platform_tag(lib: Path, policy: str) -> str: sys.exit(f"unsupported platform {sys.platform}") +def nativize_sources(dst: Path) -> None: + """Rewrite a copy of src/arcadedb at ``dst`` in place into the Python sources of the native wheel. + + The install hints name the extras of ``arcadedb``, ``import jpype`` becomes the bundled stub, the default backend is native, + and ``__init__.py`` imports the names of ``_build_info.py`` (the caller writes that file and adds the libraries). + ``scripts/dev_overlay.py`` calls it too, so a contributor's overlay holds the same Python text as a built wheel. + """ + jp = re.compile( + r"^(\s*)(?:import jpype(?:\.imports)?|import jpype as _jpype|import jpype\.types as jtypes|from jpype import JException)\s*$", + re.M, + ) + left = [] + for f in dst.rglob("*.py"): + t = f.read_text(encoding="utf-8") + t = t.replace( + "'arcadedb-jvm[", "'arcadedb[" + ) # the extras named in install hints + + def sub(m): + line = m.group(0).strip() + ind = m.group(1) + if line == "import jpype.imports": + return f"{ind}pass # jpype.imports: no JVM in this wheel" + tail = { + "import jpype as _jpype": "_jpype", + "import jpype.types as jtypes": "jtypes", + }.get(line, "jpype") + if line == "from jpype import JException": + return f"{ind}from arcadedb._jpype_stub import JException" + return f"{ind}from arcadedb import _jpype_stub as {tail}" + + t = jp.sub(sub, t) + if re.search(r"^\s*(import|from)\s+jpype", t, re.M): + left.append(f.name) + f.write_text(t, encoding="utf-8") + if left: + sys.exit(f"jpype imports left in: {left}") + init = dst / "_native" / "__init__.py" + t = init.read_text(encoding="utf-8") + assert t.count('_DEFAULT_BACKEND = "jpype"') == 1, "default-backend line not found" + init.write_text( + t.replace('_DEFAULT_BACKEND = "jpype"', '_DEFAULT_BACKEND = "native"'), + encoding="utf-8", + ) + shutil.copy(HERE / "_jpype_stub.py", dst / "_jpype_stub.py") + ip = dst / "__init__.py" + t = ip.read_text(encoding="utf-8") + t = t.replace( + "# Import async execution\n", + "from ._build_info import ENGINE_IMAGE_DIGEST, ENGINE_SNAPSHOT, ENGINE_VERSION, NATIVE_IMAGE, NATIVE_MARCH, SOURCE_COMMIT # noqa: F401\n\n# Import async execution\n", + 1, + ) + t = t.replace( + '__all__ = [\n "__version__",', + '__all__ = [\n "__version__",\n "ENGINE_VERSION",\n "NATIVE_IMAGE",\n "SOURCE_COMMIT",', + 1, + ) + ip.write_text(t, encoding="utf-8") + + def main(): ap = argparse.ArgumentParser() ap.add_argument( @@ -217,44 +277,7 @@ def main(): ), ) - jp = re.compile( - r"^(\s*)(?:import jpype(?:\.imports)?|import jpype as _jpype|import jpype\.types as jtypes|from jpype import JException)\s*$", - re.M, - ) - left = [] - for f in dst.rglob("*.py"): - t = f.read_text(encoding="utf-8") - t = t.replace( - "'arcadedb-jvm[", "'arcadedb[" - ) # the extras named in install hints - - def sub(m): - line = m.group(0).strip() - ind = m.group(1) - if line == "import jpype.imports": - return f"{ind}pass # jpype.imports: no JVM in this wheel" - tail = { - "import jpype as _jpype": "_jpype", - "import jpype.types as jtypes": "jtypes", - }.get(line, "jpype") - if line == "from jpype import JException": - return f"{ind}from arcadedb._jpype_stub import JException" - return f"{ind}from arcadedb import _jpype_stub as {tail}" - - t = jp.sub(sub, t) - if re.search(r"^\s*(import|from)\s+jpype", t, re.M): - left.append(f.name) - f.write_text(t, encoding="utf-8") - if left: - sys.exit(f"jpype imports left in: {left}") - init = dst / "_native" / "__init__.py" - t = init.read_text(encoding="utf-8") - assert t.count('_DEFAULT_BACKEND = "jpype"') == 1, "default-backend line not found" - init.write_text( - t.replace('_DEFAULT_BACKEND = "jpype"', '_DEFAULT_BACKEND = "native"'), - encoding="utf-8", - ) - shutil.copy(HERE / "_jpype_stub.py", dst / "_jpype_stub.py") + nativize_sources(dst) commit = subprocess.run( ["git", "-C", str(REPO), "rev-parse", "HEAD"], capture_output=True, text=True @@ -269,19 +292,6 @@ def sub(m): f'SOURCE_COMMIT = "{commit}" # ArcadeData/arcadedb-python commit of the bindings and the Java glue\n', encoding="utf-8", ) - ip = dst / "__init__.py" - t = ip.read_text(encoding="utf-8") - t = t.replace( - "# Import async execution\n", - "from ._build_info import ENGINE_IMAGE_DIGEST, ENGINE_SNAPSHOT, ENGINE_VERSION, NATIVE_IMAGE, NATIVE_MARCH, SOURCE_COMMIT # noqa: F401\n\n# Import async execution\n", - 1, - ) - t = t.replace( - '__all__ = [\n "__version__",', - '__all__ = [\n "__version__",\n "ENGINE_VERSION",\n "NATIVE_IMAGE",\n "SOURCE_COMMIT",', - 1, - ) - ip.write_text(t, encoding="utf-8") ship = libraries_to_ship(sys.platform, host_arch(), libname) for n in ship: diff --git a/scripts/dev_overlay.py b/scripts/dev_overlay.py new file mode 100644 index 00000000..bd96c04e --- /dev/null +++ b/scripts/dev_overlay.py @@ -0,0 +1,195 @@ +#!/usr/bin/env python3 +"""Put the Python sources of this checkout over an installed wheel, so a Python-only change runs without building a wheel. + +Run it in an environment that holds ONE of the two wheels; `uv run --with` makes such an environment: + + uv run --no-project --with "[test]" python scripts/dev_overlay.py -m pytest tests/test_core.py + uv run --no-project --with "" --with pytest python scripts/dev_overlay.py -m pytest tests/test_core.py + uv run --no-project --with "arcadedb-jvm[test]==" python scripts/dev_overlay.py my_script.py + uv run --no-project --with "arcadedb==" python scripts/dev_overlay.py # make the overlay, print how to use it + +The overlay is `.dev-overlay//arcadedb` (`ARCADEDB_DEV_OVERLAY_DIR` names another directory): every `.py` file of +`src/arcadedb` of this checkout, and links to what only the wheel has (the jars and the JRE of `arcadedb-jvm`, the libraries of +`arcadedb`, the generated `_version.py` or `_build_info.py`). For the native wheel the sources go through `nativize_sources` of +`native/wheel/build_wheel.py`, the rewrite the wheel build applies. The arguments after the script name run as +`python ` with the overlay first on `PYTHONPATH`. The overlay is made again on every run, so an edit is picked up. + +Valid for a change to Python files only. The rest is still the wheel's: the bridge jar (`src/java`), the native library and the +generated files (`native/`), and the engine. When it can tell, the script lists the files of that side that changed since the +wheel was built. CI builds the real wheels and tests those; this is the quick loop before a push. +""" + +import json +import os +import re +import shutil +import subprocess # nosec B404 - git and the interpreter of this environment, fixed argument lists +import sys +from importlib import metadata +from pathlib import Path +from urllib.parse import unquote, urlparse + +REPO = Path(__file__).resolve().parent.parent +SRC = REPO / "src" / "arcadedb" +# what a wheel is built from besides src/arcadedb (the binary side and the generated files): a change there needs a new wheel +BUILT_FROM = {"arcadedb-jvm": ["src/java"], "arcadedb": ["native"]} + + +def installed_distribution() -> metadata.Distribution: + """The one installed distribution of the two; exits when none or both are installed.""" + found = [] + for name in BUILT_FROM: + try: + found.append(metadata.distribution(name)) + except metadata.PackageNotFoundError: + pass + if len(found) != 1: + sys.exit( + f"dev_overlay: {len(found)} of the distributions arcadedb and arcadedb-jvm are installed here; it needs exactly one. " + 'Run it as: uv run --no-project --with ">" python scripts/dev_overlay.py' + ) + return found[0] + + +def wheel_file(dist: metadata.Distribution) -> str | None: + """The wheel file a distribution was installed from, or None when it came from an index.""" + text = dist.read_text("direct_url.json") + url = json.loads(text).get("url", "") if text else "" + if not url.startswith("file:"): + return None + path = unquote(urlparse(url).path) + # file:///C:/x.whl parses to /C:/x.whl + return path[1:] if os.name == "nt" and path[2:3] == ":" else path + + +def link(src: Path, dst: Path) -> None: + """A link to a file or directory of the wheel; a copy where links are not allowed (Windows without developer mode).""" + try: + os.symlink(src, dst, target_is_directory=src.is_dir()) + except OSError: + if src.is_dir(): + shutil.copytree(src, dst) + else: + shutil.copy2(src, dst) + + +def build(dist: metadata.Distribution) -> Path: + """Make the overlay of the installed distribution again and return its directory (the one that goes on PYTHONPATH).""" + name = dist.metadata["Name"] + wheel_pkg = Path(str(dist.locate_file("arcadedb"))).resolve() + if not (wheel_pkg / "__init__.py").is_file(): + sys.exit(f"dev_overlay: no arcadedb package at {wheel_pkg}") + base = Path(os.environ.get("ARCADEDB_DEV_OVERLAY_DIR") or REPO / ".dev-overlay") + root = base / name + pkg = root / "arcadedb" + if root.exists(): + shutil.rmtree(root) + # 1. the sources of this checkout (not the generated _version.py of a local build: the wheel's own is linked below) + shutil.copytree( + SRC, + pkg, + ignore=shutil.ignore_patterns( + "__pycache__", "*.pyc", "_version.py", "jars", "jre" + ), + ) + if name == "arcadedb": + sys.path.insert(0, str(REPO / "native" / "wheel")) + from build_wheel import nativize_sources + + nativize_sources(pkg) + # 2. everything only the wheel has, in the same place + for src in sorted(wheel_pkg.rglob("*")): + rel = src.relative_to(wheel_pkg) + dst = pkg / rel + if "__pycache__" in rel.parts or src.suffix == ".pyc": + continue + if dst.exists() or not dst.parent.is_dir() or dst.parent.is_symlink(): + continue # a source of the checkout, or inside a directory that is already a link + link(src, dst) + return root + + +def git(*args: str) -> str | None: + try: + r = subprocess.run( # nosec B603 B607 - fixed argument list + ["git", "-C", str(REPO), *args], capture_output=True, text=True + ) + except OSError: + return None + return r.stdout.strip() if r.returncode == 0 else None + + +def built_from(dist: metadata.Distribution, root: Path) -> str | None: + """The commit the wheel was built from: recorded in a native wheel, the release tag for a wheel from an index.""" + info = root / "arcadedb" / "_build_info.py" + if info.is_file(): + m = re.search( + r'^SOURCE_COMMIT = "([0-9a-f]{40})"', info.read_text(encoding="utf-8"), re.M + ) + if m: + return m.group(1) + if wheel_file(dist) is None: + return dist.version # a release tag is the bare version + return None + + +def report_changes(dist: metadata.Distribution, root: Path) -> None: + """Say whether the files the wheel is built from, other than src/arcadedb, changed since it was built.""" + paths = BUILT_FROM[dist.metadata["Name"]] + ref = built_from(dist, root) + if ref is None: + print( + f"dev_overlay: this wheel does not record the commit it was built from. The overlay is valid only if " + f"{', '.join(paths)} did not change since." + ) + return + short = ref[:12] if len(ref) == 40 else ref # a commit, or a release tag + changed = git("diff", "--name-only", ref, "--", *paths) + if changed is None: + print( + f"dev_overlay: git cannot compare this checkout with {short}, which built the wheel (fetch the commits and tags). " + f"The overlay is valid only if {', '.join(paths)} did not change since." + ) + elif changed: + print( + f"dev_overlay: WARNING: these files changed since the wheel was built ({short}), and the wheel does not have the " + "change. If the import or a test fails here, take a wheel that CI built from main:" + ) + for line in changed.splitlines(): + print(f" {line}") + else: + print( + f"dev_overlay: {', '.join(paths)} did not change since the wheel was built ({short})." + ) + + +def main() -> int: + dist = installed_distribution() + name = dist.metadata["Name"] + root = build(dist) + n = sum(1 for _ in SRC.rglob("*.py")) + print( + f"dev_overlay: {name} {dist.version}: {n} Python files of src/arcadedb over the wheel, in {root}" + ) + report_changes(dist, root) + args = sys.argv[1:] + if args: + env = dict(os.environ) + env["PYTHONPATH"] = os.pathsep.join( + p for p in (str(root), env.get("PYTHONPATH")) if p + ) + sys.stdout.flush() # the lines above come before the output of the command + return subprocess.call([sys.executable, *args], env=env) # nosec B603 + wheel = wheel_file(dist) + extra = "[test]" if name == "arcadedb-jvm" else "" + spec = f"{wheel}{extra}" if wheel else f"{name}{extra}=={dist.version}" + more = "" if extra else " --with pytest --with numpy" + print( + "Run a test file against it (the overlay is made again each time):\n" + f' uv run --no-project --with "{spec}"{more} python scripts/dev_overlay.py -m pytest tests/test_core.py' + ) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/test_dev_overlay.py b/tests/test_dev_overlay.py new file mode 100644 index 00000000..11581a19 --- /dev/null +++ b/tests/test_dev_overlay.py @@ -0,0 +1,56 @@ +"""scripts/dev_overlay.py: the Python sources of the checkout run over the installed wheel. + +It is the shortcut of CONTRIBUTING.md ("Change Python code without building a wheel"). The test runs it against the wheel +under test, whichever of the two packages that is, so each CI leg shows that the overlay imports on its platform. +""" + +import json +import os +import subprocess # nosec B404 - runs this interpreter with a fixed argument list +import sys +from importlib import metadata +from pathlib import Path + +import arcadedb +from arcadedb._dist_conflict import DISTRIBUTIONS + +REPO = Path(__file__).resolve().parent.parent +SCRIPT = REPO / "scripts" / "dev_overlay.py" +CODE = ( + "import arcadedb, json; " + "print('RESULT ' + json.dumps([arcadedb.__file__, arcadedb.__backend__, arcadedb.__version__]))" +) + + +def test_overlay_imports_the_checkout_sources_over_the_installed_wheel(tmp_path): + distribution = DISTRIBUTIONS[arcadedb._native.distribution_backend()] + env = dict(os.environ, ARCADEDB_DEV_OVERLAY_DIR=str(tmp_path)) + run = subprocess.run( # nosec B603 - fixed argv, no shell + [sys.executable, str(SCRIPT), "-c", CODE], + capture_output=True, + text=True, + env=env, + check=False, + ) + assert run.returncode == 0, run.stdout + run.stderr + results = [ln for ln in run.stdout.splitlines() if ln.startswith("RESULT ")] + assert len(results) == 1, run.stdout + run.stderr + file, backend, version = json.loads(results[0][len("RESULT ") :]) + + overlay = tmp_path / distribution / "arcadedb" + # the package that was imported is the overlay, not the wheel in site-packages + assert Path(file).resolve() == (overlay / "__init__.py").resolve() + # ... of the same build, with the version of the wheel it borrows the binaries from + assert backend == ("native" if distribution == "arcadedb" else "jvm") + assert version == metadata.version(distribution) + # every source file of the checkout is there, as a file of its own (a link would be the wheel's) + sources = sorted( + p.relative_to(REPO / "src" / "arcadedb") + for p in (REPO / "src" / "arcadedb").rglob("*.py") + if "__pycache__" not in p.parts and p.name != "_version.py" + ) + assert sources, "no sources found in the checkout" + for rel in sources: + assert (overlay / rel).is_file() and not (overlay / rel).is_symlink(), rel + # the first line the script prints names the distribution and its version + assert f"dev_overlay: {distribution} {version}:" in run.stdout