Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Add change-approval PR gate

Manav Rathia46d28a35f86
diff --git a/.github/scripts/change-approval.mjs b/.github/scripts/change-approval.mjs
new file mode 100644
index 0000000000..9ced2b1a2d
--- /dev/null
+++ b/.github/scripts/change-approval.mjs
@@ -0,0 +1,199 @@
+import { execFileSync } from "node:child_process";
+import { appendFileSync, closeSync, lstatSync, openSync, readFileSync, readSync } from "node:fs";
+import path from "node:path";
+
+const [base = "origin/main"] = process.argv.slice(2);
+
+const routineBinary = (file) =>
+ /\.(png|jpe?g|webp|gif|ico|icns|ttf|otf|woff2?|riv|mp3)$/i.test(file) || file.includes("Assets.xcassets/");
+const guardrailDirs = [
+ ".github/",
+ "mobile/scripts/",
+ "rust/scripts/",
+ "web/scripts/",
+ "server/scripts/",
+ "web/packages/build-config/",
+];
+const guardrailFiles = new Set([
+ "eslint.config.mjs",
+ ".prettierrc.json",
+ "analysis_options.yaml",
+]);
+const configFile =
+ /(^|\/)(rust-toolchain\.toml|\.cargo\/(config|audit)\.toml|\.npmrc|\.nvmrc|\.tool-versions|\.node-version|\.python-version|gradle-wrapper\.properties)$/;
+
+const tomlPackages = (text) =>
+ text
+ .split("[[package]]\n")
+ .slice(1)
+ .map((block) => ({
+ name: block.match(/^name = "(.+)"$/m)[1],
+ version: block.match(/^version = "(.+)"$/m)[1],
+ source: block.match(/^source = "?(.+?)"?$/m)?.[1]?.replace(/[?#][^"]*/, ""),
+ }));
+const lockfiles = {
+ "Cargo.lock": (text) => tomlPackages(text).map((p) => ({ ...p, source: p.source ?? "workspace", local: !p.source })),
+ "uv.lock": (text) => tomlPackages(text).map((p) => ({ ...p, local: !/^\{ (registry|git|url) = /.test(p.source) })),
+ "package-lock.json": (text) =>
+ Object.entries(JSON.parse(text).packages)
+ .filter(([key]) => key.includes("node_modules/"))
+ .map(([key, { name, version, resolved, link }]) => {
+ const local = link === true || resolved?.startsWith("file:") === true;
+ return {
+ name: name ?? key.slice(key.lastIndexOf("node_modules/") + 13),
+ version,
+ source: local || !resolved ? resolved : resolved.replace(/#.*$/, "").replace(/\/-\/[^/]+\.tgz$/, ""),
+ local,
+ };
+ }),
+ "pubspec.lock": (text) =>
+ [...text.matchAll(/^ (\S+):\n((?: .*\n)+)/gm)].map(([, name, body]) => {
+ const source = [body.match(/^ source: (.+)$/m)[1], body.match(/^ url: "(.+)"$/m)?.[1]]
+ .filter(Boolean)
+ .join(" ");
+ return { name, version: body.match(/^ version: "(.+)"$/m)[1], source, local: source === "path" };
+ }),
+ "go.sum": (text) =>
+ [...text.matchAll(/^(\S+) (\S+?)(?:\/go\.mod)? h1:/gm)].map(([, name, version]) => ({ name, version })),
+ "Package.resolved": (text) =>
+ JSON.parse(text).pins.map(({ identity, location, state }) => ({
+ name: identity,
+ version: state.version,
+ source: location,
+ })),
+ "Podfile.lock": (text) => {
+ const section = (title) => text.match(new RegExp(`^${title}:\\n((?: .*\\n)+)`, "m"))?.[1] ?? "";
+ const sources = new Map();
+ for (const [, repo, pods] of section("SPEC REPOS").matchAll(/^ (\S+):\n((?: - .*\n)+)/gm)) {
+ for (const [, pod] of pods.matchAll(/^ - (.+)$/gm)) sources.set(pod, { source: repo });
+ }
+ for (const [, pod, body] of section("EXTERNAL SOURCES").matchAll(/^ (\S+):\n((?: .*\n)+)/gm)) {
+ const props = Object.fromEntries([...body.matchAll(/^ :(\w+): (.+)$/gm)].map(([, key, value]) => [key, value]));
+ const source = props.git ?? props.podspec ?? props.path;
+ sources.set(pod, { source, local: !props.git && !/^"?https?:\/\//.test(source) });
+ }
+ return [...section("PODS").matchAll(/^ - "?([^/" ]+)\S* \(([^)]+)\)/gm)].map(([, name, version]) => ({
+ name,
+ version,
+ ...sources.get(name),
+ }));
+ },
+};
+
+const opts = { encoding: "utf8", maxBuffer: 64 * 1024 * 1024 };
+const git = (...args) => execFileSync("git", args, opts);
+const list = (items) => items.map((item) => `- ${item}`).join("\n");
+const code = (file) => `\`${file}\``;
+const binary = (file) => {
+ const fd = openSync(file, "r");
+ const buffer = Buffer.alloc(8000);
+ const length = readSync(fd, buffer);
+ closeSync(fd);
+ return buffer.subarray(0, length).includes(0);
+};
+
+const { GITHUB_OUTPUT, GITHUB_STEP_SUMMARY } = process.env;
+const local = !GITHUB_OUTPUT;
+
+process.chdir(git("rev-parse", "--show-toplevel").trim());
+const mergeBase = git("merge-base", base, "HEAD").trim();
+const numstat = (...filter) =>
+ git("diff", "--numstat", "--no-renames", "-z", ...filter, mergeBase, ...(local ? [] : ["HEAD"]))
+ .split("\0")
+ .filter(Boolean)
+ .map((row) => row.split("\t"));
+const untracked = local
+ ? git("ls-files", "--others", "--exclude-standard", "-z")
+ .split("\0")
+ .filter((file) => file && !lstatSync(file).isSymbolicLink())
+ : [];
+const additions = untracked.map((file) => [binary(file) ? "-" : "0", "0", file]);
+const present = [...numstat("--diff-filter=d"), ...additions];
+const kept = numstat("--diff-filter=a").map(([, , file]) => file);
+
+const treeSizes = () =>
+ git("--literal-pathspecs", "ls-tree", "-l", "-z", "HEAD", "--", ...present.map(([, , file]) => file))
+ .split("\0")
+ .map((line) => line.match(/ blob \S+ +(\d+)\t(.*)$/))
+ .filter(Boolean)
+ .map(([, size, file]) => [file, Number(size)]);
+const diskSizes = () =>
+ present.flatMap(([, , file]) => {
+ const stat = lstatSync(file);
+ return stat.isFile() ? [[file, stat.size]] : [];
+ });
+const sizes = new Map(local ? diskSizes() : present.length ? treeSizes() : []);
+const withSize = (file) => `${code(file)} (${sizes.get(file)} bytes)`;
+
+const binaries = present
+ .filter(([added, , file]) => added === "-" && !routineBinary(file))
+ .map(([, , file]) => withSize(file));
+const large = [...numstat("--diff-filter=A"), ...additions]
+ .map(([, , file]) => file)
+ .filter((file) => sizes.get(file) > 1024 * 1024)
+ .map(withSize);
+
+const known = new Map();
+for (const file of git("ls-tree", "-r", "--name-only", "-z", mergeBase).split("\0")) {
+ const kind = path.basename(file);
+ if (!lockfiles[kind]) continue;
+ if (!known.has(kind)) known.set(kind, new Map());
+ const names = known.get(kind);
+ for (const { name, source } of lockfiles[kind](git("show", `${mergeBase}:${file}`))) {
+ if (!names.has(name)) names.set(name, new Set());
+ names.get(name).add(source);
+ }
+}
+const dependencies = present
+ .map(([, , file]) => file)
+ .filter((file) => lockfiles[path.basename(file)])
+ .flatMap((file) => {
+ const before = known.get(path.basename(file)) ?? new Map();
+ const after = lockfiles[path.basename(file)](local ? readFileSync(file, "utf8") : git("show", `HEAD:${file}`)).filter(
+ ({ local }) => !local,
+ );
+ const added = new Set(after.filter(({ name }) => !before.has(name)).map(({ name, version }) => `${name} ${version}`));
+ const moved = new Set(
+ after
+ .filter(({ name, source }) => source && before.has(name) && !before.get(name).has(source))
+ .map(({ name, source }) => `${name}: ${[...before.get(name)].join(", ")} -> ${source}`),
+ );
+ return added.size + moved.size ? [{ file, added: [...added], moved: [...moved] }] : [];
+ });
+const added = dependencies.reduce((n, { added }) => n + added.length, 0);
+const moved = dependencies.reduce((n, { moved }) => n + moved.length, 0);
+
+const guardrails = kept.filter(
+ (file) => guardrailDirs.some((dir) => file.startsWith(dir)) || guardrailFiles.has(path.basename(file)),
+);
+const configs = kept.filter((file) => configFile.test(file));
+
+const categories = [
+ ["binary file", "binary files", binaries.length],
+ ["large file", "large files", large.length],
+ ["new dependency", "new dependencies", added],
+ ["dependency source change", "dependency source changes", moved],
+ ["guardrail file", "guardrail files", guardrails.length],
+ ["config file", "config files", configs.length],
+].filter(([, , n]) => n);
+const summary = categories.map(([one, many, n]) => `${n} ${n === 1 ? one : many}`).join(", ");
+const detail = [
+ binaries.length && `## Binary files\n\n${list(binaries)}`,
+ large.length && `## Large files\n\n${list(large)}`,
+ dependencies.length &&
+ `## New dependencies\n\n${dependencies
+ .map(({ file, added, moved }) => `${code(file)}\n\n${list([...added, ...moved])}`)
+ .join("\n\n")}`,
+ guardrails.length && `## Guardrail changes\n\n${list(guardrails.map(code))}`,
+ configs.length && `## Toolchain and registry config\n\n${list(configs.map(code))}`,
+]
+ .filter(Boolean)
+ .join("\n\n");
+
+if (local) {
+ if (summary) console.log(`${summary}\n\n${detail}\n`);
+ process.exit(0);
+}
+
+appendFileSync(GITHUB_OUTPUT, `categories=${JSON.stringify(categories.map(([, many]) => many))}\n`);
+if (detail) appendFileSync(GITHUB_STEP_SUMMARY, `${detail}\n`);
diff --git a/.github/scripts/change-approval.test.mjs b/.github/scripts/change-approval.test.mjs
new file mode 100644
index 0000000000..dadf0c21e6
--- /dev/null
+++ b/.github/scripts/change-approval.test.mjs
@@ -0,0 +1,388 @@
+import assert from "node:assert/strict";
+import { execFileSync } from "node:child_process";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import test from "node:test";
+
+const script = join(import.meta.dirname, "change-approval.mjs");
+const env = {
+ PATH: process.env.PATH,
+ GIT_CONFIG_GLOBAL: "/dev/null",
+ GIT_CONFIG_NOSYSTEM: "1",
+ GIT_AUTHOR_NAME: "test",
+ GIT_AUTHOR_EMAIL: "[email protected]",
+ GIT_COMMITTER_NAME: "test",
+ GIT_COMMITTER_EMAIL: "[email protected]",
+};
+
+const scan = (t, base, change, { commit: committed = true, gitlink, symlink, ci = false } = {}) => {
+ const repo = mkdtempSync(join(tmpdir(), "change-approval-"));
+ t.after(() => rmSync(repo, { recursive: true }));
+ const git = (...args) => execFileSync("git", args, { cwd: repo, env, encoding: "utf8" });
+ const write = (files) => {
+ for (const [file, content] of Object.entries(files)) {
+ if (content === null) {
+ rmSync(join(repo, file));
+ } else {
+ mkdirSync(join(repo, dirname(file)), { recursive: true });
+ writeFileSync(join(repo, file), content);
+ }
+ }
+ };
+ const commit = (revision) => {
+ git("add", "-A");
+ if (gitlink) git("update-index", "--add", "--cacheinfo", `160000,${String(revision).repeat(40)},${gitlink}`);
+ git("commit", "-q", "--allow-empty", "-m", "change");
+ return git("rev-parse", "HEAD").trim();
+ };
+ git("init", "-q", "-b", "main");
+ write(base);
+ const sha = commit(1);
+ write(change);
+ if (symlink) symlinkSync("missing-target", join(repo, symlink));
+ if (committed) commit(2);
+ const outputs = ci ? { GITHUB_OUTPUT: join(repo, ".output"), GITHUB_STEP_SUMMARY: join(repo, ".summary") } : {};
+ const stdout = execFileSync(process.execPath, [script, sha], { cwd: repo, env: { ...env, ...outputs }, encoding: "utf8" });
+ const read = (file) => (existsSync(file) ? readFileSync(file, "utf8") : "");
+ return ci ? { stdout, output: read(outputs.GITHUB_OUTPUT), summary: read(outputs.GITHUB_STEP_SUMMARY) } : stdout;
+};
+
+const registry = "registry+https://github.com/rust-lang/crates.io-index";
+const cargo = (packages) =>
+ packages
+ .map(
+ ([name, version, source = registry]) =>
+ `[[package]]\nname = "${name}"\nversion = "${version}"\n${source ? `source = "${source}"\n` : ""}`,
+ )
+ .join("\n");
+const npm = (packages) => JSON.stringify({ packages: { "": {}, ...packages } });
+const tarball = (name, version, host = "registry.npmjs.org") => ({
+ version,
+ resolved: `https://${host}/${name}/-/${name}-${version}.tgz`,
+});
+const pub = (packages) =>
+ `packages:\n${packages
+ .map(
+ ([name, version, source = "hosted"]) =>
+ ` ${name}:\n dependency: transitive\n description:\n${
+ source === "path"
+ ? ` path: "../${name}"\n relative: true\n`
+ : ` name: ${name}\n url: "https://pub.dev"\n`
+ } source: ${source}\n version: "${version}"\n`,
+ )
+ .join("")}sdks:\n dart: ">=3.0.0 <4.0.0"\n`;
+const gosum = (modules) =>
+ modules.map(([name, version]) => `${name} ${version} h1:x=\n${name} ${version}/go.mod h1:y=\n`).join("");
+const pins = (entries) =>
+ JSON.stringify({
+ pins: entries.map(([identity, version]) => ({
+ identity,
+ location: `https://github.com/x/${identity}.git`,
+ state: { version },
+ })),
+ });
+const podfile = ({ pods, repos = {}, external = {} }) =>
+ `PODS:\n${pods.map((spec) => ` - ${spec}\n`).join("")}\nSPEC REPOS:\n${Object.entries(repos)
+ .map(([repo, names]) => ` ${repo}:\n${names.map((name) => ` - ${name}\n`).join("")}`)
+ .join("")}\nEXTERNAL SOURCES:\n${Object.entries(external)
+ .map(([name, props]) => ` ${name}:\n${Object.entries(props).map(([key, value]) => ` :${key}: ${value}\n`).join("")}`)
+ .join("")}\nCOCOAPODS: 1.17.0\n`;
+const uv = (entries) =>
+ entries
+ .map(([name, version, source = '{ registry = "https://pypi.org/simple" }']) => `[[package]]\nname = "${name}"\nversion = "${version}"\nsource = ${source}\n`)
+ .join("\n");
+
+test("binary added", (t) => {
+ const output = scan(t, {}, { "a.bin": Buffer.alloc(16) });
+ assert.equal(output, "1 binary file\n\n## Binary files\n\n- `a.bin` (16 bytes)\n\n");
+});
+
+test("binary modified", (t) => {
+ const output = scan(t, { "a.bin": Buffer.alloc(16) }, { "a.bin": Buffer.alloc(32) });
+ assert.match(output, /^1 binary file\n/);
+ assert.match(output, /`a.bin` \(32 bytes\)/);
+});
+
+test("binary deleted is ignored", (t) => {
+ assert.equal(scan(t, { "a.bin": Buffer.alloc(16) }, { "a.bin": null }), "");
+});
+
+test("routine image, font, and xcassets binaries are ignored", (t) => {
+ const output = scan(t, {}, {
+ "src/logo.PNG": Buffer.alloc(16),
+ "web/fonts/a.woff2": Buffer.alloc(16),
+ "ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents": Buffer.alloc(16),
+ });
+ assert.equal(output, "");
+});
+
+test("large files added, binary or text, not grown", (t) => {
+ const size = 1024 * 1024 + 1;
+ const output = scan(
+ t,
+ { "big.txt": "a" },
+ { "big.txt": "a".repeat(size), "big.bin": Buffer.alloc(size), "new.txt": "b".repeat(size) },
+ );
+ assert.equal(
+ output,
+ `1 binary file, 2 large files\n\n## Binary files\n\n- \`big.bin\` (${size} bytes)\n\n## Large files\n\n- \`big.bin\` (${size} bytes)\n- \`new.txt\` (${size} bytes)\n\n`,
+ );
+});
+
+test("Cargo.lock new package, not version bump", (t) => {
+ const output = scan(
+ t,
+ { "rust/Cargo.lock": cargo([["a", "1.0.0"], ["b", "1.0.0"]]) },
+ { "rust/Cargo.lock": cargo([["a", "1.1.0"], ["b", "1.0.0"], ["c", "2.0.0"]]) },
+ );
+ assert.equal(output, "1 new dependency\n\n## New dependencies\n\n`rust/Cargo.lock`\n\n- c 2.0.0\n\n");
+});
+
+test("workspace-local packages are not dependencies", (t) => {
+ const output = scan(
+ t,
+ { "Cargo.lock": cargo([["a", "1.0.0"]]), "pubspec.lock": pub([["a", "1.0.0"]]), "package-lock.json": npm({}) },
+ {
+ "Cargo.lock": cargo([["a", "1.0.0"], ["member", "0.0.0", ""]]),
+ "pubspec.lock": pub([["a", "1.0.0"], ["local", "0.0.1", "path"]]),
+ "package-lock.json": npm({ "node_modules/w": { resolved: "apps/w", link: true } }),
+ },
+ );
+ assert.equal(output, "");
+});
+
+test("dependency source change, even beside the original version", (t) => {
+ const fork = "git+https://github.com/x/a";
+ const output = scan(
+ t,
+ { "package-lock.json": npm({ "node_modules/y": tarball("y", "1.0.0") }), "rust/Cargo.lock": cargo([["a", "1.0.0"]]) },
+ {
+ "package-lock.json": npm({ "node_modules/y": tarball("y", "1.0.0", "npm.example.com") }),
+ "rust/Cargo.lock": cargo([["a", "1.0.0"], ["a", "1.1.0", fork]]),
+ },
+ );
+ assert.equal(
+ output,
+ `2 dependency source changes\n\n## New dependencies\n\n\`package-lock.json\`\n\n- y: https://registry.npmjs.org/y -> https://npm.example.com/y\n\n\`rust/Cargo.lock\`\n\n- a: ${registry} -> ${fork}\n\n`,
+ );
+});
+
+test("git rev bump keeps the source, repository change does not", (t) => {
+ const at = (repo, rev) => `git+${repo}?rev=${rev}#${rev}`;
+ const output = scan(
+ t,
+ {
+ "rust/Cargo.lock": cargo([["h", "0.2.0", at("https://github.com/ente/heic-decoder.git", "aaa")], ["r", "1.0.0", at("https://github.com/a/r.git", "x")]]),
+ "uv.lock": uv([["u", "1.0.0", '{ git = "https://github.com/x/u?rev=1#1" }']]),
+ },
+ {
+ "rust/Cargo.lock": cargo([["h", "0.2.0", at("https://github.com/ente/heic-decoder.git", "bbb")], ["r", "1.0.0", at("https://github.com/b/r.git", "x")]]),
+ "uv.lock": uv([["u", "1.0.0", '{ git = "https://github.com/x/u?rev=2#2" }']]),
+ },
+ );
+ assert.equal(
+ output,
+ "1 dependency source change\n\n## New dependencies\n\n`rust/Cargo.lock`\n\n- r: git+https://github.com/a/r.git -> git+https://github.com/b/r.git\n\n",
+ );
+});
+
+test("package-lock.json new nested package", (t) => {
+ const output = scan(
+ t,
+ { "package-lock.json": npm({ "node_modules/x": tarball("x", "1.0.0") }) },
+ {
+ "package-lock.json": npm({
+ "node_modules/x": tarball("x", "1.0.1"),
+ "node_modules/x/node_modules/@s/y": tarball("y", "2.0.0"),
+ }),
+ },
+ );
+ assert.match(output, /^1 new dependency\n/);
+ assert.match(output, /- @s\/y 2\.0\.0\n/);
+});
+
+test("pubspec.lock new package", (t) => {
+ const output = scan(t, { "pubspec.lock": pub([["a", "1.0.0"]]) }, { "pubspec.lock": pub([["a", "1.0.0"], ["b", "3.1.4"]]) });
+ assert.match(output, /^1 new dependency\n/);
+ assert.match(output, /- b 3\.1\.4\n/);
+});
+
+test("Package.resolved, Podfile.lock, and uv.lock new packages", (t) => {
+ const output = scan(
+ t,
+ {
+ "Package.resolved": pins([["a", "1.0.0"]]),
+ "Podfile.lock": podfile({ pods: ["A/Core (1.0.0)"], repos: { trunk: ["A"] } }),
+ "uv.lock": uv([["a", "1.0.0"]]),
+ },
+ {
+ "Package.resolved": pins([["a", "1.0.0"], ["b", "2.0.0"]]),
+ "Podfile.lock": podfile({
+ pods: ["A/Core (1.0.0)", "A/Extra (1.0.0)", '"B/Sub+x (3.0.0)"'],
+ repos: { trunk: ["A", "B"] },
+ }),
+ "uv.lock": uv([["a", "1.0.0"], ["c", "4.0.0"], ["me", "0.0.0", '{ virtual = "." }']]),
+ },
+ );
+ assert.equal(
+ output,
+ "3 new dependencies\n\n## New dependencies\n\n`Package.resolved`\n\n- b 2.0.0\n\n`Podfile.lock`\n\n- B 3.0.0\n\n`uv.lock`\n\n- c 4.0.0\n\n",
+ );
+});
+
+test("Podfile.lock pod moving from a spec repo to git is a source change", (t) => {
+ const output = scan(
+ t,
+ { "ios/Podfile.lock": podfile({ pods: ["Sentry (8.0.0)"], repos: { trunk: ["Sentry"] } }) },
+ {
+ "ios/Podfile.lock": podfile({
+ pods: ["Sentry (8.0.0)"],
+ external: { Sentry: { branch: "main", git: "https://github.com/x/sentry-cocoa.git" } },
+ }),
+ },
+ );
+ assert.equal(
+ output,
+ "1 dependency source change\n\n## New dependencies\n\n`ios/Podfile.lock`\n\n- Sentry: trunk -> https://github.com/x/sentry-cocoa.git\n\n",
+ );
+});
+
+test("local path packages are not dependencies until they leave the tree", (t) => {
+ const output = scan(
+ t,
+ { "ios/Podfile.lock": podfile({ pods: ["A (1.0.0)"], repos: { trunk: ["A"] } }), "uv.lock": uv([["b", "1.0.0", '{ directory = "../b" }']]) },
+ {
+ "ios/Podfile.lock": podfile({
+ pods: ["A (1.0.0)", "Local (1.0.0)"],
+ repos: { trunk: ["A"] },
+ external: { Local: { path: '"../Local"' } },
+ }),
+ "uv.lock": uv([["b", "1.0.0"], ["c", "2.0.0", '{ directory = "../c" }'], ["d", "3.0.0", '{ editable = "." }']]),
+ },
+ );
+ assert.equal(
+ output,
+ '1 dependency source change\n\n## New dependencies\n\n`uv.lock`\n\n- b: { directory = "../b" } -> { registry = "https://pypi.org/simple" }\n\n',
+ );
+});
+
+test("npm alias of a present package is not new", (t) => {
+ const output = scan(
+ t,
+ { "package-lock.json": npm({ "node_modules/react": tarball("react", "18.3.1") }) },
+ {
+ "package-lock.json": npm({
+ "node_modules/react": tarball("react", "18.3.1"),
+ "node_modules/react-alias": { name: "react", ...tarball("react", "18.3.1") },
+ }),
+ },
+ );
+ assert.equal(output, "");
+});
+
+test("bundled npm entry without resolved is new by name only", (t) => {
+ const output = scan(
+ t,
+ { "package-lock.json": npm({ "node_modules/x": tarball("x", "1.0.0") }) },
+ {
+ "package-lock.json": npm({
+ "node_modules/x": tarball("x", "1.0.1"),
+ "node_modules/x/node_modules/y": { version: "1.0.0", inBundle: true },
+ }),
+ },
+ );
+ assert.equal(output, "1 new dependency\n\n## New dependencies\n\n`package-lock.json`\n\n- y 1.0.0\n\n");
+});
+
+test("npm file: entry is local until it moves to the registry", (t) => {
+ const output = scan(
+ t,
+ { "package-lock.json": npm({ "node_modules/x": { version: "1.0.0", resolved: "file:vendor/x-1.0.0.tgz" } }) },
+ {
+ "package-lock.json": npm({
+ "node_modules/x": tarball("x", "1.0.0"),
+ "node_modules/z": { version: "2.0.0", resolved: "file:vendor/z-2.0.0.tgz" },
+ }),
+ },
+ );
+ assert.equal(
+ output,
+ "1 dependency source change\n\n## New dependencies\n\n`package-lock.json`\n\n- x: file:vendor/x-1.0.0.tgz -> https://registry.npmjs.org/x\n\n",
+ );
+});
+
+test("go.sum new module", (t) => {
+ const output = scan(
+ t,
+ { "go.sum": gosum([["a.com/x", "v1.0.0"]]) },
+ { "go.sum": gosum([["a.com/x", "v1.2.0"], ["b.org/y/v2", "v2.0.1"]]) },
+ );
+ assert.match(output, /^1 new dependency\n/);
+ assert.match(output, /- b\.org\/y\/v2 v2\.0\.1\n/);
+});
+
+test("guardrail paths modified or deleted, not added", (t) => {
+ const output = scan(
+ t,
+ { ".github/scripts/x.mjs": "", ".github/workflows/x.yml": "on: push\n", "web/apps/x/eslint.config.mjs": "" },
+ {
+ ".github/scripts/x.mjs": "export {};\n",
+ ".github/workflows/x.yml": "on: pull_request\n",
+ "web/apps/x/eslint.config.mjs": null,
+ ".github/CODEOWNERS": "",
+ },
+ );
+ assert.equal(
+ output,
+ "3 guardrail files\n\n## Guardrail changes\n\n- `.github/scripts/x.mjs`\n- `.github/workflows/x.yml`\n- `web/apps/x/eslint.config.mjs`\n\n",
+ );
+});
+
+test("toolchain and registry config modified, not added", (t) => {
+ const output = scan(
+ t,
+ { "web/.npmrc": "", "rust/.cargo/config.toml": "" },
+ { "web/.npmrc": "registry=https://example.com\n", "rust/.cargo/config.toml": null, ".nvmrc": "24\n" },
+ );
+ assert.equal(
+ output,
+ "2 config files\n\n## Toolchain and registry config\n\n- `rust/.cargo/config.toml`\n- `web/.npmrc`\n\n",
+ );
+});
+
+test("uncommitted and untracked changes are scanned locally", (t) => {
+ const output = scan(
+ t,
+ { "a.bin": Buffer.alloc(16) },
+ { "a.bin": Buffer.alloc(32), "rust/Cargo.lock": cargo([["a", "1.0.0"]]) },
+ { commit: false },
+ );
+ assert.equal(
+ output,
+ "1 binary file, 1 new dependency\n\n## Binary files\n\n- `a.bin` (32 bytes)\n\n## New dependencies\n\n`rust/Cargo.lock`\n\n- a 1.0.0\n\n",
+ );
+});
+
+test("CI mode writes categories and the step summary, and tolerates gitlinks", (t) => {
+ const { stdout, output, summary } = scan(t, { "a.txt": "a\n" }, { "a.bin": Buffer.alloc(16) }, { gitlink: "sub", ci: true });
+ assert.equal(stdout, "");
+ assert.equal(output, 'categories=["binary files"]\n');
+ assert.equal(summary, "## Binary files\n\n- `a.bin` (16 bytes)\n");
+});
+
+test("untracked dangling symlink is skipped locally", (t) => {
+ const output = scan(t, { "a.txt": "a\n" }, { "a.bin": Buffer.alloc(16) }, { commit: false, symlink: "link" });
+ assert.equal(output, "1 binary file\n\n## Binary files\n\n- `a.bin` (16 bytes)\n\n");
+});
+
+test("CI mode with nothing flagged", (t) => {
+ const { stdout, output, summary } = scan(t, { "a.txt": "a\n" }, { "a.txt": "b\n" }, { ci: true });
+ assert.equal(stdout, "");
+ assert.equal(output, "categories=[]\n");
+ assert.equal(summary, "");
+});
+
+test("ordinary change is silent", (t) => {
+ assert.equal(scan(t, { "src/a.txt": "a\n" }, { "src/a.txt": "b\n", "src/b.txt": "c\n" }), "");
+});
diff --git a/.github/workflows/change-approval.yml b/.github/workflows/change-approval.yml
new file mode 100644
index 0000000000..138b2e0be5
--- /dev/null
+++ b/.github/workflows/change-approval.yml
@@ -0,0 +1,69 @@
+name: Change approval
+
+on:
+ pull_request:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ test:
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout PR
+ uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
+
+ - run: node --test .github/scripts/change-approval.test.mjs
+
+ detect:
+ runs-on: ubuntu-latest
+ outputs:
+ categories: ${{ steps.scan.outputs.categories }}
+ steps:
+ - name: Checkout PR
+ uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
+ with:
+ fetch-depth: 2
+
+ - name: Checkout trusted scanner
+ uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
+ with:
+ ref: ${{ github.event.pull_request.base.sha }}
+ path: trusted
+ sparse-checkout: .github/scripts/change-approval.mjs
+ sparse-checkout-cone-mode: false
+
+ - name: Scan changes
+ id: scan
+ run: node "$scanner" ${{ github.event.pull_request.base.sha }}
+ env:
+ scanner: ${{ hashFiles('trusted/.github/scripts/change-approval.mjs') && 'trusted/.github/scripts/change-approval.mjs' || '.github/scripts/change-approval.mjs' }}
+
+ approve:
+ needs: detect
+ if: needs.detect.outputs.categories != '[]'
+ name: Approve ${{ matrix.category }}
+ runs-on: ubuntu-latest
+ strategy:
+ matrix:
+ category: ${{ fromJSON(needs.detect.outputs.categories) }}
+ environment:
+ # Require admin approval for flagged changes.
+ name: change-approval
+ steps:
+ - run: "true"
+
+ gate:
+ needs: [test, detect, approve]
+ if: always()
+ runs-on: ubuntu-latest
+ steps:
+ - run: test "$test" = success && test "$detect" = success && { test "$approve" = success || test "$approve" = skipped; }
+ env:
+ test: ${{ needs.test.result }}
+ detect: ${{ needs.detect.result }}
+ approve: ${{ needs.approve.result }}