import { spawnSync } from "node:child_process"; import { readFileSync } from "node:fs"; import path from "node:path"; import { z } from "zod"; /** * PR gate selection (design-docs ci/manual.md 4.3, owner decision 2026-11-13). * A PR run's merge job runs a merge gate only when the PR changed a file the * gate reads, by the path table `config/ci/pr-gate-selection.json`. Main and * release runs run every gate: what a PR skips, main still checks. * * The selection fails open: a file no row matches, a global file, an empty * diff or a diff that cannot be read selects every gate. */ export const PR_GATE_SELECTION_PATH = "config/ci/pr-gate-selection.json"; /** The PR's base branch; empty (or unset) outside pull_request runs. */ export const PR_BASE_REF_VARIABLE = "CI_PR_BASE_REF"; const GATE_ID = z.string().regex(/^FE-GATE-\d{3}$/u); const TABLE_SCHEMA = z .object({ $comment: z.string(), schemaVersion: z.literal(1), always: z.array(GATE_ID), global: z.array(z.string().min(1)), rules: z.array( z .object({ id: z.string().regex(/^[a-z][a-z-]*$/u), paths: z.array(z.string().min(1)).min(1), gates: z.array(GATE_ID).min(1), }) .strict(), ), }) .strict(); export type PrGateSelectionTable = z.infer; export function loadPrGateSelectionTable(root: string): PrGateSelectionTable { return TABLE_SCHEMA.parse(JSON.parse(readFileSync(path.join(root, PR_GATE_SELECTION_PATH), "utf8"))); } /** * A path pattern of the table as a regular expression: `**` is any run of * path segments, `*` and `?` stay within one segment. */ const compiledPatterns = new Map(); export function pathPatternRegExp(pattern: string): RegExp { const compiled = compiledPatterns.get(pattern); if (compiled) return compiled; let source = ""; for (let index = 0; index < pattern.length; index += 1) { const character = pattern[index]!; if (character === "*" && pattern[index + 1] === "*") { const slash = pattern[index + 2] === "/"; source += slash ? "(?:.*/)?" : ".*"; index += slash ? 2 : 1; } else if (character === "*") { source += "[^/]*"; } else if (character === "?") { source += "[^/]"; } else { source += character.replace(/[.+^${}()|[\]\\]/gu, "\\$&"); } } const expression = new RegExp(`^${source}$`, "u"); compiledPatterns.set(pattern, expression); return expression; } function matchesAny(file: string, patterns: readonly string[]): boolean { return patterns.some((pattern) => pathPatternRegExp(pattern).test(file)); } export type PrGateSelection = | Readonly<{ kind: "all"; reason: string }> | Readonly<{ kind: "subset"; gates: ReadonlySet; changed: number }>; /** Which merge gates a PR that changed `changedFiles` runs. */ export function selectPrGates(table: PrGateSelectionTable, changedFiles: readonly string[]): PrGateSelection { if (changedFiles.length === 0) return { kind: "all", reason: "바뀐 파일이 없음(diff를 확인하지 못함)" }; const gates = new Set(table.always); for (const file of changedFiles) { if (matchesAny(file, table.global)) return { kind: "all", reason: `전역 파일 ${file}이 바뀜` }; // The first row that matches decides: a document under src/ is a document. const rule = table.rules.find(({ paths }) => matchesAny(file, paths)); if (!rule) return { kind: "all", reason: `경로표의 어느 줄에도 안 걸리는 ${file}이 바뀜` }; for (const gate of rule.gates) gates.add(gate); } return { kind: "subset", gates, changed: changedFiles.length }; } /** The log line of a skipped gate (design-docs ci/manual.md 4.1 item 3). */ export function skippedGateLine(gateId: string, reason: string): string { return `건너뜀: ${gateId} — ${reason}`; } export const SKIPPED_GATE_LINE = /^건너뜀: (?:FE-GATE-\d{3}|merge \/ [a-z ]+) — \S.*$/u; type Git = (args: readonly string[]) => Readonly<{ status: number | null; stdout: string; stderr: string }>; const runGit: Git = (args) => { const result = spawnSync("git", args, { encoding: "utf8" }); return { status: result.status, stdout: result.stdout ?? "", stderr: result.stderr ?? "" }; }; /** * The files a PR changed against its base: `git diff --name-only` from the * merge base of `origin/` and HEAD. The checkout is shallow, so the base * branch and the history to the merge base are fetched first. */ export function prChangedFiles( baseRef: string, git: Git = runGit, ): Readonly<{ files: readonly string[] } | { error: string }> { if (!/^[\w./-]+$/u.test(baseRef)) return { error: `base 브랜치 이름이 이상함: ${baseRef}` }; const shallow = git(["rev-parse", "--is-shallow-repository"]).stdout.trim() === "true"; const fetch = git([ "fetch", "--no-tags", "--quiet", ...(shallow ? ["--unshallow"] : []), "origin", `+refs/heads/${baseRef}:refs/remotes/origin/${baseRef}`, ]); if (fetch.status !== 0) return { error: `base 브랜치를 받지 못함: ${fetch.stderr.trim()}` }; const base = git(["merge-base", `refs/remotes/origin/${baseRef}`, "HEAD"]); if (base.status !== 0) return { error: `merge base를 찾지 못함: ${base.stderr.trim()}` }; const diff = git(["diff", "--name-only", "--no-renames", base.stdout.trim(), "HEAD"]); if (diff.status !== 0) return { error: `diff를 읽지 못함: ${diff.stderr.trim()}` }; return { files: diff.stdout.split("\n").filter(Boolean) }; } /** * Why a PR run skips `gateId`, or undefined when it runs the gate. Outside a * pull_request run (no base ref) every gate runs. */ export function prGateSkipReason( gateId: string, environment: NodeJS.ProcessEnv, root: string, git: Git = runGit, ): string | undefined { const baseRef = environment[PR_BASE_REF_VARIABLE]; if (!baseRef) return undefined; const table = loadPrGateSelectionTable(root); const changed = prChangedFiles(baseRef, git); if ("error" in changed) { process.stdout.write(`PR 게이트 선택: 전부 돈다 — ${changed.error}\n`); return undefined; } const selection = selectPrGates(table, changed.files); if (selection.kind === "all") { process.stdout.write(`PR 게이트 선택: 전부 돈다 — ${selection.reason}\n`); return undefined; } return selection.gates.has(gateId) ? undefined : `바뀐 파일 ${selection.changed}개가 경로표(${PR_GATE_SELECTION_PATH})에서 이 게이트에 안 걸림`; }