문제:
PR 병합 뒤 refs/heads/main push run이 merge job 셋(merge_static,
merge_test, merge_browser)을 처음부터 다시 돈다. 최근 병합 대부분은
병합 커밋 트리가 PR head(HEAD^2) 트리와 같아 같은 입력을 두 번 돌고
있다.
고른 방법과 버린 대안:
- merge job 셋의 Frozen install 바로 뒤에 main-push-reuse step을
두고 checkout에 fetch-depth: 2를 준다.
- 여섯 조건(main push, 부모 둘 병합 커밋과 tree(HEAD)==tree(HEAD^2),
.nvmrc·pnpm-lock.yaml 무변경, HEAD^2 최신 pull_request run의 같은
job success, 그 job 로그가 비어 있지 않고 SKIPPED_GATE_LINE 형식
건너뜀 줄 없음, Gitea API 정상 읽기)이 모두 참일 때만 뒤 step
(글꼴·게이트·scripts/tests·증거 업로드)을 건너뛰고 건너뜀 한 줄로
성공 종료한다. 하나라도 모르거나 실패하면 전부 돈다(fail open).
- main_gate(FE-GATE-029·030)와 release·tag run은 건너뛰지 않는다.
- 버린 안: main에서 경로표 재계산(PR 기준과 HEAD^1 사이 되돌림 누락),
보호 규칙만 믿고 조건 4 생략(우회 병합 누락), 게이트 단위 건너뛰기
(D-1 범위 밖).
위험·한계:
- job 토큰(gitea.token)으로 Gitea 1.27의 actions/runs·jobs/logs API를
읽을 수 있는지는 첫 main push 로그로 확인한다. 403이면 조건 6이
모두 돌게 하므로 기존보다 나빠지지 않는다.
- 같은 트리의 두 번째 실행 표본이 줄어든다(D-3 판정용 재시도가 PR
안에서 흔들림 판정을 대신한다).
검증:
- laptop-gate tests/unit/{main-push-reuse,ci-workflow-generation,script-entry-guards}.test.ts rc=0
- laptop-gate check:types, lint, check:ci, verify:documentation rc=0
- scripts/verify.sh docs rc=0, scripts/verify.sh hooks rc=0 (112 tests)
Refs: CI-FE-0004
423 lines
14 KiB
TypeScript
423 lines
14 KiB
TypeScript
import { spawnSync } from "node:child_process";
|
|
|
|
import { SKIPPED_GATE_LINE } from "./pr-gate-selection.ts";
|
|
import { selectRepositoryPaths } from "./repository-layout.ts";
|
|
|
|
/**
|
|
* FE-1 (design-docs ci/03-time-reduction-plan.md 4.2 "FE-1 조건", D-1 (가)).
|
|
* When a push to refs/heads/main is a merge commit whose tree equals its
|
|
* pull-request head (HEAD^2), did not change dependency-cache key inputs
|
|
* (.nvmrc, pnpm-lock.yaml), and that PR head already passed the same merge job
|
|
* in Gitea Actions without skipping any gate, the merge job logs a skipped
|
|
* line and exits green without re-running its gates.
|
|
*
|
|
* Any missing, unreadable or ambiguous input fails open to running the job.
|
|
*/
|
|
|
|
export const DEFAULT_MAIN_PUSH_REUSE_TIMEOUT_MS = 15_000;
|
|
const WORKFLOW_FILE_PREFIX = "quality-gates.yml@";
|
|
const DEPENDENCY_CACHE_KEY_INPUTS = selectRepositoryPaths("dependency-cache-key");
|
|
const REPOSITORY_PATTERN = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u;
|
|
const SHA_PATTERN = /^[0-9a-f]{40}$/u;
|
|
const PR_REF_PATTERN = /refs\/pull\/(\d+)\//u;
|
|
|
|
export type MainPushReusePrJob =
|
|
| Readonly<{
|
|
runId: number;
|
|
prNumber: number;
|
|
conclusion: string;
|
|
status?: string | undefined;
|
|
log: string;
|
|
}>
|
|
| Readonly<{ error: string }>;
|
|
|
|
export type MainPushReuseInput = Readonly<{
|
|
event: string;
|
|
ref: string;
|
|
jobName: string;
|
|
parents: readonly string[];
|
|
headTree: string;
|
|
prHeadTree?: string | undefined;
|
|
lockOrNodeChanged: boolean;
|
|
prJob?: MainPushReusePrJob | undefined;
|
|
}>;
|
|
|
|
export type ReuseDecision =
|
|
| Readonly<{ reuse: true; line: string }>
|
|
| Readonly<{ reuse: false; reason: string }>;
|
|
|
|
export function mainPushReuse(input: MainPushReuseInput): ReuseDecision {
|
|
if (input.event !== "push" || input.ref !== "refs/heads/main") {
|
|
return { reuse: false, reason: "main push가 아님" };
|
|
}
|
|
if (input.parents.length !== 2) {
|
|
return { reuse: false, reason: "부모 둘인 병합 커밋이 아님" };
|
|
}
|
|
if (!input.headTree || !input.prHeadTree || input.prHeadTree !== input.headTree) {
|
|
return { reuse: false, reason: "트리가 PR head와 다름" };
|
|
}
|
|
if (input.lockOrNodeChanged) {
|
|
return { reuse: false, reason: "pnpm-lock.yaml 또는 .nvmrc가 바뀜" };
|
|
}
|
|
if (!input.prJob || "error" in input.prJob) {
|
|
return { reuse: false, reason: `PR run을 못 읽음: ${input.prJob?.error ?? "없음"}` };
|
|
}
|
|
if (input.prJob.status && input.prJob.status !== "completed" && input.prJob.status !== "success") {
|
|
return { reuse: false, reason: `PR run ${input.prJob.runId}의 이 job 상태가 ${input.prJob.status}` };
|
|
}
|
|
if (input.prJob.conclusion !== "success") {
|
|
return { reuse: false, reason: `PR run ${input.prJob.runId}의 이 job이 ${input.prJob.conclusion}` };
|
|
}
|
|
if (input.prJob.log.trim().length === 0) {
|
|
return { reuse: false, reason: `PR run ${input.prJob.runId}의 이 job 로그가 비어 있음` };
|
|
}
|
|
const skipped = input.prJob.log
|
|
.split(/\r?\n/u)
|
|
.some((line) => SKIPPED_GATE_LINE.test(line.replace(/^\S+Z /u, "")));
|
|
if (skipped) {
|
|
return { reuse: false, reason: `PR run ${input.prJob.runId}가 이 job의 게이트를 건너뜀` };
|
|
}
|
|
const line =
|
|
`건너뜀: ${input.jobName} — 트리 ${input.headTree.slice(0, 12)}가 ` +
|
|
`PR #${input.prJob.prNumber} run ${input.prJob.runId}에서 초록`;
|
|
if (!SKIPPED_GATE_LINE.test(line)) {
|
|
return { reuse: false, reason: `job 이름이 건너뜀 형식에 안 맞음: ${input.jobName}` };
|
|
}
|
|
return { reuse: true, line };
|
|
}
|
|
|
|
export type MainPushReuseGit = (
|
|
args: readonly string[],
|
|
) => Readonly<{ status: number | null; stdout: string; stderr: string }>;
|
|
|
|
const runGit: MainPushReuseGit = (args) => {
|
|
const result = spawnSync("git", args, { encoding: "utf8" });
|
|
return { status: result.status, stdout: result.stdout ?? "", stderr: result.stderr ?? "" };
|
|
};
|
|
|
|
export type MainPushReuseFetch = (
|
|
input: string,
|
|
init?: RequestInit,
|
|
) => Promise<Pick<Response, "ok" | "status" | "json" | "text">>;
|
|
|
|
type GiteaWorkflowRun = Readonly<{
|
|
id?: unknown;
|
|
event?: unknown;
|
|
head_sha?: unknown;
|
|
path?: unknown;
|
|
ref?: unknown;
|
|
pull_requests?: unknown;
|
|
}>;
|
|
|
|
type GiteaActionJob = Readonly<{
|
|
id?: unknown;
|
|
name?: unknown;
|
|
status?: unknown;
|
|
conclusion?: unknown;
|
|
}>;
|
|
|
|
function extractPrNumber(run: GiteaWorkflowRun): number | undefined {
|
|
if (Array.isArray(run.pull_requests)) {
|
|
for (const entry of run.pull_requests) {
|
|
if (
|
|
entry &&
|
|
typeof entry === "object" &&
|
|
"number" in entry &&
|
|
typeof entry.number === "number" &&
|
|
Number.isInteger(entry.number) &&
|
|
entry.number > 0
|
|
) {
|
|
return entry.number;
|
|
}
|
|
}
|
|
}
|
|
for (const candidate of [run.path, run.ref]) {
|
|
if (typeof candidate !== "string") continue;
|
|
const match = PR_REF_PATTERN.exec(candidate);
|
|
if (!match) continue;
|
|
const parsed = Number.parseInt(match[1]!, 10);
|
|
if (Number.isInteger(parsed) && parsed > 0) return parsed;
|
|
}
|
|
return undefined;
|
|
}
|
|
|
|
function formatFetchError(label: string, error: unknown): string {
|
|
if (error instanceof Error) {
|
|
if (error.name === "TimeoutError" || error.name === "AbortError") {
|
|
return `${label} 시간 초과`;
|
|
}
|
|
return `${label} 호출 실패: ${error.message}`;
|
|
}
|
|
return `${label} 호출 실패`;
|
|
}
|
|
|
|
async function fetchWithTimeout(
|
|
fetcher: MainPushReuseFetch,
|
|
url: string,
|
|
token: string,
|
|
accept: string,
|
|
timeoutMs: number,
|
|
label: string,
|
|
): Promise<Readonly<{ response: Pick<Response, "ok" | "status" | "json" | "text"> } | { error: string }>> {
|
|
try {
|
|
const response = await fetcher(url, {
|
|
method: "GET",
|
|
headers: {
|
|
Authorization: `token ${token}`,
|
|
Accept: accept,
|
|
},
|
|
signal: AbortSignal.timeout(timeoutMs),
|
|
});
|
|
if (!response.ok) {
|
|
return { error: `${label} HTTP ${response.status}` };
|
|
}
|
|
return { response };
|
|
} catch (error) {
|
|
return { error: formatFetchError(label, error) };
|
|
}
|
|
}
|
|
|
|
export async function fetchPrJobForMainPushReuse(
|
|
options: Readonly<{
|
|
apiBaseUrl: string;
|
|
repository: string;
|
|
token: string;
|
|
prHeadSha: string;
|
|
jobName: string;
|
|
fetcher?: MainPushReuseFetch | undefined;
|
|
timeoutMs?: number | undefined;
|
|
}>,
|
|
): Promise<MainPushReusePrJob> {
|
|
const fetcher = options.fetcher ?? globalThis.fetch;
|
|
const timeoutMs = options.timeoutMs ?? DEFAULT_MAIN_PUSH_REUSE_TIMEOUT_MS;
|
|
const base = options.apiBaseUrl.replace(/\/+$/u, "");
|
|
if (!/^https?:\/\/[^/\s]+/u.test(base)) {
|
|
return { error: `API 주소가 올바르지 않음: ${options.apiBaseUrl || "(비어 있음)"}` };
|
|
}
|
|
if (!REPOSITORY_PATTERN.test(options.repository)) {
|
|
return { error: `저장소 이름이 올바르지 않음: ${options.repository || "(비어 있음)"}` };
|
|
}
|
|
if (options.token.trim().length === 0) {
|
|
return { error: "GITEA_TOKEN이 없음" };
|
|
}
|
|
if (!SHA_PATTERN.test(options.prHeadSha)) {
|
|
return { error: `PR head SHA가 올바르지 않음: ${options.prHeadSha}` };
|
|
}
|
|
|
|
const repoBase = `${base}/repos/${options.repository}`;
|
|
const runsResult = await fetchWithTimeout(
|
|
fetcher,
|
|
`${repoBase}/actions/runs?head_sha=${encodeURIComponent(options.prHeadSha)}&event=pull_request`,
|
|
options.token,
|
|
"application/json",
|
|
timeoutMs,
|
|
"actions/runs",
|
|
);
|
|
if ("error" in runsResult) return runsResult;
|
|
|
|
let runsPayload: unknown;
|
|
try {
|
|
runsPayload = await runsResult.response.json();
|
|
} catch (error) {
|
|
return { error: formatFetchError("actions/runs JSON", error) };
|
|
}
|
|
const rawRuns =
|
|
runsPayload && typeof runsPayload === "object" && "workflow_runs" in runsPayload && Array.isArray(runsPayload.workflow_runs)
|
|
? (runsPayload.workflow_runs as GiteaWorkflowRun[])
|
|
: undefined;
|
|
if (!rawRuns) {
|
|
return { error: "actions/runs 응답에 workflow_runs 배열이 없음" };
|
|
}
|
|
|
|
const matchingRuns = rawRuns
|
|
.filter((run) => {
|
|
if (typeof run.id !== "number" || !Number.isInteger(run.id) || run.id <= 0) return false;
|
|
if (run.event !== "pull_request") return false;
|
|
if (run.head_sha !== options.prHeadSha) return false;
|
|
if (typeof run.path === "string" && run.path.length > 0 && !run.path.startsWith(WORKFLOW_FILE_PREFIX)) {
|
|
return false;
|
|
}
|
|
return true;
|
|
})
|
|
.sort((left, right) => (right.id as number) - (left.id as number));
|
|
|
|
const latestRun = matchingRuns[0];
|
|
if (!latestRun) {
|
|
return { error: `head_sha ${options.prHeadSha.slice(0, 12)}의 pull_request run이 없음` };
|
|
}
|
|
const runId = latestRun.id as number;
|
|
const prNumber = extractPrNumber(latestRun);
|
|
if (prNumber === undefined) {
|
|
return { error: `PR run ${runId}에서 PR 번호를 찾지 못함` };
|
|
}
|
|
|
|
const jobsResult = await fetchWithTimeout(
|
|
fetcher,
|
|
`${repoBase}/actions/runs/${runId}/jobs?limit=50`,
|
|
options.token,
|
|
"application/json",
|
|
timeoutMs,
|
|
`actions/runs/${runId}/jobs`,
|
|
);
|
|
if ("error" in jobsResult) return jobsResult;
|
|
|
|
let jobsPayload: unknown;
|
|
try {
|
|
jobsPayload = await jobsResult.response.json();
|
|
} catch (error) {
|
|
return { error: formatFetchError(`actions/runs/${runId}/jobs JSON`, error) };
|
|
}
|
|
const rawJobs =
|
|
jobsPayload && typeof jobsPayload === "object" && "jobs" in jobsPayload && Array.isArray(jobsPayload.jobs)
|
|
? (jobsPayload.jobs as GiteaActionJob[])
|
|
: undefined;
|
|
if (!rawJobs) {
|
|
return { error: `PR run ${runId}의 jobs 응답에 jobs 배열이 없음` };
|
|
}
|
|
|
|
const matchingJobs = rawJobs.filter(
|
|
(job) => job.name === options.jobName && typeof job.id === "number" && Number.isInteger(job.id) && job.id > 0,
|
|
);
|
|
if (matchingJobs.length !== 1) {
|
|
return { error: `PR run ${runId}에서 job "${options.jobName}"을 ${matchingJobs.length}건 찾음` };
|
|
}
|
|
const job = matchingJobs[0]!;
|
|
const status = typeof job.status === "string" ? job.status : undefined;
|
|
const conclusion = typeof job.conclusion === "string" && job.conclusion.length > 0 ? job.conclusion : (status ?? "unknown");
|
|
if ((status && status !== "completed" && status !== "success") || conclusion !== "success") {
|
|
return { runId, prNumber, status, conclusion, log: "" };
|
|
}
|
|
|
|
const logResult = await fetchWithTimeout(
|
|
fetcher,
|
|
`${repoBase}/actions/jobs/${job.id as number}/logs`,
|
|
options.token,
|
|
"text/plain",
|
|
timeoutMs,
|
|
`actions/jobs/${job.id as number}/logs`,
|
|
);
|
|
if ("error" in logResult) return logResult;
|
|
|
|
let logText: string;
|
|
try {
|
|
logText = await logResult.response.text();
|
|
} catch (error) {
|
|
return { error: formatFetchError(`actions/jobs/${job.id as number}/logs 본문`, error) };
|
|
}
|
|
return { runId, prNumber, status, conclusion, log: logText };
|
|
}
|
|
|
|
export function resolveApiBaseUrl(environment: NodeJS.ProcessEnv): string {
|
|
const direct = environment["GITHUB_API_URL"] ?? environment["GITEA_API_URL"];
|
|
if (direct && direct.trim().length > 0) return direct.trim().replace(/\/+$/u, "");
|
|
const server = environment["GITHUB_SERVER_URL"] ?? environment["GITEA_SERVER_URL"];
|
|
if (server && server.trim().length > 0) return `${server.trim().replace(/\/+$/u, "")}/api/v1`;
|
|
return "";
|
|
}
|
|
|
|
export async function evaluateMainPushReuse(
|
|
options: Readonly<{
|
|
jobName: string;
|
|
environment?: NodeJS.ProcessEnv | undefined;
|
|
git?: MainPushReuseGit | undefined;
|
|
fetcher?: MainPushReuseFetch | undefined;
|
|
timeoutMs?: number | undefined;
|
|
cacheKeyInputs?: readonly string[] | undefined;
|
|
}>,
|
|
): Promise<ReuseDecision> {
|
|
const environment = options.environment ?? process.env;
|
|
const event = environment["GITHUB_EVENT_NAME"] ?? environment["GITEA_EVENT_NAME"] ?? "";
|
|
const ref = environment["GITHUB_REF"] ?? environment["GITEA_REF"] ?? "";
|
|
if (event !== "push" || ref !== "refs/heads/main") {
|
|
return mainPushReuse({
|
|
event,
|
|
ref,
|
|
jobName: options.jobName,
|
|
parents: [],
|
|
headTree: "",
|
|
lockOrNodeChanged: false,
|
|
});
|
|
}
|
|
|
|
const git = options.git ?? runGit;
|
|
const parentsResult = git(["rev-list", "--parents", "-n", "1", "HEAD"]);
|
|
if (parentsResult.status !== 0) {
|
|
return { reuse: false, reason: `git 부모 커밋을 읽지 못함: ${parentsResult.stderr.trim() || `rc=${parentsResult.status}`}` };
|
|
}
|
|
const [, ...parents] = parentsResult.stdout.trim().split(/\s+/u).filter(Boolean);
|
|
if (parents.length !== 2) {
|
|
return mainPushReuse({
|
|
event,
|
|
ref,
|
|
jobName: options.jobName,
|
|
parents,
|
|
headTree: "",
|
|
lockOrNodeChanged: false,
|
|
});
|
|
}
|
|
|
|
const headTreeResult = git(["rev-parse", "HEAD^{tree}"]);
|
|
const prHeadTreeResult = git(["rev-parse", "HEAD^2^{tree}"]);
|
|
if (headTreeResult.status !== 0 || prHeadTreeResult.status !== 0) {
|
|
return {
|
|
reuse: false,
|
|
reason: `git 트리를 읽지 못함: ${(headTreeResult.stderr || prHeadTreeResult.stderr).trim() || "fetch-depth 확인 필요"}`,
|
|
};
|
|
}
|
|
const headTree = headTreeResult.stdout.trim();
|
|
const prHeadTree = prHeadTreeResult.stdout.trim();
|
|
if (!headTree || !prHeadTree || headTree !== prHeadTree) {
|
|
return mainPushReuse({
|
|
event,
|
|
ref,
|
|
jobName: options.jobName,
|
|
parents,
|
|
headTree,
|
|
prHeadTree,
|
|
lockOrNodeChanged: false,
|
|
});
|
|
}
|
|
|
|
const cacheKeyInputs = options.cacheKeyInputs ?? DEPENDENCY_CACHE_KEY_INPUTS;
|
|
const diffResult = git(["diff", "--name-only", "HEAD^1", "HEAD", "--", ...cacheKeyInputs]);
|
|
if (diffResult.status !== 0) {
|
|
return {
|
|
reuse: false,
|
|
reason: `의존성 캐시 입력 변경 여부를 읽지 못함: ${diffResult.stderr.trim() || `rc=${diffResult.status}`}`,
|
|
};
|
|
}
|
|
const lockOrNodeChanged = diffResult.stdout.trim().length > 0;
|
|
if (lockOrNodeChanged) {
|
|
return mainPushReuse({
|
|
event,
|
|
ref,
|
|
jobName: options.jobName,
|
|
parents,
|
|
headTree,
|
|
prHeadTree,
|
|
lockOrNodeChanged,
|
|
});
|
|
}
|
|
|
|
const prJob = await fetchPrJobForMainPushReuse({
|
|
apiBaseUrl: resolveApiBaseUrl(environment),
|
|
repository: environment["GITHUB_REPOSITORY"] ?? environment["GITEA_REPOSITORY"] ?? "",
|
|
token: environment["GITEA_TOKEN"] ?? "",
|
|
prHeadSha: parents[1]!,
|
|
jobName: options.jobName,
|
|
fetcher: options.fetcher,
|
|
timeoutMs: options.timeoutMs,
|
|
});
|
|
|
|
return mainPushReuse({
|
|
event,
|
|
ref,
|
|
jobName: options.jobName,
|
|
parents,
|
|
headTree,
|
|
prHeadTree,
|
|
lockOrNodeChanged,
|
|
prJob,
|
|
});
|
|
}
|