Cotton code
170 lines · 8.2 KB · TypeScriptRaw
import { readFileSync, readdirSync, existsSync } from "node:fs";import { join } from "node:path";import { describe, expect, it } from "vitest";/** * The `checks` CI job runs `turbo typecheck lint build` and `turbo test` on * the Linux CI box, which has NO cargo, NO Swift and NO Xcode — Rust runs only * in the `rust` job (Linux), the Mac app only in the `swift` job and the phone * only in the `ios` job, both on the build Mac. A package script named `build`, * `test`, `lint` or `typecheck` that invokes one is therefore a red `checks` job * on every PR (#392 measured it for cargo: a local turbo run was a cache hit, so * it looked green until CI executed the task). * * Swift is the sharper case, because it fails BOTH ways: on the Linux runner the * toolchain is missing, and on the Mac an unlocked `swift build`/`xcodebuild` * beside an iOS archive is what the machine-wide build lock exists to prevent. * All of them belong behind names turbo never schedules (`build:rust`, * `conformance`, `gen:ffi`, `app:build`, `ios:test`). * * `apps/cotton` used to have a second, stronger defence — no `package.json` at * all, so it was not a pnpm workspace member and turbo could not see it — and * that is gone: since H2 it IS a member, for the Mac's icon scripts. The case * below ("Since H2 …") is what replaced it, sweeping that manifest's own scripts * for the same tools. This header said the opposite for months, which is the * kind of stale WHY that makes a reader trust a defence that is not there. */const ROOT = join(__dirname, "..", "..");/** * Every task name `turbo.json` declares — read from the file rather than * listed here, because a task added there and forgotten here is exactly the * one a package could hang a Mac-only tool on. `turbo.json` is JSONC (it * carries comments), so the names are read with a regex rather than a parser. */function turboTasks(): string[] {  const config = readFileSync(join(ROOT, "turbo.json"), "utf8");  expect(config.length, "turbo.json is empty — did it move?").toBeGreaterThan(0);  const tasks = config.slice(config.indexOf('"tasks"'));  const names = [...tasks.matchAll(/^ {4}"([A-Za-z][\w:-]*)": \{/gm)].map((hit) => hit[1]);  expect(names.length, "no task names found in turbo.json").toBeGreaterThan(3);  return names;}/** Every tool that lives only on the build Mac. */const MAC_ONLY = /\bcargo\b|\bxcodebuild\b|\bxcodegen\b|\bswift (build|test)\b/;/** The toolchains the `checks` runner does not have. */const OFF_RUNNER = /\b(cargo|swift build|swift test|swift run|xcodebuild|codesign)\b/;function packageDirs(): string[] {  const out: string[] = [];  for (const group of ["apps", "packages"]) {    const base = join(ROOT, group);    if (!existsSync(base)) continue;    for (const name of readdirSync(base)) {      if (existsSync(join(base, name, "package.json"))) out.push(join(group, name));    }  }  return out;}describe("cargo and swift never run under a turbo task", () => {  it("no package's build/test/lint/typecheck script invokes cargo, swift or xcodebuild", () => {    const offenders: string[] = [];    for (const dir of packageDirs()) {      const pkg = JSON.parse(readFileSync(join(ROOT, dir, "package.json"), "utf8")) as {        scripts?: Record<string, string>;      };      for (const task of turboTasks()) {        const script = pkg.scripts?.[task];        if (script && OFF_RUNNER.test(script)) offenders.push(`${dir}: "${task}": ${script}`);      }    }    expect(      offenders,      "move the call behind a name turbo does not schedule — the `checks` runner has neither toolchain",    ).toEqual([]);  });  it("the header generator stays behind gen:ffi, which turbo does not schedule", () => {    // The scripts moved to the ROOT manifest in step 5i: the Cargo workspace is    // not inside a pnpm package any more, so there is no `crates/package.json`.    const pkg = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8")) as {      scripts: Record<string, string>;    };    expect(pkg.scripts["gen:ffi"]).toMatch(/cargo test .*-p cotton-ffi/);    expect(pkg.scripts["gen:ffi:check"]).toMatch(/cargo test .*-p cotton-ffi/);  });  it("no package's build/test/lint/typecheck script invokes xcodebuild, xcodegen or swift", () => {    const offenders: string[] = [];    for (const dir of packageDirs()) {      const pkg = JSON.parse(readFileSync(join(ROOT, dir, "package.json"), "utf8")) as {        scripts?: Record<string, string>;      };      for (const task of turboTasks()) {        const script = pkg.scripts?.[task];        if (script && MAC_ONLY.test(script)) offenders.push(`${dir}: "${task}": ${script}`);      }    }    expect(      offenders,      "these tools live on ONE machine — move the call behind a name turbo does not schedule",    ).toEqual([]);  });  it("the Swift package's manifest carries only its TypeScript island — no cargo, no swift", () => {    // Since H2 `apps/cotton` IS a workspace member: the Mac's icon scripts and    // their vitest suite came with it. So the rule above applies to it like    // any other package, and this is the direct check — every script it    // declares is TypeScript tooling, and none of them is a compile.    expect(existsSync(join(ROOT, "apps", "cotton", "Package.swift"))).toBe(true);    const manifest = JSON.parse(readFileSync(join(ROOT, "apps", "cotton", "package.json"), "utf8")) as {      scripts?: Record<string, string>;    };    for (const [name, script] of Object.entries(manifest.scripts ?? {})) {      expect(script, `apps/cotton package.json script "${name}" must not build Swift or Rust`).not.toMatch(        /\b(cargo|swift|xcodebuild|xcodegen)\b/,      );    }  });  it("the phone's build and generate scripts live at the repo root, behind ios: names", () => {    const pkg = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8")) as {      scripts: Record<string, string>;    };    // Root scripts are not turbo tasks — `pnpm test` is `turbo test`, which    // schedules PACKAGE tasks. The `ios:` prefix says so out loud.    const tasks = turboTasks();    // A root script reaches a Mac-only tool DIRECTLY, or through the shell    // script it calls — `pnpm ios:test` is `bash scripts/ios-test.sh`, and a    // check that read only the script line would pass on any name at all.    for (const [name, script] of Object.entries(pkg.scripts)) {      const called = [...script.matchAll(/scripts\/[\w.-]+\.(?:sh|ts)/g)].map((hit) => hit[0]);      const reach = [        script,        ...called.map((path) => {          const full = join(ROOT, path);          return existsSync(full) ? readFileSync(full, "utf8") : "";        }),      ].join("\n");      if (!MAC_ONLY.test(reach)) continue;      expect(        tasks.includes(name),        `root script "${name}" reaches a Mac-only tool and is named like a turbo task`,      ).toBe(false);    }    // Anti-vacuity: the loop above only means something if following a root    // script into its shell script actually FINDS a Mac-only tool. This is the    // script it must find one in.    expect(MAC_ONLY.test(readFileSync(join(ROOT, "scripts", "ios-test.sh"), "utf8"))).toBe(true);    expect(pkg.scripts["ios:project"]).toContain("gen-ios-project.sh");    expect(pkg.scripts["ios:test"]).toContain("ios-test.sh");    // Where the Mac-only tools actually are: shell scripts the root calls by    // name, never a package script turbo could schedule.    expect(readFileSync(join(ROOT, "scripts", "ios-test.sh"), "utf8")).toMatch(/xcodebuild/);    expect(readFileSync(join(ROOT, "scripts", "gen-ios-project.sh"), "utf8")).toMatch(/xcodegen/);    // Both take the machine-wide build lock, or two heavy builds swap-crash a    // 16 GB Mac. `gen-ios-project.sh` compiles nothing and says why it does not.    expect(readFileSync(join(ROOT, "scripts", "ios-test.sh"), "utf8")).toMatch(      /with-build-lock\.sh/,    );  });  it("the cargo build stays behind rust:build, which turbo does not schedule", () => {    const pkg = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8")) as {      scripts: Record<string, string>;    };    expect(pkg.scripts["rust:build"]).toMatch(/cargo build/);    expect(pkg.scripts.build).toBeUndefined();  });});