import type { CiJob, CiJobState, CiStepLog } from "@refs/backend/contract"; export type StepState = "pending" | "running" | "succeeded" | "failed" | "cancelled" | "skipped"; export interface StepView { readonly step: number; readonly name: string; readonly state: StepState; readonly lines: readonly string[]; readonly startedAt: number | null; readonly endedAt: number | null; } const ENDED: readonly CiJobState[] = ["succeeded", "failed", "skipped", "cancelled", "timed_out"]; const ANSI = /\x1b\[[0-9;?]*[ -/]*[@-~]/g; /** * Splits a job's output into its steps, as GitHub Actions does: a setup step, then one per step of the job. A step * before the failed one succeeded, the failed one failed, and the ones after it never ran. In a running job, the last * step that started is running. */ export function stepViews(job: CiJob, logs: readonly CiStepLog[]): StepView[] { const byStep = new Map(logs.map((log) => [log.step, log])); const names = ["Set up job", ...job.steps]; const started = logs.filter((log) => log.startedAt !== null || log.text).map((log) => log.step); const reached = started.length ? Math.max(...started) : -1; const ended = ENDED.includes(job.state); const failedAt = job.state === "succeeded" ? null : (job.failedStep ?? (ended && reached >= 0 ? reached : null)); return names.map((name, step) => { const log = byStep.get(step); return { step, name, state: stateOf(step), lines: toLines(log?.text ?? ""), startedAt: log?.startedAt ?? null, endedAt: log?.endedAt ?? null }; }); function stateOf(step: number): StepState { if (!ended) return step < reached ? "succeeded" : step === reached && job.state === "running" ? "running" : "pending"; if (job.state === "succeeded") return "succeeded"; if (failedAt === null || step > failedAt) return "skipped"; if (step < failedAt) return "succeeded"; return job.state === "cancelled" ? "cancelled" : "failed"; } } function toLines(text: string): string[] { if (!text) return []; const lines = text.replace(ANSI, "").replace(/\r\n/g, "\n").split("\n"); if (lines.at(-1) === "") lines.pop(); return lines.map((line) => line.slice(line.lastIndexOf("\r") + 1)); }