48 lines · 2.2 KBRaw
| 1 | import type { CiJob, CiJobState, CiStepLog } from "@refs/backend/contract"; |
| 2 | |
| 3 | export type StepState = "pending" | "running" | "succeeded" | "failed" | "cancelled" | "skipped"; |
| 4 | |
| 5 | export interface StepView { |
| 6 | readonly step: number; |
| 7 | readonly name: string; |
| 8 | readonly state: StepState; |
| 9 | readonly lines: readonly string[]; |
| 10 | readonly startedAt: number | null; |
| 11 | readonly endedAt: number | null; |
| 12 | } |
| 13 | |
| 14 | const ENDED: readonly CiJobState[] = ["succeeded", "failed", "skipped", "cancelled", "timed_out"]; |
| 15 | const ANSI = /\x1b\[[0-9;?]*[ -/]*[@-~]/g; |
| 16 | |
| 17 | /** |
| 18 | * Splits a job's output into its steps, as GitHub Actions does: a setup step, then one per step of the job. A step |
| 19 | * before the failed one succeeded, the failed one failed, and the ones after it never ran. In a running job, the last |
| 20 | * step that started is running. |
| 21 | */ |
| 22 | export function stepViews(job: CiJob, logs: readonly CiStepLog[]): StepView[] { |
| 23 | const byStep = new Map(logs.map((log) => [log.step, log])); |
| 24 | const names = ["Set up job", ...job.steps]; |
| 25 | const started = logs.filter((log) => log.startedAt !== null || log.text).map((log) => log.step); |
| 26 | const reached = started.length ? Math.max(...started) : -1; |
| 27 | const ended = ENDED.includes(job.state); |
| 28 | const failedAt = job.state === "succeeded" ? null : (job.failedStep ?? (ended && reached >= 0 ? reached : null)); |
| 29 | return names.map((name, step) => { |
| 30 | const log = byStep.get(step); |
| 31 | return { step, name, state: stateOf(step), lines: toLines(log?.text ?? ""), startedAt: log?.startedAt ?? null, endedAt: log?.endedAt ?? null }; |
| 32 | }); |
| 33 | |
| 34 | function stateOf(step: number): StepState { |
| 35 | if (!ended) return step < reached ? "succeeded" : step === reached && job.state === "running" ? "running" : "pending"; |
| 36 | if (job.state === "succeeded") return "succeeded"; |
| 37 | if (failedAt === null || step > failedAt) return "skipped"; |
| 38 | if (step < failedAt) return "succeeded"; |
| 39 | return job.state === "cancelled" ? "cancelled" : "failed"; |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | function toLines(text: string): string[] { |
| 44 | if (!text) return []; |
| 45 | const lines = text.replace(ANSI, "").replace(/\r\n/g, "\n").split("\n"); |
| 46 | if (lines.at(-1) === "") lines.pop(); |
| 47 | return lines.map((line) => line.slice(line.lastIndexOf("\r") + 1)); |
| 48 | } |