@rightkit/ci 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -19,8 +19,8 @@ jobs:
19
19
  run: |
20
20
  echo "::error::right-git: repository is private; managed public-only workflows must not run here."
21
21
  exit 1
22
- swift-check:
23
- needs: [private-repo-guard]
22
+ ${CHECK_JOB} swift-check:
23
+ needs: [private-repo-guard, check]
24
24
  runs-on: ${SWIFT_CHECK_RUNNER}
25
25
  timeout-minutes: 45
26
26
  env:
@@ -1,168 +0,0 @@
1
- import test from "node:test";
2
- import assert from "node:assert/strict";
3
- import fs from "node:fs";
4
- import os from "node:os";
5
- import path from "node:path";
6
- import crypto from "node:crypto";
7
- import { fetchArtifacts, parseFetchArgs, treeDigest, globToRegExp, artifactsCommand, RECEIPT_SCHEMA } from "./artifacts.mjs";
8
-
9
- const sha = (text) => crypto.createHash("sha256").update(text).digest("hex");
10
-
11
- function fakeGh(runs) {
12
- const calls = [];
13
- const execFile = async (cmd, args) => {
14
- calls.push([cmd, ...args]);
15
- if (cmd === "gh") {
16
- if (args[0] === "api" && !/\/zip$/.test(args[1])) return { stdout: JSON.stringify([{ artifacts: runs.artifacts }]) };
17
- assert.equal(args[0], "api");
18
- const id = Number(/artifacts\/(\d+)\/zip$/.exec(args[1])[1]);
19
- const artifact = (runs.replacement?.[id] ?? runs.artifacts.find((entry) => entry.id === id));
20
- const name = artifact.name;
21
- if (runs.fail?.includes(name)) throw new Error("boom\nsecond line");
22
- return { stdout: Buffer.from(JSON.stringify(runs.files[name] ?? {})) };
23
- }
24
- const zip = args.find((arg) => arg.endsWith(".zip") || args.includes("-xf") && arg === args[args.indexOf("-xf") + 1]);
25
- const dir = args[args.indexOf("-d") + 1] ?? args[args.indexOf("-C") + 1];
26
- for (const [rel, text] of Object.entries(JSON.parse(fs.readFileSync(zip, "utf8")))) {
27
- fs.mkdirSync(path.dirname(path.join(dir, rel)), { recursive: true });
28
- fs.writeFileSync(path.join(dir, rel), text);
29
- }
30
- return { stdout: "" };
31
- };
32
- return { execFile, calls };
33
- }
34
-
35
- const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), "right-git-artifacts-"));
36
- const RUN = {
37
- artifacts: [{ id: 1, name: "swiftright-render-abc" }, { id: 2, name: "results-mac" }, { id: 3, name: "results-win" }],
38
- files: {
39
- "swiftright-render-abc": { "render.dll": "dll-bytes" },
40
- "results-mac": { "results-mac.jsonl": "mac\n", "shared.txt": "same" },
41
- "results-win": { "results-win.jsonl": "win\n", "shared.txt": "same", "sub/a.txt": "a" },
42
- },
43
- };
44
-
45
- test("parseFetchArgs requires a run id and an output dir and rejects unsafe values", () => {
46
- assert.deepEqual(parseFetchArgs(["--run", "12", "--out", "o", "--name", "results-*", "--expect-sha256", "A".repeat(64), "--file", "render.dll"]), { run: "12", out: "o", name: "results-*", expectSha256: "a".repeat(64), file: "render.dll" });
47
- for (const argv of [[], ["--run", "x", "--out", "o"], ["--run", "1"], ["--run", "1", "--out", "o", "--name", "a b"], ["--run", "1", "--out", "o", "--expect-sha256", "abc"], ["--run", "1", "--out", "o", "--file", "x"], ["--run", "1", "--out", "o", "--expect-sha256", "a".repeat(64), "--file", "../x"], ["--run", "1", "--out", "o", "--repo", "bad"], ["--run", "1", "--out", "o", "--wat"]]) {
48
- assert.throws(() => parseFetchArgs(argv), (error) => error.code === "ARTIFACTS_USAGE", JSON.stringify(argv));
49
- }
50
- });
51
-
52
- test("globToRegExp supports * and ? and anchors the match", () => {
53
- assert.ok(globToRegExp("results-*").test("results-mac"));
54
- assert.ok(!globToRegExp("results-*").test("xresults-mac"));
55
- assert.ok(globToRegExp("a?c.txt").test("abc.txt"));
56
- assert.ok(!globToRegExp("a?c.txt").test("abcxtxt"));
57
- });
58
-
59
- test("fetch merges per-job artifacts into one tree and writes a receipt with the tree digest", async () => {
60
- const out = path.join(tmp(), "run");
61
- const receiptPath = path.join(tmp(), "receipt.json");
62
- const { execFile, calls } = fakeGh(RUN);
63
- const receipt = await fetchArtifacts({ run: "99", out, name: "results-*", repo: "Orthic-Labs/swiftright", receipt: receiptPath }, { execFile });
64
- assert.equal(receipt.schema, RECEIPT_SCHEMA);
65
- assert.deepEqual(receipt.artifacts.map((artifact) => artifact.name), ["results-mac", "results-win"]);
66
- assert.equal(receipt.fileCount, 4);
67
- assert.equal(fs.readFileSync(path.join(out, "sub", "a.txt"), "utf8"), "a");
68
- assert.equal(fs.readFileSync(path.join(out, "shared.txt"), "utf8"), "same");
69
- const expected = treeDigest([{ path: "shared.txt", sha256: sha("same") }, { path: "results-mac.jsonl", sha256: sha("mac\n") }, { path: "results-win.jsonl", sha256: sha("win\n") }, { path: "sub/a.txt", sha256: sha("a") }]);
70
- assert.equal(receipt.treeSha256, expected);
71
- assert.equal(JSON.parse(fs.readFileSync(receiptPath, "utf8")).treeSha256, expected);
72
- assert.equal(receipt.verified, false);
73
- assert.ok(calls.some((call) => call[0] === "gh" && call[2] === "repos/Orthic-Labs/swiftright/actions/artifacts/2/zip"));
74
- assert.ok(calls.every((call) => !call.includes("--name")), "downloads go by artifact id, never by name");
75
- assert.deepEqual(receipt.artifacts.map((artifact) => artifact.id), [2, 3]);
76
- assert.ok(receipt.artifacts.every((artifact) => /^[0-9a-f]{64}$/.test(artifact.zipSha256)));
77
- assert.deepEqual(fs.readdirSync(path.dirname(out)).filter((entry) => entry.includes(".fetch-")), []);
78
- });
79
-
80
- test("a per-file pin passes when it matches and the receipt records it", async () => {
81
- const out = path.join(tmp(), "pair");
82
- const { execFile } = fakeGh(RUN);
83
- const receipt = await fetchArtifacts({ run: "99", out, name: "swiftright-render-*", expectSha256: sha("dll-bytes"), file: "render.dll" }, { execFile });
84
- assert.equal(receipt.verified, true);
85
- assert.deepEqual(receipt.pin, { subject: "render.dll", expected: sha("dll-bytes"), actual: sha("dll-bytes") });
86
- assert.equal(fs.readFileSync(path.join(out, "render.dll"), "utf8"), "dll-bytes");
87
- });
88
-
89
- test("a pin mismatch fails, leaves the output untouched and removes staging", async () => {
90
- const root = tmp();
91
- const out = path.join(root, "pair");
92
- const { execFile } = fakeGh(RUN);
93
- await assert.rejects(fetchArtifacts({ run: "99", out, name: "swiftright-render-*", expectSha256: "0".repeat(64), file: "render.dll" }, { execFile }), (error) => error.code === "ARTIFACTS_PIN_MISMATCH");
94
- assert.equal(fs.existsSync(out), false);
95
- assert.deepEqual(fs.readdirSync(root), []);
96
- await assert.rejects(fetchArtifacts({ run: "99", out, name: "swiftright-render-*", expectSha256: "0".repeat(64), file: "missing.dll" }, { execFile }), (error) => error.code === "ARTIFACTS_PIN_FILE");
97
- });
98
-
99
- test("the tree pin verifies the whole merged tree", async () => {
100
- const out = path.join(tmp(), "tree");
101
- const { execFile } = fakeGh(RUN);
102
- const digest = treeDigest([{ path: "render.dll", sha256: sha("dll-bytes") }]);
103
- const receipt = await fetchArtifacts({ run: "99", out, name: "swiftright-render-*", expectSha256: digest }, { execFile });
104
- assert.deepEqual(receipt.pin, { subject: "tree", expected: digest, actual: digest });
105
- });
106
-
107
- test("conflicting files across artifacts, no match, expired, failed download and unsafe names are refused", async () => {
108
- const conflict = { artifacts: RUN.artifacts, files: { ...RUN.files, "results-win": { ...RUN.files["results-win"], "shared.txt": "different" } } };
109
- await assert.rejects(fetchArtifacts({ run: "1", out: path.join(tmp(), "o"), name: "results-*" }, fakeGh(conflict)), (error) => error.code === "ARTIFACTS_CONFLICT");
110
- await assert.rejects(fetchArtifacts({ run: "1", out: path.join(tmp(), "o"), name: "nothing-*" }, fakeGh(RUN)), (error) => error.code === "ARTIFACTS_NONE");
111
- await assert.rejects(fetchArtifacts({ run: "1", out: path.join(tmp(), "o") }, fakeGh({ ...RUN, artifacts: [{ id: 1, name: "old", expired: true }] })), (error) => error.code === "ARTIFACTS_EXPIRED");
112
- await assert.rejects(fetchArtifacts({ run: "1", out: path.join(tmp(), "o"), name: "results-mac" }, fakeGh({ ...RUN, fail: ["results-mac"] })), (error) => error.code === "ARTIFACTS_DOWNLOAD" && !/second line/.test(error.message));
113
- await assert.rejects(fetchArtifacts({ run: "1", out: path.join(tmp(), "o") }, fakeGh({ ...RUN, artifacts: [{ id: 1, name: "../evil" }] })), (error) => error.code === "ARTIFACTS_NAME");
114
- const listing = { execFile: async () => { throw new Error("no auth"); } };
115
- await assert.rejects(fetchArtifacts({ run: "1", out: path.join(tmp(), "o") }, listing), (error) => error.code === "ARTIFACTS_LIST");
116
- });
117
-
118
- test("artifactsCommand prints a summary or JSON and returns exit codes", async () => {
119
- const lines = [];
120
- const io = { log: (line) => lines.push(line), error: (line) => lines.push(`E ${line}`) };
121
- const out = path.join(tmp(), "cmd");
122
- assert.equal(await artifactsCommand(["fetch", "--run", "5", "--out", out, "--name", "swiftright-render-*", "--json"], fakeGh(RUN), io), 0);
123
- assert.equal(JSON.parse(lines[0]).run, "5");
124
- assert.equal(await artifactsCommand(["fetch", "--run", "5"], fakeGh(RUN), io), 2);
125
- assert.equal(await artifactsCommand(["bogus"], fakeGh(RUN), io), 2);
126
- assert.equal(await artifactsCommand(["fetch", "--run", "5", "--out", path.join(tmp(), "x"), "--name", "none-*"], fakeGh(RUN), io), 1);
127
- assert.match(lines.at(-1), /ARTIFACTS_NONE/);
128
- });
129
-
130
- test("a destination symlink (directory or file) is refused and nothing outside the output root is written", async () => {
131
- const root = tmp();
132
- const outside = path.join(root, "outside");
133
- fs.mkdirSync(outside);
134
- const out = path.join(root, "out");
135
- fs.mkdirSync(out);
136
- fs.symlinkSync(outside, path.join(out, "sub"));
137
- const { execFile } = fakeGh(RUN);
138
- await assert.rejects(fetchArtifacts({ run: "9", out, name: "results-win" }, { execFile }), (error) => error.code === "ARTIFACTS_DEST_SYMLINK");
139
- assert.deepEqual(fs.readdirSync(outside), []);
140
- fs.rmSync(path.join(out, "sub"));
141
- const victim = path.join(root, "victim.txt");
142
- fs.writeFileSync(victim, "keep");
143
- fs.symlinkSync(victim, path.join(out, "results-win.jsonl"));
144
- await assert.rejects(fetchArtifacts({ run: "9", out, name: "results-win" }, { execFile }), (error) => error.code === "ARTIFACTS_DEST_SYMLINK");
145
- assert.equal(fs.readFileSync(victim, "utf8"), "keep");
146
- const linkedOut = path.join(root, "linked");
147
- fs.symlinkSync(outside, linkedOut);
148
- await assert.rejects(fetchArtifacts({ run: "9", out: linkedOut, name: "results-win" }, { execFile }), (error) => error.code === "ARTIFACTS_DEST_SYMLINK");
149
- assert.deepEqual(fs.readdirSync(outside), []);
150
- });
151
-
152
- test("downloads use the listed artifact id: a same-name replacement cannot change what the receipt names", async () => {
153
- const out = path.join(tmp(), "ids");
154
- const gh = fakeGh({ ...RUN, replacement: {}, });
155
- const receipt = await fetchArtifacts({ run: "9", out, name: "swiftright-render-*" }, gh);
156
- assert.deepEqual(receipt.artifacts.map((artifact) => artifact.id), [1]);
157
- await assert.rejects(fetchArtifacts({ run: "9", out: path.join(tmp(), "n"), name: "results-mac" }, fakeGh({ ...RUN, artifacts: [{ name: "results-mac" }] })), (error) => error.code === "ARTIFACTS_ID");
158
- });
159
-
160
- test("a receipt path that collides with a fetched file is refused before anything is written", async () => {
161
- const root = tmp();
162
- const out = path.join(root, "out");
163
- const { execFile } = fakeGh(RUN);
164
- await assert.rejects(fetchArtifacts({ run: "9", out, name: "swiftright-render-*", expectSha256: sha("dll-bytes"), file: "render.dll", receipt: path.join(out, "render.dll") }, { execFile }), (error) => error.code === "ARTIFACTS_RECEIPT_COLLISION");
165
- assert.equal(fs.existsSync(out), false);
166
- const receipt = await fetchArtifacts({ run: "9", out, name: "swiftright-render-*", receipt: path.join(out, "receipt.json") }, { execFile });
167
- assert.equal(receipt.fileCount, 1);
168
- });
package/checkout.test.mjs DELETED
@@ -1,92 +0,0 @@
1
- import test from "node:test";
2
- import assert from "node:assert/strict";
3
- import fs from "node:fs";
4
- import os from "node:os";
5
- import path from "node:path";
6
- import { renderLanes } from "./sync.mjs";
7
- import { applyCheckoutOptions } from "./checkout.mjs";
8
- import { KNOWN_LANES } from "./manifest.mjs";
9
-
10
- const BASE = {
11
- schemaVersion: 1,
12
- compile: "github-actions-only",
13
- lanes: [...KNOWN_LANES],
14
- swift: { check: { runner: "macos-15", xcodeVersion: "16.4", projectDirectory: "ios", spec: "project.yml", project: "Widgets.xcodeproj", scheme: "Widgets", xcodegenVersion: "2.44.1" } },
15
- matrix: { os: ["ubuntu-latest", "macos-latest", "windows-latest"], node: ["22.13", "24"] },
16
- packageManager: "pnpm@11.24.0",
17
- publish: {
18
- npm: { oidc: true, provenance: true },
19
- homebrew: { tap: "acme/homebrew-tap", formulaName: "widgets" },
20
- winget: { packageIdentifier: "Acme.Widgets" },
21
- },
22
- regenerate: { script: "regenerate" },
23
- templateVersion: "1.0.0",
24
- };
25
- const NODE_LANES = ["ci", "qualification", "package-smoke", "publish-npm", "publish-package-managers", "regenerate"];
26
-
27
- function repo() {
28
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), "rg-checkout-"));
29
- fs.writeFileSync(path.join(dir, "package.json"), JSON.stringify({ name: "widgets" }));
30
- return dir;
31
- }
32
-
33
- test("checkout unset, empty or longPaths:false leaves every lane byte-identical", () => {
34
- const r = repo();
35
- const base = { ...BASE, lanes: NODE_LANES };
36
- const plain = renderLanes(base, r);
37
- assert.deepEqual(renderLanes({ ...base, checkout: {} }, r), plain);
38
- assert.deepEqual(renderLanes({ ...base, checkout: { longPaths: false } }, r), plain);
39
- });
40
-
41
- test("checkout.longPaths puts a Windows-gated system core.longpaths step before every checkout", () => {
42
- const manifest = { ...BASE, lanes: NODE_LANES, checkout: { longPaths: true } };
43
- for (const { content } of renderLanes(manifest, repo())) {
44
- const lines = content.split("\n");
45
- let seen = 0;
46
- lines.forEach((line, i) => {
47
- if (!/uses: actions\/checkout@/.test(line)) return;
48
- seen += 1;
49
- const header = /- uses:/.test(line) ? i : i - 1;
50
- assert.equal(lines[header - 1].trim(), "run: git config --system core.longpaths true");
51
- assert.equal(lines[header - 3].trim(), "if: runner.os == 'Windows'");
52
- assert.equal(lines[header - 4].trim(), "- name: Enable Windows long paths");
53
- });
54
- assert.equal((content.match(/Enable Windows long paths/g) ?? []).length, seen);
55
- }
56
- });
57
-
58
- test("checkout.sparse merges into with: and leaves other-repository checkouts alone", () => {
59
- const manifest = { ...BASE, lanes: ["ci", "publish-package-managers"], checkout: { sparse: ["packages/", "examples/App"] } };
60
- const [ci, pm] = renderLanes(manifest, repo()).map((r) => r.content);
61
- assert.match(ci, /sparse-checkout: \|\n\s+packages\/\n\s+examples\/App\n\s+sparse-checkout-cone-mode: true/);
62
- assert.doesNotMatch(ci, /core\.longpaths/);
63
- const tap = pm.split("- name: Checkout Homebrew tap")[1].split(" - run:")[0];
64
- assert.doesNotMatch(tap, /sparse-checkout/);
65
- assert.match(pm, /sparse-checkout: \|/);
66
- });
67
-
68
- test("rust-hybrid ci renders both options deterministically", () => {
69
- const manifest = { ...BASE, lanes: ["ci"], profile: "rust-hybrid", gate: { path: "scripts/gate.sh" }, templateVersion: "1.1.0", checkout: { longPaths: true, sparse: ["packages"] } };
70
- const r = repo();
71
- const a = renderLanes(manifest, r)[0].content;
72
- assert.equal(renderLanes(manifest, r)[0].content, a);
73
- assert.match(a, /Enable Windows long paths/);
74
- assert.match(a, /sparse-checkout: \|\n\s+packages\n/);
75
- });
76
-
77
- test("applyCheckoutOptions adds with: when the step has none", () => {
78
- const out = applyCheckoutOptions("jobs:\n a:\n steps:\n - uses: actions/checkout@v5\n - run: x\n", { checkout: { sparse: ["a"] } });
79
- assert.equal(out, "jobs:\n a:\n steps:\n - uses: actions/checkout@v5\n with:\n sparse-checkout: |\n a\n sparse-checkout-cone-mode: true\n - run: x\n");
80
- });
81
-
82
- test("defaultBranch renders into push triggers; unset stays main", () => {
83
- const r = repo();
84
- const base = { ...BASE, lanes: ["ci", "qualification", "package-smoke"] };
85
- for (const { content } of renderLanes(base, r)) assert.match(content, /branches: \[main\]/);
86
- for (const { content } of renderLanes({ ...base, defaultBranch: "master" }, r)) {
87
- assert.match(content, /branches: \[master\]/);
88
- assert.doesNotMatch(content, /branches: \[main\]/);
89
- }
90
- const rh = { ...BASE, lanes: ["ci"], profile: "rust-hybrid", gate: { path: "scripts/gate.sh" }, templateVersion: "1.1.0", defaultBranch: "master" };
91
- assert.match(renderLanes(rh, r)[0].content, /branches: \[master\]/);
92
- });
package/cli.test.mjs DELETED
@@ -1,68 +0,0 @@
1
- // CLI-level regression coverage for right-git.mjs. cli/right-git.mjs is a
2
- // true entrypoint (it dispatches on process.argv at module-load time), not a
3
- // library module, so its argument parsing can only be exercised honestly by
4
- // spawning it as a real subprocess with real argv — the same way the QA
5
- // report reproduced F7.
6
-
7
- import test from "node:test";
8
- import assert from "node:assert/strict";
9
- import fs from "node:fs";
10
- import os from "node:os";
11
- import path from "node:path";
12
- import { fileURLToPath } from "node:url";
13
- import { spawnSync } from "node:child_process";
14
- import { SAMPLE_MANIFEST } from "./test-support.mjs";
15
-
16
- const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)));
17
- const cliPath = path.join(packageRoot, "cli", "right-git.mjs");
18
-
19
- function runCli(args, cwd) {
20
- return spawnSync(process.execPath, [cliPath, ...args], { cwd, encoding: "utf8" });
21
- }
22
-
23
- // F7 regression: `right-git drift --all <root>` is the documented syntax
24
- // (see printHelp: "drift --all [workspace-root]"). The old parseFlags
25
- // treated `--all` like any other "--flag value" pair, so it consumed the
26
- // root path as --all's *value* instead of leaving it positional; runDrift
27
- // then fell back to `path.resolve(positional[0] || ".")`, silently scanning
28
- // the current working directory instead of the supplied root. Only the
29
- // undocumented `--all=true <root>` form worked. Prove the fix by running the
30
- // CLI from a cwd that has no managed repos, with the real fixture root
31
- // passed as a plain trailing argument, and asserting the fixture repo is the
32
- // one actually discovered.
33
- test("F7: `right-git drift --all <root>` (space-separated) scopes the scan to the given root, not process.cwd()", () => {
34
- const fixtureRoot = fs.mkdtempSync(path.join(os.tmpdir(), "right-git-cli-root-"));
35
- const repoDir = path.join(fixtureRoot, "managed-repo");
36
- fs.mkdirSync(repoDir, { recursive: true });
37
- fs.writeFileSync(path.join(repoDir, ".rightgit.json"), `${JSON.stringify(SAMPLE_MANIFEST, null, 2)}\n`, "utf8");
38
- fs.writeFileSync(path.join(repoDir, "package.json"), JSON.stringify({ name: "widgets" }), "utf8");
39
-
40
- // Deliberately not fixtureRoot and carries no managed repo of its own —
41
- // if the bug is present, the CLI scans this directory instead and the
42
- // fixture repo is never mentioned in the output.
43
- const emptyCwd = fs.mkdtempSync(path.join(os.tmpdir(), "right-git-cli-cwd-"));
44
-
45
- const result = runCli(["drift", "--all", fixtureRoot], emptyCwd);
46
-
47
- const output = `${result.stdout}${result.stderr}`;
48
- assert.ok(
49
- output.includes(repoDir),
50
- `expected 'drift --all ${fixtureRoot}' (run from an unrelated cwd) to discover ${repoDir}; got stdout=${JSON.stringify(result.stdout)} stderr=${JSON.stringify(result.stderr)}`,
51
- );
52
- });
53
-
54
- // Non-regression: the workaround documented by the QA report, `--all=true`
55
- // followed by the root, must keep working exactly as before.
56
- test("`right-git drift --all=true <root>` still scopes the scan to the given root", () => {
57
- const fixtureRoot = fs.mkdtempSync(path.join(os.tmpdir(), "right-git-cli-root-eq-"));
58
- const repoDir = path.join(fixtureRoot, "managed-repo");
59
- fs.mkdirSync(repoDir, { recursive: true });
60
- fs.writeFileSync(path.join(repoDir, ".rightgit.json"), `${JSON.stringify(SAMPLE_MANIFEST, null, 2)}\n`, "utf8");
61
- fs.writeFileSync(path.join(repoDir, "package.json"), JSON.stringify({ name: "widgets" }), "utf8");
62
-
63
- const emptyCwd = fs.mkdtempSync(path.join(os.tmpdir(), "right-git-cli-cwd-eq-"));
64
- const result = runCli(["drift", `--all=true`, fixtureRoot], emptyCwd);
65
-
66
- const output = `${result.stdout}${result.stderr}`;
67
- assert.ok(output.includes(repoDir), `expected discovery of ${repoDir}; got stdout=${JSON.stringify(result.stdout)} stderr=${JSON.stringify(result.stderr)}`);
68
- });
package/drift.test.mjs DELETED
@@ -1,203 +0,0 @@
1
- import test from "node:test";
2
- import assert from "node:assert/strict";
3
- import fs from "node:fs";
4
- import os from "node:os";
5
- import path from "node:path";
6
- import { syncCommand } from "./sync.mjs";
7
- import { driftCommand, findManagedRepos } from "./drift.mjs";
8
- import { makeTempRepo, PUBLIC_DEPS, PRIVATE_DEPS, SAMPLE_MANIFEST } from "./test-support.mjs";
9
-
10
- test("drift reports no drift right after a clean sync", async () => {
11
- const dir = makeTempRepo(SAMPLE_MANIFEST);
12
- await syncCommand(dir, { deps: PUBLIC_DEPS });
13
- const result = await driftCommand(dir, PUBLIC_DEPS);
14
- assert.equal(result.ok, true);
15
- assert.equal(result.driftDetected, false);
16
- assert.ok(result.findings.every((f) => f.status === "match"));
17
- });
18
-
19
- test("drift detects a hand-mutated managed file", async () => {
20
- const dir = makeTempRepo(SAMPLE_MANIFEST);
21
- await syncCommand(dir, { deps: PUBLIC_DEPS });
22
- const ciPath = path.join(dir, ".github", "workflows", "ci.yml");
23
- fs.appendFileSync(ciPath, "\n# hand edit\n");
24
-
25
- const result = await driftCommand(dir, PUBLIC_DEPS);
26
- assert.equal(result.ok, true);
27
- assert.equal(result.driftDetected, true);
28
- const ciFinding = result.findings.find((f) => f.filename === "ci.yml");
29
- assert.equal(ciFinding.status, "mismatch");
30
- });
31
-
32
- test("drift flags driftDetected when a lane's file is missing", async () => {
33
- const dir = makeTempRepo(SAMPLE_MANIFEST);
34
- await syncCommand(dir, { deps: PUBLIC_DEPS });
35
- fs.rmSync(path.join(dir, ".github", "workflows", "ci.yml"));
36
-
37
- const result = await driftCommand(dir, PUBLIC_DEPS);
38
- assert.equal(result.driftDetected, true);
39
- assert.ok(result.findings.some((f) => f.filename === "ci.yml" && f.status === "missing"));
40
- });
41
-
42
- test("drift flags a public->private visibility flip even with no file drift", async () => {
43
- const dir = makeTempRepo(SAMPLE_MANIFEST);
44
- await syncCommand(dir, { deps: PUBLIC_DEPS });
45
- const result = await driftCommand(dir, PRIVATE_DEPS);
46
- assert.equal(result.driftDetected, true);
47
- assert.equal(result.visibility.allowed, false);
48
- });
49
-
50
- test("findManagedRepos finds every directory carrying a .rightgit.json under a root", () => {
51
- const root = fs.mkdtempSync(path.join(os.tmpdir(), "right-git-root-"));
52
- const repoA = makeTempRepo(SAMPLE_MANIFEST);
53
- const repoB = makeTempRepo(SAMPLE_MANIFEST);
54
- fs.cpSync(repoA, path.join(root, "repo-a"), { recursive: true });
55
- fs.cpSync(repoB, path.join(root, "repo-b"), { recursive: true });
56
- fs.mkdirSync(path.join(root, "not-managed"));
57
-
58
- const found = findManagedRepos(root).map((p) => path.basename(p)).sort();
59
- assert.deepEqual(found, ["repo-a", "repo-b"]);
60
- });
61
-
62
- // F7 regression: a repo whose .rightgit.json was deleted (or never
63
- // committed) but whose .github/workflows/ still carries MANAGED_MARKER
64
- // files is an "orphan" — right-git put those workflows there, but the
65
- // manifest-only scan in the old findManagedRepos could never see it, so
66
- // `drift --all` silently skipped exactly the repos most likely to be
67
- // drifted (missing manifest is itself drift).
68
- test("findManagedRepos finds an orphan repo: managed workflow files present, .rightgit.json missing", () => {
69
- const root = fs.mkdtempSync(path.join(os.tmpdir(), "right-git-orphan-root-"));
70
- const dir = makeTempRepo(SAMPLE_MANIFEST);
71
- fs.cpSync(dir, path.join(root, "orphan-repo"), { recursive: true });
72
-
73
- const orphanDir = path.join(root, "orphan-repo");
74
- // A synced install would leave workflow files; simulate that state
75
- // directly, then remove the manifest to reproduce "manifest lost, workflow
76
- // files remain".
77
- fs.mkdirSync(path.join(orphanDir, ".github", "workflows"), { recursive: true });
78
- fs.writeFileSync(
79
- path.join(orphanDir, ".github", "workflows", "ci.yml"),
80
- "# Managed by right-git — do not hand-edit. Run `right-git sync` to update.\nname: ci\n",
81
- "utf8",
82
- );
83
- fs.rmSync(path.join(orphanDir, ".rightgit.json"));
84
-
85
- const found = findManagedRepos(root).map((p) => path.basename(p)).sort();
86
- assert.deepEqual(found, ["orphan-repo"]);
87
- });
88
-
89
- test("driftCommand reports an orphan repo as drift instead of a hard failure", async () => {
90
- const dir = makeTempRepo(SAMPLE_MANIFEST);
91
- await syncCommand(dir, { deps: PUBLIC_DEPS });
92
- fs.rmSync(path.join(dir, ".rightgit.json"));
93
-
94
- const result = await driftCommand(dir, PUBLIC_DEPS);
95
- assert.equal(result.ok, true);
96
- assert.equal(result.driftDetected, true);
97
- assert.ok(result.findings.some((f) => f.status === "orphan" && f.filename === "ci.yml"));
98
- });
99
-
100
- // Regenerate approval check (drift warns; it is advisory and never changes driftDetected).
101
- // The stub answers the visibility lookup, `git remote get-url origin`, and `gh api`; any other
102
- // command throws, so a test cannot reach the real gh or network.
103
- const REGENERATE_MANIFEST = { ...SAMPLE_MANIFEST, lanes: ["ci", "regenerate"], regenerate: { script: "regenerate" } };
104
- const PERMISSIONS_PATH = "repos/acme/widgets/actions/permissions/workflow";
105
-
106
- function workflowSettingsDeps({ approve = true, origin = "git@github.com:acme/widgets.git", gitFails = false, apiError = null, apiStdout = null } = {}) {
107
- const deps = {
108
- calls: [],
109
- execFile: async (cmd, args) => {
110
- deps.calls.push([cmd, ...args].join(" "));
111
- if (cmd === "gh" && args[0] === "repo") return { stdout: JSON.stringify({ visibility: "PUBLIC" }) };
112
- if (cmd === "git" && args[0] === "remote") {
113
- if (gitFails) throw new Error("fatal: No such remote 'origin'");
114
- return { stdout: `${origin}\n` };
115
- }
116
- if (cmd === "gh" && args[0] === "api") {
117
- if (apiError) throw apiError;
118
- return { stdout: apiStdout ?? JSON.stringify({ default_workflow_permissions: "read", can_approve_pull_request_reviews: approve }) };
119
- }
120
- throw new Error(`unexpected exec: ${cmd}`);
121
- },
122
- };
123
- return deps;
124
- }
125
-
126
- test("drift warns when the regenerate lane's pull-request setting is off, without reporting drift", async () => {
127
- const dir = makeTempRepo(REGENERATE_MANIFEST);
128
- await syncCommand(dir, { deps: PUBLIC_DEPS });
129
- const deps = workflowSettingsDeps({ approve: false });
130
- const result = await driftCommand(dir, deps);
131
- assert.equal(result.ok, true);
132
- assert.equal(result.driftDetected, false);
133
- assert.equal(result.warnings.length, 1);
134
- assert.match(result.warnings[0], /Allow GitHub Actions to create and approve pull requests/);
135
- assert.deepEqual(result.notes, []);
136
- assert.ok(deps.calls.includes(`gh api ${PERMISSIONS_PATH}`), `expected gh api call; got ${deps.calls.join(" | ")}`);
137
- });
138
-
139
- test("drift is silent when the regenerate lane's pull-request setting is on", async () => {
140
- const dir = makeTempRepo(REGENERATE_MANIFEST);
141
- await syncCommand(dir, { deps: PUBLIC_DEPS });
142
- const result = await driftCommand(dir, workflowSettingsDeps({ approve: true }));
143
- assert.equal(result.driftDetected, false);
144
- assert.deepEqual(result.warnings, []);
145
- assert.deepEqual(result.notes, []);
146
- });
147
-
148
- test("drift skips the approval check with a note when gh is not installed", async () => {
149
- const dir = makeTempRepo(REGENERATE_MANIFEST);
150
- await syncCommand(dir, { deps: PUBLIC_DEPS });
151
- const missing = Object.assign(new Error("spawn gh ENOENT"), { code: "ENOENT" });
152
- const result = await driftCommand(dir, workflowSettingsDeps({ apiError: missing }));
153
- assert.equal(result.driftDetected, false);
154
- assert.deepEqual(result.warnings, []);
155
- assert.equal(result.notes.length, 1);
156
- assert.match(result.notes[0], /skipped the Actions pull-request approval check \(gh is not installed\)/);
157
- });
158
-
159
- test("drift notes an unreadable or incomplete permissions response instead of guessing", async () => {
160
- const dir = makeTempRepo(REGENERATE_MANIFEST);
161
- await syncCommand(dir, { deps: PUBLIC_DEPS });
162
- const notJson = await driftCommand(dir, workflowSettingsDeps({ apiStdout: "<html>403</html>" }));
163
- assert.deepEqual(notJson.warnings, []);
164
- assert.match(notJson.notes[0], /gh api returned no JSON/);
165
-
166
- const incomplete = await driftCommand(dir, workflowSettingsDeps({ apiStdout: JSON.stringify({ default_workflow_permissions: "read" }) }));
167
- assert.deepEqual(incomplete.warnings, []);
168
- assert.match(incomplete.notes[0], /no can_approve_pull_request_reviews/);
169
-
170
- const forbidden = await driftCommand(dir, workflowSettingsDeps({ apiError: new Error("HTTP 403: Resource not accessible") }));
171
- assert.deepEqual(forbidden.warnings, []);
172
- assert.match(forbidden.notes[0], /gh api failed: HTTP 403/);
173
- });
174
-
175
- test("drift skips the approval check for a non-GitHub origin and never calls gh api", async () => {
176
- const dir = makeTempRepo(REGENERATE_MANIFEST);
177
- await syncCommand(dir, { deps: PUBLIC_DEPS });
178
- const deps = workflowSettingsDeps({ origin: "https://gitlab.com/acme/widgets.git" });
179
- const result = await driftCommand(dir, deps);
180
- assert.deepEqual(result.warnings, []);
181
- assert.match(result.notes[0], /origin is not a github\.com repository/);
182
- assert.equal(deps.calls.some((call) => call.startsWith("gh api")), false);
183
- });
184
-
185
- test("drift notes a missing origin remote and does not guess the repository", async () => {
186
- const dir = makeTempRepo(REGENERATE_MANIFEST);
187
- await syncCommand(dir, { deps: PUBLIC_DEPS });
188
- const deps = workflowSettingsDeps({ gitFails: true });
189
- const result = await driftCommand(dir, deps);
190
- assert.deepEqual(result.warnings, []);
191
- assert.match(result.notes[0], /no origin remote/);
192
- assert.equal(deps.calls.some((call) => call.startsWith("gh api")), false);
193
- });
194
-
195
- test("drift never asks Actions settings for a manifest without the regenerate lane", async () => {
196
- const dir = makeTempRepo(SAMPLE_MANIFEST);
197
- await syncCommand(dir, { deps: PUBLIC_DEPS });
198
- const deps = workflowSettingsDeps({ approve: false });
199
- const result = await driftCommand(dir, deps);
200
- assert.deepEqual(result.warnings, []);
201
- assert.deepEqual(result.notes, []);
202
- assert.equal(deps.calls.some((call) => call.startsWith("gh api")), false);
203
- });