Skip to content
303 linesCodeBlameRaw
1/**
2 * Pieces of the Actions pages: how a run, job or step stands, how long it
3 * took, and a job's log as GitHub shows one, with its groups folded and
4 * its errors and warnings marked.
5 */
6import { AlertTriangle, Ban, Check, ChevronRight, CircleDashed, CircleSlash, Clock, Hourglass, Info, Loader2, ShieldAlert, X } from "lucide-react";
7import { useEffect, useMemo, useRef, useState } from "react";
8import { Link } from "react-router";
9
10import type { CommitStatus, Conclusion, LogChunk, WorkflowNote } from "@g1t/contracts";
11
12import { Hint } from "./ui/hint";
13import { type Line, blocks, highlight, searchLog } from "../lib/log-lines";
14
15/**
16 * Where a run, job or step stands. `of` says which: a run's `pending` waits
17 * for its concurrency group and its `waiting` for its environments' rules,
18 * while a job's `pending` is held at its environment and its `waiting`
19 * waits for the jobs it needs. `environment` is the job's.
20 */
21type Standing = { status: string; conclusion: Conclusion | null; of?: "run" | "job"; environment?: string | null };
22
23/** Held until a person (or a wait timer) lets it through. */
24function heldWord({ status, of = "run", environment }: Standing): string | null {
25 if (of === "run" && status === "action_required") return "Approval required";
26 if (of === "run" && status === "waiting") return "Waiting for review";
27 if (of === "job" && status === "pending") return environment ? `Waiting to deploy to ${environment}` : "Waiting at its environment";
28 return null;
29}
30
31/** One icon for where a run, job or step stands. */
32export function StatusIcon({ status, conclusion, of = "run", environment, size = 16 }: Standing & { size?: number }) {
33 if (status === "in_progress") return <Loader2 size={size} className="shrink-0 animate-spin text-warn" aria-label="Running" />;
34 const held = heldWord({ status, conclusion, of, environment });
35 if (held)
36 return status === "action_required" ? (
37 <ShieldAlert size={size} className="shrink-0 text-warn" aria-label={held} />
38 ) : (
39 <Hourglass size={size} className="shrink-0 text-warn" aria-label={held} />
40 );
41 if (status !== "completed")
42 return <Clock size={size} className="shrink-0 text-faint" aria-label={status === "pending" ? "Waiting its turn" : "Queued"} />;
43 switch (conclusion) {
44 case "success":
45 return (
46 <span className="inline-flex shrink-0 rounded-full bg-success/15 p-0.5 text-success" aria-label="Succeeded">
47 <Check size={size - 4} strokeWidth={3} />
48 </span>
49 );
50 case "failure":
51 return (
52 <span className="inline-flex shrink-0 rounded-full bg-danger/15 p-0.5 text-danger" aria-label="Failed">
53 <X size={size - 4} strokeWidth={3} />
54 </span>
55 );
56 case "cancelled":
57 return <Ban size={size} className="shrink-0 text-faint" aria-label="Cancelled" />;
58 default:
59 return <CircleDashed size={size} className="shrink-0 text-faint" aria-label="Skipped" />;
60 }
61}
62
63export function standingWord(standing: Standing): string {
64 const { status, conclusion } = standing;
65 if (status === "in_progress") return "Running";
66 const held = heldWord(standing);
67 if (held) return held;
68 if (status === "pending") return "Waiting for its concurrency group";
69 if (status === "waiting") return "Waiting for the jobs it needs";
70 if (status === "calling") return "Running the workflow it calls";
71 if (status !== "completed") return "Queued";
72 return { success: "Succeeded", failure: "Failed", cancelled: "Cancelled", skipped: "Skipped" }[conclusion ?? "skipped"];
73}
74
75/** `1m 12s`, from two times, or from a start until now. */
76export function duration(start: string | null, end: string | null): string {
77 if (!start) return "";
78 const ms = (end ? new Date(end).getTime() : Date.now()) - new Date(start).getTime();
79 const seconds = Math.max(0, Math.round(ms / 1000));
80 if (seconds < 60) return `${seconds}s`;
81 const minutes = Math.floor(seconds / 60);
82 if (minutes < 60) return `${minutes}m ${seconds % 60}s`;
83 return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
84}
85
86/**
87 * How long something ran, as text. While it is still running the server and
88 * the browser count to a different now, so the text may differ on hydration
89 * (as TimeAgo's does).
90 */
91export function Duration({ start, end, className }: { start: string | null; end: string | null; className?: string }) {
92 return (
93 <span className={className} suppressHydrationWarning>
94 {duration(start, end)}
95 </span>
96 );
97}
98
99/** `main` from `refs/heads/main`, `v1.2` from a tag, `#12` for a pull request. */
100export function shortRef(ref: string): string {
101 const pull = /^refs\/pull\/(\d+)\//.exec(ref);
102 if (pull) return `#${pull[1]}`;
103 return ref.replace(/^refs\/(heads|tags)\//, "");
104}
105
106const LINE_STYLE: Record<Line["kind"], string> = {
107 text: "text-fg/85",
108 error: "text-danger",
109 warning: "text-warn",
110 notice: "text-accent",
111 debug: "text-faint",
112 command: "text-muted",
113};
114
115function LogLine({ line, number, query = "" }: { line: Line; number: number; query?: string }) {
116 const text = line.text.replace(/^(Error|Warning|Notice): /, "");
117 return (
118 <div className={`flex gap-4 px-4 hover:bg-raised/40 ${line.kind === "error" ? "bg-danger/5" : ""}`}>
119 <span className="w-8 shrink-0 select-none text-right text-faint/70">{number}</span>
120 <span className={`min-w-0 whitespace-pre-wrap break-all ${LINE_STYLE[line.kind]}`}>
121 {line.kind === "error" && <span className="font-semibold">Error: </span>}
122 {line.kind === "warning" && <span className="font-semibold">Warning: </span>}
123 {query
124 ? highlight(text, query).map((piece, index) =>
125 piece.match ? (
126 <mark key={index} className="rounded-sm bg-accent/30 text-fg">
127 {piece.text}
128 </mark>
129 ) : (
130 piece.text
131 ),
132 )
133 : text}
134 </span>
135 </div>
136 );
137}
138
139/**
140 * A step's log. With `query`, only the lines holding it (any case), groups
141 * opened, each match marked.
142 */
143export function LogText({ text, query = "" }: { text: string; query?: string }) {
144 const parsed = useMemo(() => blocks(text), [text]);
145 const found = useMemo(() => searchLog(text, query), [text, query]);
146 if (!text.trim()) return <p className="px-4 py-2 text-xs text-faint">No output.</p>;
147 if (query.trim()) {
148 return (
149 <div className="py-1 font-mono text-xs leading-5">
150 {found.map(({ line, number }) => (
151 <LogLine key={number} line={line} number={number} query={query} />
152 ))}
153 </div>
154 );
155 }
156 return (
157 <div className="py-1 font-mono text-xs leading-5">
158 {parsed.map((block, index) =>
159 block.kind === "line" ? (
160 <LogLine key={index} line={block.line} number={block.number} />
161 ) : (
162 <details key={index} className="group/log">
163 <summary className="flex cursor-pointer list-none items-center gap-1.5 px-4 text-fg/85 hover:bg-raised/40">
164 <span className="w-8 shrink-0" />
165 <ChevronRight size={12} className="shrink-0 text-faint transition-transform group-open/log:rotate-90" />
166 {block.title}
167 </summary>
168 {block.lines.map(({ line, number }) => (
169 <LogLine key={number} line={line} number={number} />
170 ))}
171 </details>
172 ),
173 )}
174 </div>
175 );
176}
177
178/**
179 * A job's log, fetched as it grows, split by step: `render` gets each
180 * step's text (0 is the job's setup).
181 */
182export function useJobLog(url: string, live: boolean): Map<number, string> {
183 const [chunks, setChunks] = useState<LogChunk[]>([]);
184 const after = useRef(0);
185 useEffect(() => {
186 after.current = 0;
187 setChunks([]);
188 }, [url]);
189 useEffect(() => {
190 let stopped = false;
191 let timer: ReturnType<typeof setTimeout> | undefined;
192 const load = async () => {
193 try {
194 // Pages of up to 500 chunks, until there is no more for now.
195 for (;;) {
196 const response = await fetch(`${url}?after=${after.current}`);
197 if (!response.ok) break;
198 const page = (await response.json()) as { chunks: LogChunk[]; done: boolean };
199 if (stopped) return;
200 if (page.chunks.length > 0) {
201 after.current = page.chunks[page.chunks.length - 1].seq;
202 setChunks((known) => [...known, ...page.chunks]);
203 }
204 if (page.chunks.length < 500) {
205 if (!page.done && live) timer = setTimeout(load, 2000);
206 break;
207 }
208 }
209 } catch {
210 if (!stopped && live) timer = setTimeout(load, 4000);
211 }
212 };
213 load();
214 return () => {
215 stopped = true;
216 if (timer) clearTimeout(timer);
217 };
218 }, [url, live]);
219 return useMemo(() => {
220 const byStep = new Map<number, string>();
221 for (const chunk of chunks) byStep.set(chunk.step, (byStep.get(chunk.step) ?? "") + chunk.text);
222 return byStep;
223 }, [chunks]);
224}
225
226const NOTE_ICON = {
227 info: <Info size={14} className="mt-0.5 shrink-0 text-muted" />,
228 warning: <AlertTriangle size={14} className="mt-0.5 shrink-0 text-warn" />,
229 unsupported: <CircleSlash size={14} className="mt-0.5 shrink-0 text-danger" />,
230};
231
232/** What in a workflow runs differently on g1t, worst first. */
233export function Notes({ notes }: { notes: WorkflowNote[] }) {
234 if (notes.length === 0) return null;
235 const order = { unsupported: 0, warning: 1, info: 2 };
236 const sorted = [...notes].sort((a, b) => order[a.severity] - order[b.severity]);
237 const blocking = notes.filter((n) => n.severity === "unsupported").length;
238 return (
239 <details className="group rounded-xl border border-line bg-surface" open={blocking > 0}>
240 <summary className="cursor-pointer list-none px-4 py-2.5 text-sm">
241 <span className="font-medium">How this runs on g1t</span>
242 <span className="text-muted">
243 {" · "}
244 {blocking > 0 ? `${blocking} thing${blocking === 1 ? "" : "s"} g1t cannot run yet` : `${notes.length} note${notes.length === 1 ? "" : "s"}`}
245 </span>
246 </summary>
247 <ul className="space-y-2 border-t border-line px-4 py-3 text-sm">
248 {sorted.map((note, index) => (
249 <li key={index} className="flex gap-2">
250 {NOTE_ICON[note.severity]}
251 <span>
252 {note.job && <span className="font-mono text-xs text-muted">{note.job}: </span>}
253 {note.message}
254 </span>
255 </li>
256 ))}
257 </ul>
258 </details>
259 );
260}
261
262
263/** What workflow runs said about a pull request's head, each linking to its run. */
264export function WorkflowStatuses({ statuses }: { statuses: CommitStatus[] }) {
265 if (statuses.length === 0) return null;
266 const standing = (state: CommitStatus["state"]) =>
267 state === "pending"
268 ? { status: "in_progress", conclusion: null }
269 : { status: "completed", conclusion: (state === "success" ? "success" : "failure") as Conclusion };
270 const failed = statuses.filter((s) => s.state === "failure" || s.state === "error").length;
271 const pending = statuses.filter((s) => s.state === "pending").length;
272 return (
273 <section className="rounded-xl border border-line bg-surface p-4">
274 <h3 className="text-sm font-medium">
275 {failed > 0 ? `${failed} workflow${failed === 1 ? "" : "s"} failed` : pending > 0 ? "Workflows running" : "Workflows passed"}
276 </h3>
277 <ul className="mt-3 space-y-2 text-sm">
278 {statuses.map((status) => {
279 const path = status.targetUrl?.replace(/^https:\/\/g1t\.sh/, "") ?? null;
280 const row = (
281 <>
282 <StatusIcon {...standing(status.state)} size={14} />
283 <span className="min-w-0 truncate">{status.context}</span>
284 </>
285 );
286 return (
287 <li key={status.context}>
288 {path ? (
289 <Hint label={status.description}>
290 <Link to={path} className="flex items-center gap-2 hover:text-fg">
291 {row}
292 </Link>
293 </Hint>
294 ) : (
295 <span className="flex items-center gap-2">{row}</span>
296 )}
297 </li>
298 );
299 })}
300 </ul>
301 </section>
302 );
303}