import { spawnSync } from "node:child_process"; import { chmodSync, existsSync, mkdtempSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { afterEach, describe, expect, it } from "vitest"; const ROOT = resolve(__dirname, "../.."); const SCRIPT = join(ROOT, "scripts/ci/setup-android.sh"); const roots: string[] = []; afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); }); type Options = { sdkMissing?: boolean; ndkMissing?: boolean; java?: string; javac?: string; initialNdk?: string | null; cachedNdk?: string; installedNdk?: string; install?: "success" | "failure" | "no-binary"; targetFailure?: boolean; }; function fixture(options: Options = {}) { // REALPATH, because on macOS `/var` is a symlink to `/private/var` and // `mkdtemp` hands back the unresolved spelling. The script runs a child that // prints `$PWD`, which bash reports RESOLVED — so every path assertion here // compared `/var/folders/…` against `/private/var/folders/…` and this test // could only fail on a Mac. Resolving once at the source keeps the fixture's // paths and the child's agreeing on both platforms. const root = realpathSync(mkdtempSync(join(tmpdir(), "cotton-android-ci-"))); roots.push(root); const bin = join(root, "bin"); const sdk = join(root, "sdk"); const ndk = join(sdk, "ndk/27.1.12297006"); const log = join(root, "tools.log"); const githubPath = join(root, "github-path"); const cacheBin = join(root, ".cache/cottondb/android/cargo-ndk-4.1.2/bin"); mkdirSync(bin, { recursive: true }); writeFileSync(log, ""); writeFileSync(githubPath, ""); if (!options.sdkMissing) mkdirSync(join(sdk, "platforms/android-36"), { recursive: true }); function executable(file: string, body: string) { mkdirSync(resolve(file, ".."), { recursive: true }); writeFileSync(file, `#!/bin/bash\nset -eu\n${body}\n`); chmodSync(file, 0o755); } function tool(name: string, body: string) { executable(join(bin, name), `printf '${name} %s|cwd=%s\\n' "$*" "$PWD" >> "$FIXTURE_LOG"\n${body}`); } function ndkBinary(file: string, version: string) { executable(file, `printf 'cargo-ndk-binary %s|cwd=%s\\n' "$*" "$PWD" >> "$FIXTURE_LOG"\nprintf 'cargo-ndk ${version}\\n'`); } if (!options.ndkMissing) executable(join(ndk, "toolchains/llvm/prebuilt/linux-x86_64/bin/clang"), "exit 0"); tool("uname", "echo Linux"); tool("java", `echo 'openjdk version "${options.java ?? "21.0.12.1"}"' >&2`); tool("javac", `echo 'javac ${options.javac ?? "21.0.12.1"}' >&2`); tool("rustup", options.targetFailure ? "exit 7" : "exit 0"); if (options.initialNdk !== null) ndkBinary(join(bin, "cargo-ndk"), options.initialNdk ?? "4.1.2"); if (options.cachedNdk) ndkBinary(join(cacheBin, "cargo-ndk"), options.cachedNdk); const installedBinary = join(root, "installed-cargo-ndk"); ndkBinary(installedBinary, options.installedNdk ?? "4.1.2"); tool("cargo", ` case "$1" in ndk) shift; exec cargo-ndk "$@" ;; install) [ "$FIXTURE_INSTALL" != failure ] || exit 23 [ "$FIXTURE_INSTALL" != no-binary ] || exit 0 install_root='' while [ "$#" -gt 0 ]; do if [ "$1" = --root ]; then install_root="$2"; shift; fi shift done [ -n "$install_root" ] || exit 24 mkdir -p "$install_root/bin" cp "$FIXTURE_INSTALL_BINARY" "$install_root/bin/cargo-ndk" chmod 755 "$install_root/bin/cargo-ndk" ;; *) exit 25 ;; esac`); const env: NodeJS.ProcessEnv = { ...process.env, // No real Rust binaries can satisfy this fake tool boundary. PATH: `${bin}:/usr/bin:/bin`, HOME: root, JAVA_HOME: undefined, ANDROID_HOME: sdk, ANDROID_SDK_ROOT: sdk, ANDROID_NDK_HOME: ndk, CARGO_BUILD_JOBS: "99", CARGO_HOME: undefined, RUSTUP_HOME: undefined, FIXTURE_LOG: log, FIXTURE_INSTALL: options.install ?? "success", FIXTURE_INSTALL_BINARY: installedBinary, GITHUB_PATH: githubPath, BUILD_LOCK_DIR: join(root, "build.lock"), BUILD_LOCK_LOG: join(root, "build.log"), // A scratch cargo target, not named shared: with none, the lock wrapper runs // `cargo install` under the target this checkout's .cargo/config.toml names // (a worktree's: the machine's real shared target) and its cargo lock, so an // install case waited out its deadline whenever a real build held that lock. CARGO_TARGET_DIR: join(root, "target"), }; function run(args: string[] = ["bash", "-c", "printf '%s\\n' \"$PWD\" \"$ANDROID_HOME\" \"$ANDROID_SDK_ROOT\" \"$ANDROID_NDK_HOME\" \"$CARGO_BUILD_JOBS\""], extra: NodeJS.ProcessEnv = {}) { // This is a fake installation through the real lock wrappers, not a // ten-second performance contract. Dispatched run 4970 completed cargo // but hit that deadline during wrapper cleanup under runner load. const result = spawnSync("/bin/bash", [SCRIPT, ...args], { cwd: root, env: { ...env, ...extra }, encoding: "utf8", timeout: 30_000, }); // A spawn failure is different from the child statuses these guards test. if (result.error) throw result.error; return result; } return { root, bin, sdk, ndk, cacheBin, githubPath, run, executable, log: () => readFileSync(log, "utf8") }; } describe("Android CI toolchain bootstrap", () => { it("uses the repository toolchain for every target and preserves the child's directory and SDK", () => { const f = fixture(); const result = f.run(); expect(result.status, result.stderr).toBe(0); expect(result.stdout.trim().split("\n").slice(-5)).toEqual([f.root, f.sdk, f.sdk, f.ndk, "6"]); for (const target of ["aarch64-linux-android", "armv7-linux-androideabi", "i686-linux-android", "x86_64-linux-android"]) { expect(f.log()).toContain(`rustup target add ${target}|cwd=${ROOT}/crates`); } expect(f.log()).not.toContain("cargo install"); }); it("succeeds without a child command", () => { const f = fixture(); expect(f.run([]).status).toBe(0); }); it("reuses the Linux Rust job's persistent installation when it is absent from PATH", () => { const f = fixture(); const rustRoot = join(f.root, ".cache/cottondb/rust"); const cargoHome = join(rustRoot, "cargo"); mkdirSync(join(cargoHome, "bin"), { recursive: true }); for (const name of ["cargo", "rustup"]) renameSync(join(f.bin, name), join(cargoHome, "bin", name)); const result = f.run(["bash", "-c", "printf '%s\\n' \"$CARGO_HOME\" \"$RUSTUP_HOME\""]); expect(result.status, result.stderr).toBe(0); expect(result.stdout).toContain("using the Linux CI Rust cache"); expect(result.stdout.trim().split("\n").slice(-2)).toEqual([cargoHome, join(rustRoot, "rustup")]); expect(f.log()).toContain(`rustup target add x86_64-linux-android|cwd=${ROOT}/crates`); expect(f.log()).not.toContain("cargo install"); }); it("reports a missing Rust installation before invoking the child", () => { const f = fixture(); for (const name of ["cargo", "rustup"]) rmSync(join(f.bin, name)); const result = f.run(); expect(result.status).not.toBe(0); expect(result.stderr).toContain("Rust is required on PATH or in the Linux CI Rust cache"); expect(result.stdout).not.toContain(f.sdk); }); it.each([ [{ sdkMissing: true }, "API 36"], [{ ndkMissing: true }, "NDK"], [{ java: "17.0.12" }, "JDK 21"], [{ javac: "17.0.12" }, "JDK 21"], ] satisfies Array<[Options, string]>)("refuses a missing or incompatible platform before provisioning (%j)", (options, message) => { const f = fixture(options); const result = f.run(); expect(result.status).not.toBe(0); expect(result.stderr).toContain(message); expect(f.log()).not.toContain("rustup"); expect(f.log()).not.toContain("cargo install"); }); it("refuses contradictory SDK roots", () => { const f = fixture(); const result = f.run([], { ANDROID_SDK_ROOT: join(f.root, "different-sdk") }); expect(result.status).not.toBe(0); expect(result.stderr).toContain("disagree"); expect(f.log()).not.toContain("rustup"); }); it("refuses an invalid JAVA_HOME rather than using an unrelated Java", () => { const f = fixture(); const result = f.run([], { JAVA_HOME: join(f.root, "missing-jdk") }); expect(result.status).not.toBe(0); expect(result.stderr).toContain("JAVA_HOME"); expect(f.log()).not.toContain("rustup"); }); it("honors the workflow's JDK ahead of another Java on PATH", () => { const f = fixture({ java: "17.0.12", javac: "17.0.12" }); const javaHome = join(f.root, "jdk21"); f.executable(join(javaHome, "bin/java"), "echo 'openjdk version \"21.0.8\"' >&2"); f.executable(join(javaHome, "bin/javac"), "echo javac 21.0.8 >&2"); expect(f.run([], { JAVA_HOME: javaHome }).status).toBe(0); }); it("propagates target installation failure without invoking the child", () => { const f = fixture({ targetFailure: true }); const result = f.run(); expect(result.status).toBe(7); expect(result.stdout).not.toContain(f.sdk); expect(f.log()).not.toContain("cargo install"); expect(f.log()).not.toContain("rustup target add x86_64-linux-android"); }); it("installs a missing cargo-ndk in an isolated cache and publishes that binary", () => { const f = fixture({ initialNdk: null }); const result = f.run(); expect(result.status, result.stderr).toBe(0); expect(f.log()).toContain(`cargo install --locked -j 6 --root ${resolve(f.cacheBin, "..")} cargo-ndk --version 4.1.2`); expect(existsSync(join(f.cacheBin, "cargo-ndk"))).toBe(true); expect(existsSync(join(f.root, ".cargo/bin/cargo-ndk"))).toBe(false); expect(readFileSync(f.githubPath, "utf8").trim()).toBe(f.cacheBin); }); it("uses an exact cached version without installing over a different global version", () => { const f = fixture({ initialNdk: "4.0.0", cachedNdk: "4.1.2" }); const before = readFileSync(join(f.bin, "cargo-ndk"), "utf8"); expect(f.run([]).status).toBe(0); expect(f.log()).not.toContain("cargo install"); expect(readFileSync(join(f.bin, "cargo-ndk"), "utf8")).toBe(before); expect(readFileSync(f.githubPath, "utf8").trim()).toBe(f.cacheBin); }); it("does not accept lookalike version strings as the pinned version", () => { const f = fixture({ initialNdk: "4x1x2" }); expect(f.run([]).status).toBe(0); expect(f.log()).toContain("cargo install --locked"); }); it("propagates an installation failure instead of running with the old tool", () => { const f = fixture({ initialNdk: "4.0.0", install: "failure" }); const result = f.run(); expect(result.status).toBe(23); expect(result.stdout).not.toContain(f.sdk); expect(f.log()).toContain("cargo install --locked"); }); it.each([ [{ initialNdk: null, installedNdk: "4.1.3" }, "4.1.2"], [{ initialNdk: null, install: "no-binary" }, "executable"], ] satisfies Array<[Options, string]>)("verifies the install result before running the child (%j)", (options, message) => { const f = fixture(options); const result = f.run(); expect(result.status).not.toBe(0); expect(result.stderr).toContain(message); expect(result.stdout).not.toContain(f.sdk); }); it("preserves the child exit status", () => { expect(fixture().run(["bash", "-c", "exit 47"]).status).toBe(47); }); });