mirror of
https://github.com/diegosouzapw/OmniRoute.git
synced 2026-11-16 17:09:09 +00:00
feat(ci): shared pr/release gate mode and a derived-files guard for feature PRs
Plan 2026-11-13 (derived numbers and texts resolved only at release), shared contract for phases 4 and 5: - scripts/check/lib/gateMode.mjs resolves pr|release for every gate that judges derived content: --mode, then OMNIROUTE_GATE_MODE, then the Actions event (feature pull_request, merge_group and omni-queue pushes are pr; push, schedule, dispatch, the release PR and local runs stay release, the strict behaviour of today). It also resolves the PR diff base and the changed files. - scripts/check/check-pr-derived-paths.mjs fails a feature PR that carries files a refresh owns, per family declared in config/quality/derived-paths/*.json. A PR that only touches one family (a translation fix) and the family's writer branches are allowed; queue batches are skipped. No family is declared yet: phases 4 and 5 add theirs together with the gates they switch to release mode. - Wired as a step of the PR Test Policy job.
This commit is contained in:
10
.github/workflows/ci.yml
vendored
10
.github/workflows/ci.yml
vendored
@@ -751,6 +751,16 @@ jobs:
|
||||
node-version: ${{ env.CI_NODE_VERSION }}
|
||||
- name: Fetch base branch
|
||||
run: git fetch --no-tags origin "${GITHUB_BASE_REF}"
|
||||
# Plan 2026-11-13 (derived files are written at release): translation mirrors, the
|
||||
# non-English UI/CLI catalogs, generated docs and quality baselines each have ONE writer
|
||||
# (a translation wave, `release:refresh-derived`, a nightly refresh PR). A feature PR that
|
||||
# carries its own copy conflicts with every sibling that does the same (48 open PRs edited
|
||||
# the same ~43 locale catalogs on 2026-11-13). Families + writer branches:
|
||||
# config/quality/derived-paths/*.json. The diff base is the freshly fetched origin/<base>,
|
||||
# not the event's base SHA: on a fast base the merge ref is newer than that SHA and the
|
||||
# base's own commits would be judged as the PR's.
|
||||
- name: Derived files stay out of feature PRs
|
||||
run: npm run check:pr-derived-paths
|
||||
- name: Validate source changes include tests
|
||||
run: node scripts/check/check-pr-test-policy.mjs --summary-file .artifacts/pr-test-policy.md
|
||||
# Anti test-masking: flag net assert removal / new assert.ok(true) in changed tests.
|
||||
|
||||
@@ -163,6 +163,11 @@
|
||||
"command": "node scripts/check/check-docs-symbols.mjs",
|
||||
"disposition": "separately-invoked"
|
||||
},
|
||||
{
|
||||
"name": "check:pr-derived-paths",
|
||||
"command": "node scripts/check/check-pr-derived-paths.mjs",
|
||||
"disposition": "separately-invoked"
|
||||
},
|
||||
{
|
||||
"name": "check:docs-sync",
|
||||
"command": "node scripts/check/check-docs-sync.mjs",
|
||||
|
||||
@@ -254,6 +254,7 @@
|
||||
"check:type-scale-ratchet": "node scripts/check/check-type-scale-ratchet.mjs",
|
||||
"check:licenses": "node scripts/check/check-licenses.mjs",
|
||||
"check:pr-evidence": "node scripts/check/check-pr-evidence.mjs",
|
||||
"check:pr-derived-paths": "node scripts/check/check-pr-derived-paths.mjs",
|
||||
"check:vuln-ratchet": "node scripts/check/check-vuln-ratchet.mjs",
|
||||
"check:codeql-ratchet": "node scripts/check/check-codeql-ratchet.mjs",
|
||||
"check:secrets": "node scripts/check/check-secrets.mjs",
|
||||
|
||||
332
scripts/check/check-pr-derived-paths.mjs
Normal file
332
scripts/check/check-pr-derived-paths.mjs
Normal file
@@ -0,0 +1,332 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* OmniRoute — derived files stay out of feature PRs (PR-scope gate, blocking in `pr` mode).
|
||||
*
|
||||
* Plan "derived numbers and texts resolved only at release" (2026-11-13). Some files are not
|
||||
* written by people: the 66 translation mirrors under docs/i18n, the UI/CLI catalogs of the
|
||||
* non-English locales, generated reference docs, quality baselines. Each one is recomputed in
|
||||
* one place — a translation wave, the release refresh (`release:refresh-derived`) or a nightly
|
||||
* refresh PR. When feature PRs also edit them, every merge invalidates the copy that every
|
||||
* sibling PR carries: on 2026-11-13, 48 open PRs touched the same ~43 locale catalogs and 44
|
||||
* touched docs/i18n. This gate keeps those files out of feature PRs.
|
||||
*
|
||||
* The rule, per FAMILY of derived files (config/quality/derived-paths/*.json):
|
||||
* - a PR that touches nothing but that family's files (plus its companions, e.g. a changelog
|
||||
* fragment) is a refresh/translation PR → allowed (a community fix to ko.json is fine);
|
||||
* - a PR whose head branch matches one of the family's `writers` globs → allowed
|
||||
* (release/v*, translation waves, derived-refresh branches);
|
||||
* - any other PR that touches a family file → FAIL: those edits ride along with a feature
|
||||
* and belong to the refresh that owns them.
|
||||
*
|
||||
* Only runs in `pr` mode (scripts/check/lib/gateMode.mjs). In `release` mode it is a no-op:
|
||||
* the release PR and the refresh branches are exactly the ones that write derived files.
|
||||
*
|
||||
* Usage:
|
||||
* node scripts/check/check-pr-derived-paths.mjs # mode from the environment
|
||||
* node scripts/check/check-pr-derived-paths.mjs --mode=pr # preview the CI verdict locally
|
||||
* node scripts/check/check-pr-derived-paths.mjs --files=changed.txt # explicit change list
|
||||
* node scripts/check/check-pr-derived-paths.mjs --branch=feat/x # override the head branch
|
||||
* node scripts/check/check-pr-derived-paths.mjs --warn | --json
|
||||
* npm run check:pr-derived-paths
|
||||
*
|
||||
* Base for the diff (pr mode): BASE_SHA, GITHUB_BASE_SHA, BASE_REF, origin/$GITHUB_BASE_REF,
|
||||
* origin/release/v<package.json version> — first that resolves. No resolvable base → SKIP.
|
||||
*/
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import process from "node:process";
|
||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||
|
||||
import {
|
||||
describeGateMode,
|
||||
listChangedFiles,
|
||||
resolveGateModeInfo,
|
||||
resolveHeadBranch,
|
||||
resolvePrDiffBase,
|
||||
} from "./lib/gateMode.mjs";
|
||||
|
||||
const SCRIPT_DIR = path.dirname(fileURLToPath(import.meta.url));
|
||||
const ROOT = path.resolve(SCRIPT_DIR, "..", "..");
|
||||
export const CONFIG_DIR_REL = "config/quality/derived-paths";
|
||||
const TAG = "[derived-paths]";
|
||||
// Queue batches (Mergify drafts, the omni-queue candidate, GitHub's merge queue) are sums of PRs.
|
||||
const QUEUE_BRANCHES = [/^mergify\/merge-queue\//, /^omni-queue\//, /^gh-readonly-queue\//];
|
||||
|
||||
/**
|
||||
* Glob → RegExp over repo-relative POSIX paths. `**` crosses directories (`**` before a slash may also
|
||||
* match zero directories), `*` and `?` stay inside one path segment. No braces or classes: the config
|
||||
* only needs these three.
|
||||
*/
|
||||
export function globToRegExp(glob) {
|
||||
let out = "";
|
||||
for (let i = 0; i < glob.length; i += 1) {
|
||||
const ch = glob[i];
|
||||
if (ch === "*") {
|
||||
if (glob[i + 1] === "*") {
|
||||
const slashAfter = glob[i + 2] === "/";
|
||||
out += slashAfter ? "(?:.*/)?" : ".*";
|
||||
i += slashAfter ? 2 : 1;
|
||||
} else {
|
||||
out += "[^/]*";
|
||||
}
|
||||
} else if (ch === "?") {
|
||||
out += "[^/]";
|
||||
} else {
|
||||
out += ch.replace(/[.+^${}()|[\]\\]/g, "\\$&");
|
||||
}
|
||||
}
|
||||
return new RegExp(`^${out}$`);
|
||||
}
|
||||
|
||||
export function matchesAny(file, globs = []) {
|
||||
return globs.some((glob) => globToRegExp(glob).test(file));
|
||||
}
|
||||
|
||||
function asStringArray(value, where) {
|
||||
if (value === undefined) return [];
|
||||
if (!Array.isArray(value) || value.some((v) => typeof v !== "string" || !v.trim())) {
|
||||
throw new Error(`${where} must be an array of non-empty strings`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/** Validates one family file; returns a normalized object or throws with the file name. */
|
||||
export function normalizeFamily(raw, source = "<inline>") {
|
||||
const where = (field) => `${source}: ${field}`;
|
||||
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
|
||||
throw new Error(`${source}: expected a JSON object`);
|
||||
}
|
||||
if (typeof raw.family !== "string" || !raw.family.trim()) throw new Error(where("family"));
|
||||
if (!Array.isArray(raw.categories) || raw.categories.length === 0) {
|
||||
throw new Error(where("categories must be a non-empty array"));
|
||||
}
|
||||
const ids = new Set();
|
||||
const categories = raw.categories.map((cat, i) => {
|
||||
const at = `categories[${i}]`;
|
||||
if (!cat || typeof cat.id !== "string" || !cat.id.trim()) throw new Error(where(`${at}.id`));
|
||||
if (ids.has(cat.id)) throw new Error(where(`duplicate category id "${cat.id}"`));
|
||||
ids.add(cat.id);
|
||||
const paths = asStringArray(cat.paths, where(`${at}.paths`));
|
||||
if (!paths.length) throw new Error(where(`${at}.paths must not be empty`));
|
||||
return {
|
||||
id: cat.id,
|
||||
paths,
|
||||
except: asStringArray(cat.except, where(`${at}.except`)),
|
||||
why: typeof cat.why === "string" ? cat.why : "",
|
||||
refreshedBy: typeof cat.refreshedBy === "string" ? cat.refreshedBy : "",
|
||||
};
|
||||
});
|
||||
return {
|
||||
family: raw.family,
|
||||
description: typeof raw.description === "string" ? raw.description : "",
|
||||
writers: asStringArray(raw.writers, where("writers")),
|
||||
companions: asStringArray(raw.companions, where("companions")),
|
||||
categories,
|
||||
source,
|
||||
};
|
||||
}
|
||||
|
||||
/** Every `*.json` under the config dir, sorted by file name. A missing dir is an empty set. */
|
||||
export function loadFamilies(root = ROOT) {
|
||||
const dir = path.join(root, CONFIG_DIR_REL);
|
||||
if (!fs.existsSync(dir)) return [];
|
||||
const families = fs
|
||||
.readdirSync(dir)
|
||||
.filter((name) => name.endsWith(".json"))
|
||||
.sort()
|
||||
.map((name) => {
|
||||
const rel = `${CONFIG_DIR_REL}/${name}`;
|
||||
let raw;
|
||||
try {
|
||||
raw = JSON.parse(fs.readFileSync(path.join(dir, name), "utf8"));
|
||||
} catch (err) {
|
||||
throw new Error(`${rel}: ${err.message}`);
|
||||
}
|
||||
return normalizeFamily(raw, rel);
|
||||
});
|
||||
const seen = new Map();
|
||||
for (const fam of families) {
|
||||
if (seen.has(fam.family)) {
|
||||
throw new Error(
|
||||
`family "${fam.family}" declared twice (${seen.get(fam.family)}, ${fam.source})`
|
||||
);
|
||||
}
|
||||
seen.set(fam.family, fam.source);
|
||||
}
|
||||
return families;
|
||||
}
|
||||
|
||||
/** First category of the family that claims the file, or null. */
|
||||
export function categoryOf(file, family) {
|
||||
for (const cat of family.categories) {
|
||||
if (matchesAny(file, cat.paths) && !matchesAny(file, cat.except)) return cat;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pure core.
|
||||
* @param {object} args
|
||||
* @param {string[]} args.files repo-relative paths the change touches
|
||||
* @param {string} args.branch head branch name ("" when unknown)
|
||||
* @param {ReturnType<typeof normalizeFamily>[]} args.families
|
||||
* @returns {{ violations: Array<{ family: string, category: string, files: string[], why: string, refreshedBy: string }>,
|
||||
* allowed: Array<{ family: string, reason: "writer" | "family-only", files: string[] }> }}
|
||||
*/
|
||||
export function evaluateDerivedPaths({ files, branch, families }) {
|
||||
const violations = [];
|
||||
const allowed = [];
|
||||
for (const family of families) {
|
||||
const byCategory = new Map();
|
||||
for (const file of files) {
|
||||
const cat = categoryOf(file, family);
|
||||
if (!cat) continue;
|
||||
if (!byCategory.has(cat.id)) byCategory.set(cat.id, { cat, files: [] });
|
||||
byCategory.get(cat.id).files.push(file);
|
||||
}
|
||||
if (byCategory.size === 0) continue;
|
||||
const touched = [...byCategory.values()].flatMap((entry) => entry.files);
|
||||
|
||||
if (branch && matchesAny(branch, family.writers)) {
|
||||
allowed.push({ family: family.family, reason: "writer", files: touched });
|
||||
continue;
|
||||
}
|
||||
const familyOnly = files.every(
|
||||
(file) => categoryOf(file, family) !== null || matchesAny(file, family.companions)
|
||||
);
|
||||
if (familyOnly) {
|
||||
allowed.push({ family: family.family, reason: "family-only", files: touched });
|
||||
continue;
|
||||
}
|
||||
for (const { cat, files: catFiles } of byCategory.values()) {
|
||||
violations.push({
|
||||
family: family.family,
|
||||
category: cat.id,
|
||||
files: catFiles,
|
||||
why: cat.why,
|
||||
refreshedBy: cat.refreshedBy,
|
||||
});
|
||||
}
|
||||
}
|
||||
return { violations, allowed };
|
||||
}
|
||||
|
||||
function parseArgs(argv) {
|
||||
const value = (name) => {
|
||||
const hit = argv.find((arg) => arg.startsWith(`--${name}=`));
|
||||
return hit ? hit.slice(name.length + 3) : undefined;
|
||||
};
|
||||
return {
|
||||
warn: argv.includes("--warn"),
|
||||
json: argv.includes("--json"),
|
||||
files: value("files"),
|
||||
branch: value("branch"),
|
||||
};
|
||||
}
|
||||
|
||||
function readFileList(file) {
|
||||
return fs
|
||||
.readFileSync(path.resolve(file), "utf8")
|
||||
.split(/\r?\n/)
|
||||
.map((line) => line.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function emit(opts, payload, lines, stream = "log") {
|
||||
if (opts.json) process.stdout.write(`${JSON.stringify(payload, null, 2)}\n`);
|
||||
else for (const line of lines) console[stream](line);
|
||||
}
|
||||
|
||||
export function main(argv = process.argv.slice(2), env = process.env, cwd = ROOT) {
|
||||
const opts = parseArgs(argv);
|
||||
const info = resolveGateModeInfo({ argv, env });
|
||||
const families = loadFamilies(cwd);
|
||||
|
||||
if (info.mode === "release") {
|
||||
emit(opts, { ok: true, skipped: true, reason: "release-mode", mode: info }, [
|
||||
`${TAG} SKIP — ${describeGateMode(info)}: the release PR and refresh branches are the writers of derived files.`,
|
||||
]);
|
||||
return 0;
|
||||
}
|
||||
|
||||
const branch = opts.branch ?? resolveHeadBranch({ env, cwd });
|
||||
if (env.GITHUB_EVENT_NAME === "merge_group" || QUEUE_BRANCHES.some((re) => re.test(branch))) {
|
||||
emit(opts, { ok: true, skipped: true, reason: "queue-batch", mode: info, branch }, [
|
||||
`${TAG} SKIP reason=queue-batch — ${branch || "merge_group"} sums PRs this gate already judged one by one (a translation-only PR next to feature PRs is not a mixed PR).`,
|
||||
]);
|
||||
return 0;
|
||||
}
|
||||
|
||||
let files;
|
||||
let baseLabel;
|
||||
if (opts.files) {
|
||||
files = readFileList(opts.files);
|
||||
baseLabel = `--files=${opts.files}`;
|
||||
} else {
|
||||
const base = resolvePrDiffBase({ env, cwd });
|
||||
if (!base) {
|
||||
emit(opts, { ok: true, skipped: true, reason: "base-unresolved", mode: info }, [
|
||||
`${TAG} SKIP reason=base-unresolved — no merge base (shallow clone or unknown base ref); set BASE_SHA or fetch the base branch.`,
|
||||
]);
|
||||
return 0;
|
||||
}
|
||||
files = listChangedFiles(base.sha, { cwd, includeWorktree: !env.CI });
|
||||
baseLabel = `${base.ref} @ ${base.sha.slice(0, 10)}`;
|
||||
}
|
||||
|
||||
const { violations, allowed } = evaluateDerivedPaths({ files, branch, families });
|
||||
const payload = {
|
||||
ok: violations.length === 0,
|
||||
mode: info,
|
||||
base: baseLabel,
|
||||
branch,
|
||||
violations,
|
||||
allowed,
|
||||
};
|
||||
|
||||
if (violations.length === 0) {
|
||||
const notes = allowed.map(
|
||||
(a) =>
|
||||
`${TAG} allowed ${a.family}: ${a.files.length} file(s) (${a.reason === "writer" ? `writer branch ${branch}` : "derived-only PR"})`
|
||||
);
|
||||
emit(opts, payload, [
|
||||
`${TAG} PASS — ${describeGateMode(info)}; ${files.length} changed file(s) vs ${baseLabel}; ${families.length} famil${families.length === 1 ? "y" : "ies"} checked.`,
|
||||
...notes,
|
||||
]);
|
||||
return 0;
|
||||
}
|
||||
|
||||
const label = opts.warn ? "WARN" : "FAIL";
|
||||
const lines = [
|
||||
`${TAG} ${label} — ${describeGateMode(info)}; this PR edits files that a refresh owns, next to a feature change (base ${baseLabel}, branch ${branch || "?"}):`,
|
||||
];
|
||||
const sample = 6;
|
||||
for (const v of violations) {
|
||||
lines.push(
|
||||
` ✗ ${v.family}/${v.category} — ${v.files.length} file(s): ${v.files.slice(0, sample).join(", ")}${v.files.length > sample ? ", …" : ""}`
|
||||
);
|
||||
if (v.why) lines.push(` why: ${v.why}`);
|
||||
if (v.refreshedBy) lines.push(` refreshed by: ${v.refreshedBy}`);
|
||||
}
|
||||
lines.push(
|
||||
"",
|
||||
" Fix: drop those edits from this PR — restore each file to the base",
|
||||
" git restore --source=<base> --staged --worktree -- <file> (git rm <file> if this PR added it)",
|
||||
" and leave them to the refresh named above. A PR that changes ONLY files of one family",
|
||||
" (e.g. a translation fix to one locale) is allowed; so are the writer branches listed in",
|
||||
` ${CONFIG_DIR_REL}/<family>.json.`
|
||||
);
|
||||
emit(opts, payload, lines, "error");
|
||||
return opts.warn ? 0 : 1;
|
||||
}
|
||||
|
||||
const isDirectRun = process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href;
|
||||
if (isDirectRun) {
|
||||
try {
|
||||
process.exitCode = main();
|
||||
} catch (err) {
|
||||
console.error(`${TAG} ERROR — ${err.message}`);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
173
scripts/check/lib/gateMode.mjs
Normal file
173
scripts/check/lib/gateMode.mjs
Normal file
@@ -0,0 +1,173 @@
|
||||
// scripts/check/lib/gateMode.mjs
|
||||
// Shared mode resolver for the gates that judge DERIVED content (translation mirrors, UI
|
||||
// catalogs of the non-English locales, generated docs, quality baselines, managed counts).
|
||||
//
|
||||
// Plan "derived numbers and texts resolved only at release" (2026-11-13): a feature PR never
|
||||
// writes a value that depends on the state of its base. Those values are recomputed once, by
|
||||
// the release refresh (`release:refresh-derived`) or by a translation wave. So every gate that
|
||||
// compares derived content against the tree runs in one of two modes:
|
||||
//
|
||||
// pr — judge only what the change itself did. Never fail because the base moved.
|
||||
// release — strict equality against the tree, as these gates always did.
|
||||
//
|
||||
// Resolution order (first match wins):
|
||||
// 1. `--mode=pr|release` on the command line;
|
||||
// 2. `OMNIROUTE_GATE_MODE=pr|release` in the environment;
|
||||
// 3. automatic, from the GitHub Actions event:
|
||||
// pull_request / pull_request_target, head not `release/v*` → pr
|
||||
// merge_group, or push to `omni-queue/**` (a queue batch is a sum of feature PRs,
|
||||
// none of which carries refreshed derived files) → pr
|
||||
// everything else — push, schedule, workflow_dispatch, the release PR
|
||||
// (`release/v* → main`) and any local run → release
|
||||
//
|
||||
// A local run defaults to `release` on purpose: it is the behaviour every gate had before the
|
||||
// split, so nothing gets weaker by accident. Pass `--mode=pr` to preview what CI will judge.
|
||||
|
||||
import { execFileSync } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
export const GATE_MODES = Object.freeze(["pr", "release"]);
|
||||
|
||||
const PR_EVENTS = new Set(["pull_request", "pull_request_target"]);
|
||||
const RELEASE_HEAD = /^release\/v/;
|
||||
const QUEUE_REF = /^omni-queue\//;
|
||||
|
||||
function assertMode(value, source) {
|
||||
if (!GATE_MODES.includes(value)) {
|
||||
throw new Error(`invalid gate mode "${value}" from ${source} (expected pr or release)`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mode implied by the GitHub Actions event alone (step 3 above).
|
||||
* @param {Record<string, string | undefined>} env
|
||||
* @returns {{ mode: "pr" | "release", reason: string }}
|
||||
*/
|
||||
export function detectGateMode(env = process.env) {
|
||||
const event = env.GITHUB_EVENT_NAME || "";
|
||||
if (PR_EVENTS.has(event)) {
|
||||
const head = env.GITHUB_HEAD_REF || "";
|
||||
if (RELEASE_HEAD.test(head)) return { mode: "release", reason: `${event} from ${head}` };
|
||||
return { mode: "pr", reason: event };
|
||||
}
|
||||
if (event === "merge_group") return { mode: "pr", reason: "merge_group" };
|
||||
const refName = env.GITHUB_REF_NAME || "";
|
||||
if (event === "push" && QUEUE_REF.test(refName)) {
|
||||
return { mode: "pr", reason: `push to ${refName}` };
|
||||
}
|
||||
return { mode: "release", reason: event ? event : "local run" };
|
||||
}
|
||||
|
||||
/**
|
||||
* Full resolution with its provenance, for log lines.
|
||||
* @param {{ argv?: string[], env?: Record<string, string | undefined> }} [opts]
|
||||
* @returns {{ mode: "pr" | "release", source: "flag" | "env" | "auto", reason: string }}
|
||||
*/
|
||||
export function resolveGateModeInfo({ argv = process.argv, env = process.env } = {}) {
|
||||
const flag = argv.find((arg) => arg.startsWith("--mode="));
|
||||
if (flag) {
|
||||
return {
|
||||
mode: assertMode(flag.slice("--mode=".length), "--mode"),
|
||||
source: "flag",
|
||||
reason: flag,
|
||||
};
|
||||
}
|
||||
const fromEnv = (env.OMNIROUTE_GATE_MODE || "").trim();
|
||||
if (fromEnv) {
|
||||
return {
|
||||
mode: assertMode(fromEnv, "OMNIROUTE_GATE_MODE"),
|
||||
source: "env",
|
||||
reason: `OMNIROUTE_GATE_MODE=${fromEnv}`,
|
||||
};
|
||||
}
|
||||
return { ...detectGateMode(env), source: "auto" };
|
||||
}
|
||||
|
||||
/** @returns {"pr" | "release"} */
|
||||
export function resolveGateMode(opts = {}) {
|
||||
return resolveGateModeInfo(opts).mode;
|
||||
}
|
||||
|
||||
/** One log fragment, e.g. `mode=pr (auto: pull_request)`. */
|
||||
export function describeGateMode(info) {
|
||||
return `mode=${info.mode} (${info.source}: ${info.reason})`;
|
||||
}
|
||||
|
||||
function git(args, cwd) {
|
||||
return execFileSync("git", args, {
|
||||
cwd,
|
||||
encoding: "utf8",
|
||||
stdio: ["ignore", "pipe", "ignore"],
|
||||
}).trim();
|
||||
}
|
||||
|
||||
function tryGit(args, cwd) {
|
||||
try {
|
||||
return git(args, cwd);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function packageVersion(cwd) {
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(path.join(cwd, "package.json"), "utf8")).version || null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Base refs worth trying, most specific first: the base SHA the workflow passes, an explicit
|
||||
* BASE_REF, the PR's base branch, and finally the active release line of package.json.
|
||||
*/
|
||||
export function baseRefCandidates(env = process.env, cwd = process.cwd()) {
|
||||
const out = [];
|
||||
for (const value of [env.BASE_SHA, env.GITHUB_BASE_SHA, env.BASE_REF]) {
|
||||
if (value && value.trim()) out.push(value.trim());
|
||||
}
|
||||
if (env.GITHUB_BASE_REF) out.push(`origin/${env.GITHUB_BASE_REF}`);
|
||||
const version = packageVersion(cwd);
|
||||
if (version && /^\d+\.\d+\.\d+$/.test(version)) out.push(`origin/release/v${version}`);
|
||||
return [...new Set(out)];
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge base between HEAD and the first resolvable candidate, or null (shallow clone, unknown
|
||||
* ref). Callers SKIP their diff-based check on null, like the other diff-aware gates do.
|
||||
* @returns {{ sha: string, ref: string } | null}
|
||||
*/
|
||||
export function resolvePrDiffBase({ env = process.env, cwd = process.cwd() } = {}) {
|
||||
for (const ref of baseRefCandidates(env, cwd)) {
|
||||
if (!tryGit(["rev-parse", "--verify", "--quiet", `${ref}^{commit}`], cwd)) continue;
|
||||
const sha = tryGit(["merge-base", "HEAD", ref], cwd);
|
||||
if (sha) return { sha, ref };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Paths the change touches relative to `base` (a commit). Renames count on both sides, so
|
||||
* moving a file into or out of a guarded tree is visible. With `includeWorktree` the staged,
|
||||
* unstaged and untracked files of a local checkout are added — what a developer is about to
|
||||
* commit is judged the same way CI will judge it.
|
||||
* @returns {string[]} sorted, unique, repo-relative POSIX paths
|
||||
*/
|
||||
export function listChangedFiles(base, { cwd = process.cwd(), includeWorktree = false } = {}) {
|
||||
const lines = git(["diff", "--name-only", "--no-renames", base, "HEAD"], cwd).split("\n");
|
||||
if (includeWorktree) {
|
||||
lines.push(...git(["diff", "--name-only", "--no-renames", "HEAD"], cwd).split("\n"));
|
||||
lines.push(...git(["ls-files", "--others", "--exclude-standard"], cwd).split("\n"));
|
||||
}
|
||||
return [...new Set(lines.map((line) => line.trim()).filter(Boolean))].sort();
|
||||
}
|
||||
|
||||
/** Current head branch: the PR head in Actions, otherwise the checked-out branch. */
|
||||
export function resolveHeadBranch({ env = process.env, cwd = process.cwd() } = {}) {
|
||||
if (env.GITHUB_HEAD_REF) return env.GITHUB_HEAD_REF;
|
||||
if (env.GITHUB_REF_NAME && env.GITHUB_EVENT_NAME === "push") return env.GITHUB_REF_NAME;
|
||||
const branch = tryGit(["rev-parse", "--abbrev-ref", "HEAD"], cwd);
|
||||
return branch && branch !== "HEAD" ? branch : "";
|
||||
}
|
||||
305
tests/unit/check-pr-derived-paths.test.ts
Normal file
305
tests/unit/check-pr-derived-paths.test.ts
Normal file
@@ -0,0 +1,305 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import test from "node:test";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import {
|
||||
categoryOf,
|
||||
evaluateDerivedPaths,
|
||||
globToRegExp,
|
||||
loadFamilies,
|
||||
main,
|
||||
normalizeFamily,
|
||||
} from "../../scripts/check/check-pr-derived-paths.mjs";
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
|
||||
|
||||
const translation = normalizeFamily(
|
||||
{
|
||||
family: "translation",
|
||||
writers: ["release/v*", "docs/i18n-*", "chore/i18n-*", "chore/derived-*"],
|
||||
companions: ["changelog.d/**"],
|
||||
categories: [
|
||||
{
|
||||
id: "ui-locale-catalogs",
|
||||
paths: ["src/i18n/messages/*.json"],
|
||||
except: ["src/i18n/messages/en.json"],
|
||||
refreshedBy: "sync-ui-keys",
|
||||
},
|
||||
{ id: "docs-i18n-mirrors", paths: ["docs/i18n/**", ".i18n-state.json"] },
|
||||
],
|
||||
},
|
||||
"inline"
|
||||
);
|
||||
|
||||
test("glob: * stays in one segment, ** crosses directories", () => {
|
||||
assert.ok(globToRegExp("src/i18n/messages/*.json").test("src/i18n/messages/pt-BR.json"));
|
||||
assert.ok(!globToRegExp("src/i18n/messages/*.json").test("src/i18n/messages/sub/pt-BR.json"));
|
||||
assert.ok(globToRegExp("docs/i18n/**").test("docs/i18n/pt-BR/docs/guides/X.md"));
|
||||
assert.ok(globToRegExp("docs/**/*.svg").test("docs/a.svg"));
|
||||
assert.ok(globToRegExp("docs/**/*.svg").test("docs/diagrams/x/a.svg"));
|
||||
assert.ok(!globToRegExp("release/v*").test("release-notes/v1"));
|
||||
assert.ok(globToRegExp("release/v*").test("release/v3.8.55"));
|
||||
assert.ok(!globToRegExp("a.b").test("axb"), "dots are literal");
|
||||
});
|
||||
|
||||
test("en.json is the source, never a derived file", () => {
|
||||
assert.equal(categoryOf("src/i18n/messages/en.json", translation), null);
|
||||
assert.equal(categoryOf("src/i18n/messages/ko.json", translation)?.id, "ui-locale-catalogs");
|
||||
assert.equal(categoryOf(".i18n-state.json", translation)?.id, "docs-i18n-mirrors");
|
||||
});
|
||||
|
||||
test("a feature PR that also edits locale catalogs and mirrors fails, one entry per category", () => {
|
||||
const { violations } = evaluateDerivedPaths({
|
||||
files: [
|
||||
"src/app/x.tsx",
|
||||
"src/i18n/messages/en.json",
|
||||
"src/i18n/messages/ko.json",
|
||||
"src/i18n/messages/pt-BR.json",
|
||||
"docs/i18n/ko/llm.txt",
|
||||
],
|
||||
branch: "feat/thing",
|
||||
families: [translation],
|
||||
});
|
||||
assert.deepEqual(
|
||||
violations.map((v) => [v.category, v.files]),
|
||||
[
|
||||
["ui-locale-catalogs", ["src/i18n/messages/ko.json", "src/i18n/messages/pt-BR.json"]],
|
||||
["docs-i18n-mirrors", ["docs/i18n/ko/llm.txt"]],
|
||||
]
|
||||
);
|
||||
assert.equal(violations[0].refreshedBy, "sync-ui-keys");
|
||||
});
|
||||
|
||||
test("a feature PR that only touches en.json passes", () => {
|
||||
const result = evaluateDerivedPaths({
|
||||
files: ["src/app/x.tsx", "src/i18n/messages/en.json", "changelog.d/features/1-x.md"],
|
||||
branch: "feat/thing",
|
||||
families: [translation],
|
||||
});
|
||||
assert.deepEqual(result, { violations: [], allowed: [] });
|
||||
});
|
||||
|
||||
test("a translation-only PR (plus a changelog fragment) is allowed", () => {
|
||||
const { violations, allowed } = evaluateDerivedPaths({
|
||||
files: ["src/i18n/messages/ko.json", "changelog.d/fixes/9-ko.md"],
|
||||
branch: "fix/ko-wording",
|
||||
families: [translation],
|
||||
});
|
||||
assert.equal(violations.length, 0);
|
||||
assert.deepEqual(allowed, [
|
||||
{ family: "translation", reason: "family-only", files: ["src/i18n/messages/ko.json"] },
|
||||
]);
|
||||
});
|
||||
|
||||
test("en.json next to locale edits is not a translation-only PR", () => {
|
||||
const { violations } = evaluateDerivedPaths({
|
||||
files: ["src/i18n/messages/en.json", "src/i18n/messages/ko.json"],
|
||||
branch: "fix/ko-wording",
|
||||
families: [translation],
|
||||
});
|
||||
assert.equal(violations.length, 1);
|
||||
});
|
||||
|
||||
test("writer branches may mix derived files with anything", () => {
|
||||
for (const branch of [
|
||||
"release/v3.8.55",
|
||||
"docs/i18n-wave-1113",
|
||||
"chore/i18n-mirror-refresh",
|
||||
"chore/derived-refresh",
|
||||
]) {
|
||||
const { violations, allowed } = evaluateDerivedPaths({
|
||||
files: ["AGENTS.md", "docs/i18n/bs/AGENTS.md"],
|
||||
branch,
|
||||
families: [translation],
|
||||
});
|
||||
assert.equal(violations.length, 0, branch);
|
||||
assert.equal(allowed[0].reason, "writer", branch);
|
||||
}
|
||||
});
|
||||
|
||||
test("config validation names the file and the field", () => {
|
||||
assert.throws(
|
||||
() => normalizeFamily({ family: "x", categories: [] }, "f.json"),
|
||||
/f\.json: categories/
|
||||
);
|
||||
assert.throws(
|
||||
() => normalizeFamily({ family: "x", categories: [{ id: "a", paths: [] }] }, "f.json"),
|
||||
/paths must not be empty/
|
||||
);
|
||||
assert.throws(
|
||||
() =>
|
||||
normalizeFamily(
|
||||
{
|
||||
family: "x",
|
||||
categories: [
|
||||
{ id: "a", paths: ["x"] },
|
||||
{ id: "a", paths: ["y"] },
|
||||
],
|
||||
},
|
||||
"f.json"
|
||||
),
|
||||
/duplicate category id "a"/
|
||||
);
|
||||
assert.throws(
|
||||
() =>
|
||||
normalizeFamily({
|
||||
family: "x",
|
||||
writers: "release/*",
|
||||
categories: [{ id: "a", paths: ["x"] }],
|
||||
}),
|
||||
/writers/
|
||||
);
|
||||
});
|
||||
|
||||
test("the checked-in families load and keep en.json out of every category", () => {
|
||||
const families = loadFamilies(root);
|
||||
for (const family of families) {
|
||||
for (const source of [
|
||||
"src/i18n/messages/en.json",
|
||||
"bin/cli/locales/en.json",
|
||||
"llm.txt",
|
||||
"AGENTS.md",
|
||||
]) {
|
||||
assert.equal(
|
||||
categoryOf(source, family),
|
||||
null,
|
||||
`${family.family} claims the source ${source}`
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
function gitIn(dir: string, ...args: string[]) {
|
||||
return execFileSync("git", args, {
|
||||
cwd: dir,
|
||||
encoding: "utf8",
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
}).trim();
|
||||
}
|
||||
|
||||
function withRepo(fn: (dir: string, baseSha: string) => void) {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "derived-paths-"));
|
||||
try {
|
||||
gitIn(dir, "init", "-q", "-b", "base");
|
||||
gitIn(dir, "config", "user.email", "test@example.invalid");
|
||||
gitIn(dir, "config", "user.name", "test");
|
||||
gitIn(dir, "config", "commit.gpgsign", "false");
|
||||
fs.mkdirSync(path.join(dir, "config/quality/derived-paths"), { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(dir, "config/quality/derived-paths/translation.json"),
|
||||
JSON.stringify({
|
||||
family: "translation",
|
||||
writers: ["docs/i18n-*"],
|
||||
categories: [{ id: "docs-i18n-mirrors", paths: ["docs/i18n/**"] }],
|
||||
})
|
||||
);
|
||||
fs.writeFileSync(path.join(dir, "app.ts"), "1\n");
|
||||
gitIn(dir, "add", "-A");
|
||||
gitIn(dir, "commit", "-q", "-m", "base");
|
||||
const baseSha = gitIn(dir, "rev-parse", "HEAD");
|
||||
gitIn(dir, "checkout", "-q", "-b", "feat/x");
|
||||
fn(dir, baseSha);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
function quiet<T>(fn: () => T): T {
|
||||
const { log, error } = console;
|
||||
console.log = () => {};
|
||||
console.error = () => {};
|
||||
try {
|
||||
return fn();
|
||||
} finally {
|
||||
console.log = log;
|
||||
console.error = error;
|
||||
}
|
||||
}
|
||||
|
||||
test("main: pr mode fails a feature commit that edits a mirror; --warn reports and passes", () => {
|
||||
withRepo((dir, baseSha) => {
|
||||
fs.writeFileSync(path.join(dir, "app.ts"), "2\n");
|
||||
fs.mkdirSync(path.join(dir, "docs/i18n/ko"), { recursive: true });
|
||||
fs.writeFileSync(path.join(dir, "docs/i18n/ko/llm.txt"), "x\n");
|
||||
gitIn(dir, "add", "-A");
|
||||
gitIn(dir, "commit", "-q", "-m", "feat");
|
||||
const env = { CI: "1", BASE_SHA: baseSha };
|
||||
assert.equal(
|
||||
quiet(() => main(["--mode=pr"], env, dir)),
|
||||
1
|
||||
);
|
||||
assert.equal(
|
||||
quiet(() => main(["--mode=pr", "--warn"], env, dir)),
|
||||
0
|
||||
);
|
||||
assert.equal(
|
||||
quiet(() => main(["--mode=pr", "--branch=docs/i18n-wave-1"], env, dir)),
|
||||
0
|
||||
);
|
||||
assert.equal(
|
||||
quiet(() => main(["--mode=release"], env, dir)),
|
||||
0,
|
||||
"release mode never judges"
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
test("main: unresolved base is a SKIP, not a pass by accident of an empty diff", () => {
|
||||
withRepo((dir) => {
|
||||
const lines: string[] = [];
|
||||
const { log } = console;
|
||||
console.log = (line: string) => lines.push(line);
|
||||
try {
|
||||
assert.equal(main(["--mode=pr"], { CI: "1", BASE_REF: "nope" }, dir), 0);
|
||||
} finally {
|
||||
console.log = log;
|
||||
}
|
||||
assert.match(lines.join("\n"), /SKIP reason=base-unresolved/);
|
||||
});
|
||||
});
|
||||
|
||||
test("main: --files reads an explicit change list (the classify-pr-changes format)", () => {
|
||||
withRepo((dir) => {
|
||||
const list = path.join(dir, "changed.txt");
|
||||
fs.writeFileSync(list, "app.ts\ndocs/i18n/ko/README.md\n");
|
||||
assert.equal(
|
||||
quiet(() => main(["--mode=pr", `--files=${list}`, "--branch=feat/x"], { CI: "1" }, dir)),
|
||||
1
|
||||
);
|
||||
fs.writeFileSync(list, "docs/i18n/ko/README.md\n");
|
||||
assert.equal(
|
||||
quiet(() => main(["--mode=pr", `--files=${list}`, "--branch=feat/x"], { CI: "1" }, dir)),
|
||||
0
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
test("main: queue batches are skipped — each PR in them was judged on its own", () => {
|
||||
withRepo((dir, baseSha) => {
|
||||
fs.writeFileSync(path.join(dir, "app.ts"), "2\n");
|
||||
fs.mkdirSync(path.join(dir, "docs/i18n/ko"), { recursive: true });
|
||||
fs.writeFileSync(path.join(dir, "docs/i18n/ko/llm.txt"), "x\n");
|
||||
gitIn(dir, "add", "-A");
|
||||
gitIn(dir, "commit", "-q", "-m", "batch");
|
||||
const env = { CI: "1", BASE_SHA: baseSha };
|
||||
for (const branch of [
|
||||
"mergify/merge-queue/abc",
|
||||
"omni-queue/release/v3.8.54/1",
|
||||
"gh-readonly-queue/main/pr-1",
|
||||
]) {
|
||||
assert.equal(
|
||||
quiet(() => main(["--mode=pr", `--branch=${branch}`], env, dir)),
|
||||
0,
|
||||
branch
|
||||
);
|
||||
}
|
||||
assert.equal(
|
||||
quiet(() => main(["--mode=pr"], { ...env, GITHUB_EVENT_NAME: "merge_group" }, dir)),
|
||||
0
|
||||
);
|
||||
});
|
||||
});
|
||||
138
tests/unit/gate-mode.test.ts
Normal file
138
tests/unit/gate-mode.test.ts
Normal file
@@ -0,0 +1,138 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import test from "node:test";
|
||||
|
||||
import {
|
||||
baseRefCandidates,
|
||||
describeGateMode,
|
||||
detectGateMode,
|
||||
listChangedFiles,
|
||||
resolveGateMode,
|
||||
resolveGateModeInfo,
|
||||
resolveHeadBranch,
|
||||
resolvePrDiffBase,
|
||||
} from "../../scripts/check/lib/gateMode.mjs";
|
||||
|
||||
const noArgs = ["node", "script"];
|
||||
|
||||
test("pull_request from a feature branch is pr mode", () => {
|
||||
const env = { GITHUB_EVENT_NAME: "pull_request", GITHUB_HEAD_REF: "feat/x" };
|
||||
assert.equal(resolveGateMode({ argv: noArgs, env }), "pr");
|
||||
assert.equal(
|
||||
resolveGateMode({ argv: noArgs, env: { ...env, GITHUB_EVENT_NAME: "pull_request_target" } }),
|
||||
"pr"
|
||||
);
|
||||
});
|
||||
|
||||
test("the release PR (release/v* → main) is release mode", () => {
|
||||
const env = { GITHUB_EVENT_NAME: "pull_request", GITHUB_HEAD_REF: "release/v3.8.54" };
|
||||
assert.equal(resolveGateMode({ argv: noArgs, env }), "release");
|
||||
});
|
||||
|
||||
test("queue batches are pr mode: merge_group and push to omni-queue/**", () => {
|
||||
assert.equal(detectGateMode({ GITHUB_EVENT_NAME: "merge_group" }).mode, "pr");
|
||||
assert.equal(
|
||||
detectGateMode({ GITHUB_EVENT_NAME: "push", GITHUB_REF_NAME: "omni-queue/release/v3.8.54/7" })
|
||||
.mode,
|
||||
"pr"
|
||||
);
|
||||
});
|
||||
|
||||
test("push, schedule, dispatch and local runs stay strict (release)", () => {
|
||||
for (const env of [
|
||||
{ GITHUB_EVENT_NAME: "push", GITHUB_REF_NAME: "main" },
|
||||
{ GITHUB_EVENT_NAME: "push", GITHUB_REF_NAME: "release/v3.8.54" },
|
||||
{ GITHUB_EVENT_NAME: "schedule" },
|
||||
{ GITHUB_EVENT_NAME: "workflow_dispatch" },
|
||||
{},
|
||||
]) {
|
||||
assert.equal(resolveGateMode({ argv: noArgs, env }), "release", JSON.stringify(env));
|
||||
}
|
||||
});
|
||||
|
||||
test("--mode beats OMNIROUTE_GATE_MODE, which beats the event", () => {
|
||||
const env = {
|
||||
GITHUB_EVENT_NAME: "pull_request",
|
||||
GITHUB_HEAD_REF: "feat/x",
|
||||
OMNIROUTE_GATE_MODE: "release",
|
||||
};
|
||||
assert.deepEqual(resolveGateModeInfo({ argv: noArgs, env }).source, "env");
|
||||
assert.equal(resolveGateMode({ argv: noArgs, env }), "release");
|
||||
const info = resolveGateModeInfo({ argv: [...noArgs, "--mode=pr"], env });
|
||||
assert.equal(info.mode, "pr");
|
||||
assert.equal(info.source, "flag");
|
||||
assert.match(describeGateMode(info), /^mode=pr \(flag: --mode=pr\)$/);
|
||||
});
|
||||
|
||||
test("an invalid mode is an error, never a silent default", () => {
|
||||
assert.throws(
|
||||
() => resolveGateMode({ argv: [...noArgs, "--mode=strict"], env: {} }),
|
||||
/invalid gate mode "strict"/
|
||||
);
|
||||
assert.throws(
|
||||
() => resolveGateMode({ argv: noArgs, env: { OMNIROUTE_GATE_MODE: "loose" } }),
|
||||
/OMNIROUTE_GATE_MODE/
|
||||
);
|
||||
});
|
||||
|
||||
test("base candidates keep the documented order and drop duplicates", () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "gate-mode-pkg-"));
|
||||
try {
|
||||
fs.writeFileSync(path.join(dir, "package.json"), JSON.stringify({ version: "3.8.54" }));
|
||||
const env = {
|
||||
BASE_SHA: "abc",
|
||||
GITHUB_BASE_SHA: "abc",
|
||||
BASE_REF: "origin/x",
|
||||
GITHUB_BASE_REF: "release/v3.8.54",
|
||||
};
|
||||
assert.deepEqual(baseRefCandidates(env, dir), ["abc", "origin/x", "origin/release/v3.8.54"]);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
function gitIn(dir: string, ...args: string[]) {
|
||||
return execFileSync("git", args, {
|
||||
cwd: dir,
|
||||
encoding: "utf8",
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
}).trim();
|
||||
}
|
||||
|
||||
test("merge base and changed files come from git, renames count on both sides", () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "gate-mode-git-"));
|
||||
try {
|
||||
gitIn(dir, "init", "-q", "-b", "base");
|
||||
gitIn(dir, "config", "user.email", "test@example.invalid");
|
||||
gitIn(dir, "config", "user.name", "test");
|
||||
gitIn(dir, "config", "commit.gpgsign", "false");
|
||||
fs.writeFileSync(path.join(dir, "a.txt"), "a\n");
|
||||
fs.writeFileSync(path.join(dir, "old.txt"), "old\n");
|
||||
gitIn(dir, "add", "-A");
|
||||
gitIn(dir, "commit", "-q", "-m", "base");
|
||||
const baseSha = gitIn(dir, "rev-parse", "HEAD");
|
||||
gitIn(dir, "checkout", "-q", "-b", "feat/x");
|
||||
fs.writeFileSync(path.join(dir, "a.txt"), "a2\n");
|
||||
gitIn(dir, "mv", "old.txt", "new.txt");
|
||||
gitIn(dir, "commit", "-q", "-am", "change");
|
||||
fs.writeFileSync(path.join(dir, "untracked.txt"), "u\n");
|
||||
|
||||
const base = resolvePrDiffBase({ env: { BASE_REF: "base" }, cwd: dir });
|
||||
assert.deepEqual(base, { sha: baseSha, ref: "base" });
|
||||
assert.equal(resolvePrDiffBase({ env: { BASE_REF: "does-not-exist" }, cwd: dir }), null);
|
||||
assert.deepEqual(listChangedFiles(baseSha, { cwd: dir }), ["a.txt", "new.txt", "old.txt"]);
|
||||
assert.deepEqual(listChangedFiles(baseSha, { cwd: dir, includeWorktree: true }), [
|
||||
"a.txt",
|
||||
"new.txt",
|
||||
"old.txt",
|
||||
"untracked.txt",
|
||||
]);
|
||||
assert.equal(resolveHeadBranch({ env: {}, cwd: dir }), "feat/x");
|
||||
assert.equal(resolveHeadBranch({ env: { GITHUB_HEAD_REF: "fix/y" }, cwd: dir }), "fix/y");
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user