import { execFileSync, spawnSync } from "node:child_process"; import { chmodSync, existsSync, mkdtempSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { beforeEach, describe, expect, it } from "vitest"; import { requires } from "./requires"; const REPO_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "../.."); const SCRIPT = join(REPO_ROOT, "scripts", "build-android-core.sh"); const APP_JNI_LIBS = join(REPO_ROOT, "apps", "cotton-android", "app", "src", "main", "jniLibs"); type Run = { status: number; stdout: string; stderr: string; calls: string[] }; let sandbox: string; let cargoLog: string; let targetDir: string; let jniLibsDir: string; beforeEach(() => { sandbox = mkdtempSync(join(tmpdir(), "android-core-build-")); cargoLog = join(sandbox, "cargo.log"); targetDir = join(sandbox, "target"); jniLibsDir = join(sandbox, "jniLibs"); mkdirSync(join(sandbox, "ndk")); mkdirSync(join(sandbox, "home")); writeFileSync(cargoLog, ""); const cargo = join(sandbox, "cargo"); writeFileSync( cargo, `#!/bin/sh set -eu printf '%s\\n' "\${CARGO_BUILD_JOBS-unset}" >> "$CARGO_LOG.jobs" printf '%s' "$PWD" >> "$CARGO_LOG" for argument in "$@"; do printf '|%s' "$argument" >> "$CARGO_LOG"; done printf '\\n' >> "$CARGO_LOG" if [ "$1" = ndk ]; then abi="" output="" shift while [ "$#" -gt 0 ]; do case "$1" in -t) abi="$2"; shift 2 ;; -o) output="$2"; shift 2 ;; *) shift ;; esac done mkdir -p "$output/$abi" : > "$output/$abi/libcotton_android_jni.so" elif [ "$1" = metadata ]; then printf '{"target_directory":"%s"}\\n' "\${CARGO_TARGET_DIR:-$CARGO_METADATA_TARGET_DIR}" else profile=debug for argument in "$@"; do [ "$argument" = --release ] && profile=release; done output_target="\${CARGO_TARGET_DIR:-$CARGO_METADATA_TARGET_DIR}" mkdir -p "$output_target/$profile" : > "$output_target/$profile/libcotton_android_jni.so" fi `, ); chmodSync(cargo, 0o755); // A `uname` THAT SAYS LINUX, because the script's first gate is // `[ "$(uname -s)" = "Linux" ]` and every case below is about what it does // AFTER that gate. Without this, seven of these tests asserted nothing on a // Mac: they all got "Android core builds are supported on Linux only" and the // failures read as bugs in the script. The Darwin case overwrites this file // with its own stub, which is what makes the refusal test real on Linux too. // Every other flag is delegated to the real `uname`, so `-m` still answers // this machine. const real = execFileSync("bash", ["-lc", "command -v uname"], { encoding: "utf8" }).trim(); writeFileSync( join(sandbox, "uname"), `#!/bin/sh\nif [ "$1" = "-s" ] || [ $# -eq 0 ]; then echo Linux; exit 0; fi\nexec ${real} "$@"\n`, ); chmodSync(join(sandbox, "uname"), 0o755); }); function run(args: string[], extraEnv: Record = {}): Run { const env: NodeJS.ProcessEnv = { ...process.env, PATH: `${sandbox}:${process.env.PATH ?? ""}`, HOME: join(sandbox, "home"), ANDROID_NDK_HOME: join(sandbox, "ndk"), CARGO_LOG: cargoLog, CARGO_TARGET_DIR: targetDir, CARGO_METADATA_TARGET_DIR: targetDir, COTTON_ANDROID_JNI_LIBS_DIR: jniLibsDir, BUILD_LOCK_DIR: join(sandbox, "lock"), BUILD_LOCK_LOG: join(sandbox, "lock.log"), ...extraEnv, }; for (const [key, value] of Object.entries(env)) { if (value === undefined) delete env[key]; } const done = spawnSync("/bin/bash", [SCRIPT, ...args], { cwd: REPO_ROOT, encoding: "utf8", env, }); return { status: done.status ?? -1, stdout: done.stdout ?? "", stderr: done.stderr ?? "", calls: readFileSync(cargoLog, "utf8") .trim() .split("\n") .filter((line) => line.length > 0 && !line.includes("|metadata|")), }; } describe("build-android-core.sh", () => { // Why: on 29 Sep 2026 the review found `export CARGO_BUILD_JOBS=6` here and in // setup-android.sh, run INSIDE `build-slot.sh run` — so the slot's share of the host // (min(asked, cores / (busy + 1))) was overwritten with six for the whole four-ABI // build, whatever else was running. Six is the ceiling and the default; a smaller value stands. it("keeps a smaller CARGO_BUILD_JOBS — the build slot's share — and is six at most and by default", () => { const jobs = () => readFileSync(`${cargoLog}.jobs`, "utf8").trim().split("\n"); const shared = run([], { CARGO_BUILD_JOBS: "3" }); expect(shared.status, shared.stderr).toBe(0); expect(new Set(jobs())).toEqual(new Set(["3"])); writeFileSync(`${cargoLog}.jobs`, ""); const alone = run([], { CARGO_BUILD_JOBS: undefined }); expect(alone.status, alone.stderr).toBe(0); expect(new Set(jobs())).toEqual(new Set(["6"])); writeFileSync(`${cargoLog}.jobs`, ""); const greedy = run([], { CARGO_BUILD_JOBS: "99" }); expect(greedy.status, greedy.stderr).toBe(0); expect(new Set(jobs())).toEqual(new Set(["6"])); // setup-android.sh wraps this script in CI and needs a JDK and an SDK to run at // all, so its half is read: no unconditional assignment of the variable. const setup = readFileSync(join(REPO_ROOT, "scripts/ci/setup-android.sh"), "utf8"); expect(setup).not.toMatch(/^\s*(export\s+)?CARGO_BUILD_JOBS=[0-9]/m); expect(setup).toContain('android_jobs="${CARGO_BUILD_JOBS:-6}"'); expect(setup).toContain('[ "$android_jobs" -le 6 ] || android_jobs=6'); }); it("builds the four Android ABI products serially through cargo-ndk", () => { const result = run([]); expect(result.status, result.stderr).toBe(0); expect(result.calls).toEqual([ `${join(REPO_ROOT, "crates")}|ndk|-t|arm64-v8a|-P|28|-o|${jniLibsDir}|build|--locked|-p|cotton-android-jni`, `${join(REPO_ROOT, "crates")}|ndk|-t|armeabi-v7a|-P|28|-o|${jniLibsDir}|build|--locked|-p|cotton-android-jni`, `${join(REPO_ROOT, "crates")}|ndk|-t|x86|-P|28|-o|${jniLibsDir}|build|--locked|-p|cotton-android-jni`, `${join(REPO_ROOT, "crates")}|ndk|-t|x86_64|-P|28|-o|${jniLibsDir}|build|--locked|-p|cotton-android-jni`, ]); expect(result.stdout.trim().split("\n")).toEqual([ `${jniLibsDir}/arm64-v8a/libcotton_android_jni.so`, `${jniLibsDir}/armeabi-v7a/libcotton_android_jni.so`, `${jniLibsDir}/x86/libcotton_android_jni.so`, `${jniLibsDir}/x86_64/libcotton_android_jni.so`, ]); }); it("builds the JVM smoke-test library for the host without invoking cargo-ndk", () => { const result = run(["--host"]); expect(result.status, result.stderr).toBe(0); expect(result.calls).toEqual([`${join(REPO_ROOT, "crates")}|build|--locked|-p|cotton-android-jni`]); expect(result.stdout.trim()).toBe(`${targetDir}/debug/libcotton_android_jni.so`); }); it("limits a release build to its requested ABI", () => { const result = run(["--abi", "x86_64", "--release"]); expect(result.status, result.stderr).toBe(0); expect(result.calls).toEqual([ `${join(REPO_ROOT, "crates")}|ndk|-t|x86_64|-P|28|-o|${jniLibsDir}|build|--locked|-p|cotton-android-jni|--release`, ]); expect(result.stdout.trim()).toBe(`${jniLibsDir}/x86_64/libcotton_android_jni.so`); }); it("rejects an unsupported ABI before it invokes Cargo", () => { const result = run(["--abi", "mips"]); expect(result.status).toBe(2); expect(result.stderr).toContain("unsupported ABI 'mips'"); expect(result.calls).toEqual([]); }); it("refuses a non-Linux host before it invokes Cargo", () => { const uname = join(sandbox, "uname"); writeFileSync(uname, "#!/bin/sh\necho Darwin\n"); chmodSync(uname, 0o755); const result = run([]); expect(result.status).toBe(1); expect(result.stderr).toContain("supported on Linux only"); expect(result.calls).toEqual([]); }); it("rejects a configured NDK path that does not exist before it invokes Cargo", () => { const result = run([], { ANDROID_NDK_HOME: join(sandbox, "missing-ndk") }); expect(result.status).toBe(1); expect(result.stderr).toContain("ANDROID_NDK_HOME is not a directory"); expect(result.calls).toEqual([]); }); // RULE: With no CARGO_TARGET_DIR the script builds where the lock wrapper's // cargo writes — the machine's one shared target (one locked target per // machine, 2235f6b84) — unless this checkout's .cargo/config.toml names a // target-dir, which Cargo and the wrapper both honour. Before this rule the // script asked `cargo metadata` outside the wrapper and looked for the // library in a directory the build never wrote to. it("builds in the target the lock wrapper's cargo writes to when the environment names none", (ctx) => { // CI's checkout names no target-dir, and there the shared target under the // (sandboxed) HOME is the only right answer. A checkout whose generated // config names one (every worktree:new worktree and lane) leaves the answer // to that config, which names THIS MACHINE's real shared target: the lock // wrapper exports it to cargo, so the fake build would land a stray library // there and the case would judge the machine, not the script. const configured = [join(REPO_ROOT, "crates/.cargo/config.toml"), join(REPO_ROOT, ".cargo/config.toml")] .filter((p) => existsSync(p)) .some((p) => /^\s*target-dir\s*=/m.test(readFileSync(p, "utf8"))); requires(ctx, { probe: () => !configured, reason: "this checkout's .cargo/config.toml names a target-dir, the machine's real shared target" }); const expected = join(sandbox, "home/.cache/cottondb/cargo-target/shared"); const result = run(["--host"], { CARGO_TARGET_DIR: undefined, CARGO_METADATA_TARGET_DIR: join(sandbox, "configured-target"), }); expect(result.status, result.stderr).toBe(0); expect(result.stdout.trim()).toBe(`${expected}/debug/libcotton_android_jni.so`); }); it("does not let a stale Android recursion marker bypass the lock around Cargo", () => { const lockLog = join(sandbox, "lock-calls.log"); const lock = join(sandbox, "with-build-lock"); writeFileSync(lock, `#!/bin/sh printf '%s' "$1" >> "$COTTON_LOCK_LOG" first=1 for argument in "$@"; do [ "$first" = 1 ] && { first=0; continue; } printf '|%s' "$argument" >> "$COTTON_LOCK_LOG" done printf '\\n' >> "$COTTON_LOCK_LOG" exec "$@" `); chmodSync(lock, 0o755); const result = run(["--host"], { COTTON_ANDROID_CORE_LOCKED: "1", COTTON_BUILD_LOCK_SCRIPT: lock, COTTON_LOCK_LOG: lockLog, }); expect(result.status, result.stderr).toBe(0); expect(readFileSync(lockLog, "utf8").trim()).toBe("cargo|build|--locked|-p|cotton-android-jni"); }); it("keeps generated JNI products out of source control", () => { const ignore = readFileSync(join(REPO_ROOT, "apps", "cotton-android", ".gitignore"), "utf8"); expect(ignore).toContain("app/src/main/jniLibs/"); }); });