Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

774 linesCodeBlameRaw
1/**
2 * The parts of a pull request's merge box that say what stands between it
3 * and a merge: the checks the branch requires and every other check, job by
4 * job, and whether
5 * the change merges cleanly into its target, with what to do when not.
6 */
7import {
8 Check,
9 ChevronRight,
10 CircleAlert,
11 CircleCheck,
12 CircleX,
13 Copy,
14 GitCommitHorizontal,
15 History,
16 LoaderCircle,
17 RotateCw,
18 Terminal,
19 TriangleAlert,
20} from "lucide-react";
21import { useMemo, useState } from "react";
22import { Form, Link } from "react-router";
23
24import {
25 type CheckResult,
26 type CheckRun,
27 type CommitStatus,
28 DEPENDENCY_REVIEW_CHECK,
29 type Job,
30 type Mergeable,
31 type Pull,
32 type RequiredCheck,
33} from "@g1t/contracts";
34
35import { useAddresses } from "../lib/addresses";
36import { duration } from "./actions";
37import { CopyLine, ErrorText, SubmitButton, TimeAgo } from "./ui";
38import { Badge } from "./ui/badge";
39import { Button } from "./ui/button";
40import { Card } from "./ui/card";
41import { Hint } from "./ui/hint";
42import { Tooltip, TooltipContent, TooltipTrigger } from "./ui/tooltip";
43import { SkeletonLine } from "./ui/skeleton";
44
45// --- Output ---------------------------------------------------------------
46
47/** What the sandbox puts first when it kept only the end of the output. */
48const CUT_SHORT = "… (earlier output not shown)";
49
50/** One run of text in one style, from a line with ANSI colour codes. */
51type Segment = { text: string; className: string };
52
53const ANSI_COLOURS: Record<number, string> = {
54 30: "text-faint",
55 31: "text-danger",
56 32: "text-success",
57 33: "text-warn",
58 34: "text-info",
59 35: "text-merged",
60 36: "text-info",
61 37: "text-fg",
62 90: "text-faint",
63 91: "text-danger",
64 92: "text-success",
65 93: "text-warn",
66 94: "text-info",
67 95: "text-merged",
68 96: "text-info",
69 97: "text-fg",
70};
71
72/**
73 * A line's text split where its colour changes. Colours and bold are kept;
74 * every other escape sequence (cursor movement, erasing, links) is dropped.
75 */
76export function ansiSegments(line: string): Segment[] {
77 const segments: Segment[] = [];
78 let colour = "";
79 let bold = false;
80 // SGR sequences are kept apart; anything else that starts with ESC goes.
81 const pattern = /\x1b\[([0-9;]*)m|\x1b\[[0-9;?]*[A-Za-z]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[@-_]/g;
82 let at = 0;
83 const push = (text: string) => {
84 if (text) segments.push({ text, className: [colour, bold ? "font-semibold" : ""].filter(Boolean).join(" ") });
85 };
86 for (const match of line.matchAll(pattern)) {
87 push(line.slice(at, match.index));
88 at = match.index + match[0].length;
89 if (match[1] === undefined) continue;
90 const codes = match[1] === "" ? [0] : match[1].split(";").map(Number);
91 for (const code of codes) {
92 if (code === 0) {
93 colour = "";
94 bold = false;
95 } else if (code === 1) bold = true;
96 else if (code === 22) bold = false;
97 else if (code === 39) colour = "";
98 else if (ANSI_COLOURS[code]) colour = ANSI_COLOURS[code];
99 }
100 }
101 push(line.slice(at));
102 return segments;
103}
104
105/** Text without any ANSI escape sequences, for copying. */
106export function stripAnsi(text: string): string {
107 return ansiSegments(text.replace(/\r\n/g, "\n"))
108 .map((segment) => segment.text)
109 .join("");
110}
111
112/** Lines as a terminal would show them: a carriage return starts the line over. */
113function terminalLines(text: string): string[] {
114 return text
115 .replace(/\r\n/g, "\n")
116 .split("\n")
117 .map((line) => {
118 const parts = line.split("\r");
119 return parts[parts.length - 1] || parts.filter(Boolean).pop() || "";
120 });
121}
122
123/**
124 * A command's output as a log: numbered lines, colours rendered, a copy
125 * button, and a note when only the end of it was kept.
126 */
127export function LogViewer({ text }: { text: string }) {
128 const cut = text.startsWith(CUT_SHORT);
129 const body = cut ? text.slice(CUT_SHORT.length).replace(/^\n/, "") : text;
130 const lines = useMemo(() => {
131 const all = terminalLines(body);
132 while (all.length > 0 && all[all.length - 1].trim() === "") all.pop();
133 return all;
134 }, [body]);
135 const [copied, setCopied] = useState(false);
136 if (lines.length === 0) {
137 return <p className="px-3 py-2 font-mono text-xs text-faint">No output.</p>;
138 }
139 return (
140 <div className="relative">
141 <Hint label="Copy the output">
142 <Button
143 type="button"
144 aria-label="Copy the output"
145 variant="outline"
146 size="inline"
147 className="absolute top-1.5 right-3 z-10 bg-surface p-1.5 text-faint"
148 onClick={() => {
149 void navigator.clipboard.writeText(stripAnsi(body));
150 setCopied(true);
151 setTimeout(() => setCopied(false), 1500);
152 }}
153 >
154 {copied ? <Check size={13} className="text-success" /> : <Copy size={13} />}
155 </Button>
156 </Hint>
157 {cut && <p className="border-b border-line px-3 py-1.5 text-xs text-faint">Showing the end of the output. Earlier lines were not kept.</p>}
158 <div className="max-h-96 overflow-auto py-1.5 font-mono text-xs leading-5">
159 {lines.map((line, index) => (
160 <div key={index} className="flex gap-3 pr-12 pl-2 hover:bg-raised/40">
161 <span className="w-9 shrink-0 text-right text-faint/70 select-none">{index + 1}</span>
162 <span className="min-w-0 break-all whitespace-pre-wrap text-fg/85">
163 {ansiSegments(line).map((segment, at) =>
164 segment.className ? (
165 <span key={at} className={segment.className}>
166 {segment.text}
167 </span>
168 ) : (
169 segment.text
170 ),
171 )}
172 </span>
173 </div>
174 ))}
175 </div>
176 </div>
177 );
178}
179
180// --- Checks ---------------------------------------------------------------
181
182function seconds(ms: number): string {
183 if (ms < 1000) return `${ms}ms`;
184 const s = Math.round(ms / 1000);
185 return s < 60 ? `${(ms / 1000).toFixed(ms < 10_000 ? 1 : 0)}s` : `${Math.floor(s / 60)}m ${s % 60}s`;
186}
187
188type Standing = "passed" | "failed" | "running" | "queued" | "skipped";
189
190function StandingIcon({ standing, size = 15 }: { standing: Standing; size?: number }) {
191 if (standing === "passed") return <CircleCheck size={size} className="shrink-0 text-success" aria-label="Passed" />;
192 if (standing === "failed") return <CircleX size={size} className="shrink-0 text-danger" aria-label="Failed" />;
193 if (standing === "running") return <LoaderCircle size={size} className="shrink-0 animate-spin text-warn" aria-label="Running" />;
194 if (standing === "skipped") return <CircleAlert size={size} className="shrink-0 text-faint" aria-label="Skipped" />;
195 return <LoaderCircle size={size} className="shrink-0 text-faint" aria-label="Queued" />;
196}
197
198/** The id of the workflow run a status links to, if it links to one. */
199export function runIdOf(status: CommitStatus): string | null {
200 return /\/actions\/runs\/([^/?#]+)/.exec(status.targetUrl ?? "")?.[1] ?? null;
201}
202
203/** Where a job stands, in the box's terms. */
204function jobStanding(job: Job): Standing {
205 if (job.status !== "completed") return job.status === "in_progress" || job.status === "calling" ? "running" : "queued";
206 if (job.conclusion === "success") return "passed";
207 if (job.conclusion === "skipped" || job.conclusion === "cancelled") return "skipped";
208 return "failed";
209}
210
211function statusStanding(status: CommitStatus): Standing {
212 if (status.state === "pending") return "running";
213 return status.state === "success" ? "passed" : "failed";
214}
215
216/** One row of the checks list: an icon, a name, how long, and a way in. */
217function CheckLine({
218 standing,
219 name,
220 detail,
221 time,
222 timing = false,
223 to,
224}: {
225 standing: Standing;
226 name: React.ReactNode;
227 detail?: React.ReactNode;
228 time?: string;
229 /** Its jobs and their times are still being read. */
230 timing?: boolean;
231 to?: string;
232}) {
233 return (
234 <div className="flex items-center gap-2.5 px-4 py-2 text-sm">
235 <StandingIcon standing={standing} />
236 <span className="min-w-0 grow truncate">
237 {name}
238 {detail && <span className="text-muted"> — {detail}</span>}
239 </span>
240 {time && (
241 // A running job's time counts to now, which differs between server and browser.
242 <span className="shrink-0 animate-fade-in font-mono text-xs text-faint" suppressHydrationWarning>
243 {time}
244 </span>
245 )}
246 {timing && <SkeletonLine className="w-10 shrink-0 text-xs" />}
247 {to && (
248 <Link to={to} className="shrink-0 text-xs text-muted hover:text-fg hover:underline">
249 Details
250 </Link>
251 )}
252 </div>
253 );
254}
255
256/** A command from a run recorded before checks were workflows: what it printed, open when it failed. */
257function CommandResult({ result }: { result: CheckResult }) {
258 const timedOut = result.exitCode == null && !result.passed;
259 return (
260 <details className="group" open={!result.passed}>
261 <summary className="flex cursor-pointer list-none items-center gap-2.5 px-4 py-2 text-sm hover:bg-raised/40">
262 <StandingIcon standing={result.passed ? "passed" : "failed"} />
263 <span className="min-w-0 grow truncate">
264 <code className="font-mono text-xs">{result.command}</code>
265 {!result.passed && (
266 <span className="text-muted">
267 {" — "}
268 {timedOut ? "stopped for taking too long" : `exited with code ${result.exitCode}`}
269 </span>
270 )}
271 </span>
272 <span className="shrink-0 font-mono text-xs text-faint">{seconds(result.durationMs)}</span>
273 <ChevronRight size={14} className="shrink-0 text-faint transition-transform group-open:rotate-90" />
274 </summary>
275 <Card tone="bg" radius="lg" className="mx-4 mb-3 overflow-hidden">
276 <LogViewer text={result.output} />
277 </Card>
278 </details>
279 );
280}
281
282/** Where a required check stands, in the box's terms. */
283function requiredStanding(check: RequiredCheck): Standing {
284 if (check.state === "success") return "passed";
285 if (check.state === "failure") return "failed";
286 return check.state === "pending" ? "running" : "queued";
287}
288
289/** How the required checks stand together: "2 of 3 passing", and what holds the rest. */
290export function requiredSummary(required: RequiredCheck[]): { title: string; sub: string; standing: Standing } {
291 const count = (state: RequiredCheck["state"]) => required.filter((check) => check.state === state).length;
292 const passing = count("success");
293 const failing = count("failure");
294 const running = count("pending");
295 const expected = count("expected");
296 const sub = [failing > 0 && `${failing} failing`, running > 0 && `${running} running`, expected > 0 && `${expected} not reported yet`]
297 .filter(Boolean)
298 .join(", ");
299 return {
300 title: `Required checks: ${passing} of ${required.length} passing`,
301 sub,
302 standing: failing > 0 ? "failed" : running + expected > 0 ? "running" : "passed",
303 };
304}
305
306/** The repository-relative address of a status's link, when it is on g1t. */
307function onSite(url: string | null): string | undefined {
308 if (!url) return undefined;
309 const path = url.replace(/^https:\/\/g1t\.sh(?=\/)/, "");
310 return path.startsWith("/") ? path : undefined;
311}
312
313/**
314 * Every check on a pull request, at a glance and in detail: first the
315 * checks the default branch requires, each as it stands on the head (one
316 * nothing has reported is waited for), then every workflow run on the
317 * head, job by job. A record of the merge queue taking it out comes last.
318 */
319export function ChecksSection({
320 run,
321 required,
322 statuses,
323 jobs,
324 pull,
325 base,
326 earlier,
327 canRerunWorkflows,
328 settingsUrl,
329 conflicting = false,
330 error,
331 loading = false,
332 settled = false,
333}: {
334 /** Set when the merge queue took it out, or for a run from before checks were workflows. */
335 run: CheckRun | null;
336 required: RequiredCheck[];
337 statuses: CommitStatus[];
338 /** Each workflow run's jobs, by run id, where they could be read. */
339 jobs: Record<string, Job[]>;
340 pull: Pull;
341 /** The repository's path, `/<owner>/<repo>`. */
342 base: string;
343 earlier: CheckRun[];
344 canRerunWorkflows: boolean;
345 /** Where the required checks are chosen, for those who may. */
346 settingsUrl?: string | null;
347 /**
348 * It conflicts with its target, so its `pull_request` workflows do not
349 * run: there is no merge commit to build, as on GitHub.
350 */
351 conflicting?: boolean;
352 error?: string | null;
353 /** The workflow runs' jobs are still being read: their rows wait, busy. */
354 loading?: boolean;
355 /**
356 * The pull request is closed or merged: its head's checks as they ended,
357 * to read only. Nothing is said of holding a merge.
358 */
359 settled?: boolean;
360}) {
361 const held = conflicting && !settled;
362 if (!run && statuses.length === 0 && required.length === 0 && !held) return null;
363
364 // Every workflow row, so they can be counted the same way they are shown.
365 const workflow: Standing[] = statuses.flatMap((status) => {
366 const id = runIdOf(status);
367 const theirs = id ? jobs[id] : undefined;
368 return theirs && theirs.length > 0 ? theirs.map(jobStanding) : [statusStanding(status)];
369 });
370 const failed = workflow.filter((standing) => standing === "failed").length;
371 const pending = workflow.filter((standing) => standing === "running" || standing === "queued").length;
372 const passed = workflow.filter((standing) => standing === "passed").length;
373 const skipped = workflow.filter((standing) => standing === "skipped").length;
374 const total = workflow.length;
375 const queueFailed = run?.status === "failed" && run.results.length === 0;
376
377 const summary = required.length > 0 ? requiredSummary(required) : null;
378 const headline = summary
379 ? summary.title
380 : failed > 0
381 ? `${failed} of ${total} ${total === 1 ? "check" : "checks"} failed`
382 : pending > 0
383 ? `${pending} of ${total} ${total === 1 ? "check is" : "checks are"} still running`
384 : total > 0
385 ? "All checks have passed"
386 : held
387 ? "Workflows have not run"
388 : "Checks";
389 const others = [
390 failed > 0 && `${failed} failed`,
391 pending > 0 && `${pending} running`,
392 passed > 0 && `${passed} passed`,
393 skipped > 0 && `${skipped} skipped or cancelled`,
394 ]
395 .filter(Boolean)
396 .join(", ");
397 const sub = summary
398 ? [summary.sub, others && `all checks: ${others}`].filter(Boolean).join(" · ")
399 : settled
400 ? [others, pull.headCommit && `on ${pull.headCommit.slice(0, 7)}`].filter(Boolean).join(" · ")
401 : [others, "none are required, so none hold the merge"].filter(Boolean).join(" · ");
402 const standing: Standing = summary ? summary.standing : failed > 0 ? "failed" : pending > 0 ? "running" : "passed";
403
404 const commitPath = (sha: string) => (pull.fork ? `/${pull.fork.namespace}/${pull.fork.name}/commit/${sha}` : `${base}/commit/${sha}`);
405 const older = run != null && pull.headCommit != null && run.headCommit !== pull.headCommit;
406 const failedRuns = statuses.filter((status) => statusStanding(status) === "failed" && runIdOf(status));
407 // g1t's own Dependency review check, which anyone who may start runs can
408 // have made again (after an advisory is published, say).
409 const dependencyReview = statuses.some((status) => status.context === DEPENDENCY_REVIEW_CHECK && status.source === "security");
410
411 return (
412 <div aria-busy={loading || undefined}>
413 <div className="flex items-start gap-3 px-4 py-3">
414 <span className="mt-0.5 shrink-0">
415 {standing === "failed" || queueFailed ? (
416 <CircleX size={16} className="text-danger" />
417 ) : standing === "running" ? (
418 <LoaderCircle size={16} className="animate-spin text-warn" />
419 ) : held && total === 0 ? (
420 <CircleAlert size={16} className="text-warn" />
421 ) : (
422 <CircleCheck size={16} className="text-success" />
423 )}
424 </span>
425 <div className="min-w-0 grow">
426 <p className="text-sm font-medium">{headline}</p>
427 {sub && <p className="mt-0.5 text-xs text-muted">{sub}</p>}
428 {held && (
429 <p className="mt-0.5 text-xs text-muted">
430 It conflicts with the branch it merges into, so workflows that run on <code className="font-mono">pull_request</code> do not start for it: they
431 build the pull request merged into that branch, and there is no such merge. They run again once the conflicts are resolved.
432 </p>
433 )}
434 {!summary && !settled && settingsUrl && (
435 <p className="mt-0.5 text-xs text-muted">
436 <Link to={settingsUrl} className="text-fg hover:underline">
437 Choose required checks
438 </Link>{" "}
439 to hold merges until they pass.
440 </p>
441 )}
442 </div>
443 <div className="flex shrink-0 flex-wrap items-center justify-end gap-2">
444 {canRerunWorkflows &&
445 failedRuns.map((status) => (
446 <Form method="post" key={status.context}>
447 <input type="hidden" name="action" value="rerun-workflow" />
448 <input type="hidden" name="run" value={runIdOf(status) ?? ""} />
449 <Hint label={`Re-run the failed jobs of ${status.context}`}>
450 <SubmitButton variant="outline" match={{ action: "rerun-workflow", run: runIdOf(status) ?? "" }} pending="Re-running…">
451 <RotateCw size={13} />
452 Re-run failed jobs{failedRuns.length > 1 ? ` of ${status.context}` : ""}
453 </SubmitButton>
454 </Hint>
455 </Form>
456 ))}
457 {canRerunWorkflows && dependencyReview && !settled && (
458 <Form method="post">
459 <input type="hidden" name="action" value="rerun-dependency-review" />
460 <Hint label="Review its dependency changes again, with the advisories known now">
461 <SubmitButton variant="outline" match={{ action: "rerun-dependency-review" }} pending="Re-running…">
462 <RotateCw size={13} />
463 Re-run dependency review
464 </SubmitButton>
465 </Hint>
466 </Form>
467 )}
468 </div>
469 </div>
470 {error && (
471 <div className="px-4 pb-2">
472 <ErrorText>{error}</ErrorText>
473 </div>
474 )}
475
476 <div className="divide-y divide-line border-t border-line">
477 {required.length > 0 && (
478 <section aria-label="Required checks" className="py-1">
479 <p className="px-4 pt-1.5 pb-1 text-xs font-medium text-muted">Required</p>
480 {required.map((check) => (
481 <CheckLine
482 key={check.name}
483 standing={requiredStanding(check)}
484 name={
485 <>
486 {check.name}
487 <Badge className="ml-1.5 px-1.5 text-[0.625rem] font-normal text-faint">Required</Badge>
488 </>
489 }
490 detail={
491 check.state === "expected" ? "Waiting for status to be reported" : (check.description ?? (check.state === "pending" ? "running" : undefined))
492 }
493 to={onSite(check.targetUrl)}
494 />
495 ))}
496 </section>
497 )}
498
499 {statuses.length > 0 && (
500 <section aria-label="All checks" className="py-1">
501 <p className="px-4 pt-1.5 pb-1 text-xs font-medium text-muted">{required.length > 0 ? "All checks" : "Workflows"}</p>
502 {statuses.map((status) => {
503 const id = runIdOf(status);
504 const runPath = id ? `${base}/actions/runs/${id}` : onSite(status.targetUrl);
505 const theirs = id ? jobs[id] : undefined;
506 if (!theirs || theirs.length === 0) {
507 return (
508 <CheckLine
509 key={status.context}
510 standing={statusStanding(status)}
511 name={status.context}
512 detail={status.description ?? undefined}
513 timing={loading && id != null}
514 to={runPath}
515 />
516 );
517 }
518 return theirs.map((job) => (
519 <CheckLine
520 key={`${status.context}-${job.id}`}
521 standing={jobStanding(job)}
522 name={
523 <>
524 <span className="text-muted">{status.context} / </span>
525 {job.name}
526 </>
527 }
528 detail={job.reason ?? (jobStanding(job) === "failed" ? "failed" : undefined)}
529 time={duration(job.startedAt, job.finishedAt) || undefined}
530 to={`${runPath}?job=${job.id}`}
531 />
532 ));
533 })}
534 </section>
535 )}
536
537 {run && (
538 <section aria-label={queueFailed ? "Merge queue" : "Earlier commands"} className="py-1">
539 <p className="flex flex-wrap items-center gap-x-1.5 px-4 pt-1.5 pb-1 text-xs text-faint">
540 <span className="font-medium text-muted">{queueFailed ? "Merge queue" : "Commands from the work item"}</span>
541 <span>· on</span>
542 <Link to={commitPath(run.headCommit)} className="inline-flex items-center gap-1 font-mono hover:text-fg">
543 <GitCommitHorizontal size={12} />
544 {run.headCommit.slice(0, 7)}
545 </Link>
546 {run.finishedAt ? (
547 <span>
548 · <TimeAgo at={run.finishedAt} />
549 </span>
550 ) : (
551 <span>
552 · started <TimeAgo at={run.createdAt} />
553 </span>
554 )}
555 </p>
556 {older && !queueFailed && (
557 <p className="mx-4 my-1.5 flex items-start gap-2 rounded-md bg-warn/10 px-2.5 py-1.5 text-xs text-warn">
558 <TriangleAlert size={13} className="mt-0.5 shrink-0" />
559 These ran on an older commit, before the latest push, <span className="font-mono">{pull.headCommit?.slice(0, 7)}</span>.
560 </p>
561 )}
562 {run.error && (
563 <Card asChild tone="bg" radius="lg" className="mx-4 my-1.5 px-3 py-2 text-sm text-muted">
564 <p>{run.error}</p>
565 </Card>
566 )}
567 {run.results.map((result, index) => (
568 <CommandResult key={`${result.command}-${index}`} result={result} />
569 ))}
570 </section>
571 )}
572
573 {earlier.length > 0 && (
574 <details className="group">
575 <summary className="flex cursor-pointer list-none items-center gap-2 px-4 py-2 text-xs text-muted hover:text-fg">
576 <History size={13} />
577 Earlier records ({earlier.length})
578 <ChevronRight size={13} className="transition-transform group-open:rotate-90" />
579 </summary>
580 <ul className="space-y-1 px-4 pb-3 text-xs">
581 {earlier.map((before) => (
582 <li key={before.id} className="flex items-center gap-2 text-muted">
583 <StandingIcon
584 size={13}
585 standing={before.status === "passed" ? "passed" : before.status === "queued" || before.status === "running" ? "queued" : "failed"}
586 />
587 <Link to={commitPath(before.headCommit)} className="font-mono hover:text-fg">
588 {before.headCommit.slice(0, 7)}
589 </Link>
590 <span className="min-w-0 truncate">
591 {before.status === "errored"
592 ? `could not run${before.error ? `: ${before.error}` : ""}`
593 : before.results.length > 0
594 ? `${before.results.filter((result) => result.passed).length} of ${before.results.length} passed`
595 : (before.error ?? before.status)}
596 </span>
597 <span className="ml-auto shrink-0 text-faint">
598 <TimeAgo at={before.createdAt} />
599 </span>
600 </li>
601 ))}
602 </ul>
603 </details>
604 )}
605 </div>
606 </div>
607 );
608}
609
610// --- Mergeability ---------------------------------------------------------
611
612/** How to resolve the conflicts by hand, step by step, for a branch or a fork. */
613export function commandLineSteps(pull: Pull, owner: string, repo: string, defaultBranch: string, files: string[], site = "https://g1t.sh"): string[] {
614 const upstream = `${site}/${owner}/${repo}.git`;
615 const add = files.length > 0 && files.length <= 6 ? `git add ${files.join(" ")}` : "git add -A";
616 // A branch of someone's fork of the repository: fetched from and pushed to the fork.
617 if (pull.branch && pull.headRepo && !pull.fork) {
618 const fork = pull.headRepo;
619 return [
620 `git clone -b ${pull.branch} ${site}/${fork.namespace}/${fork.name}.git && cd ${fork.name}`,
621 `git pull --no-rebase ${upstream} ${defaultBranch}`,
622 `${add} && git commit --no-edit`,
623 `git push origin ${pull.branch}`,
624 ];
625 }
626 if (pull.branch) {
627 return [
628 `git fetch origin`,
629 `git checkout ${pull.branch}`,
630 `git merge origin/${defaultBranch}`,
631 `${add} && git commit --no-edit`,
632 `git push origin ${pull.branch}`,
633 ];
634 }
635 const fork = pull.fork!;
636 return [
637 `git clone ${site}/${fork.namespace}/${fork.name}.git && cd ${fork.name}`,
638 `git pull --no-rebase ${upstream} ${defaultBranch}`,
639 `${add} && git commit --no-edit`,
640 `git push`,
641 ];
642}
643
644/**
645 * The branch conflicts with its target: which files, and the ways out:
646 * the browser (soon), or the command line.
647 */
648export function ConflictsSection({
649 conflicts,
650 pull,
651 owner,
652 repo,
653 defaultBranch,
654 changesUrl,
655 error,
656}: {
657 conflicts: string[];
658 pull: Pull;
659 owner: string;
660 repo: string;
661 defaultBranch: string;
662 /** Where the pull request's changes are shown, to link each file. */
663 changesUrl: string;
664 error?: string | null;
665}) {
666 const { site } = useAddresses();
667 const steps = commandLineSteps(pull, owner, repo, defaultBranch, conflicts, site);
668 return (
669 <div className="bg-danger/5">
670 <div className="flex gap-3 px-4 py-3">
671 <CircleAlert size={16} className="mt-0.5 shrink-0 text-danger" />
672 <div className="min-w-0 grow">
673 <p className="text-sm font-medium">This branch has conflicts that must be resolved</p>
674 <p className="mt-0.5 text-sm text-muted">
675 Merging <span className="font-mono">{defaultBranch}</span> into it stops on {conflicts.length === 1 ? "one file" : `${conflicts.length} files`}. It
676 cannot merge until they are resolved.
677 </p>
678 {conflicts.length > 0 && (
679 <>
680 <p className="mt-3 text-xs font-medium text-muted">Conflicting files</p>
681 <ul className="mt-1.5 space-y-1">
682 {conflicts.map((path) => (
683 <li key={path}>
684 <Link to={`${changesUrl}#file-${path}`} className="font-mono text-xs text-fg hover:text-danger hover:underline">
685 {path}
686 </Link>
687 </li>
688 ))}
689 </ul>
690 </>
691 )}
692 <div className="mt-3 flex flex-wrap items-center gap-2">
693 <Tooltip>
694 <TooltipTrigger asChild>
695 {/* A disabled button gets no pointer events; the span carries the tooltip. */}
696 <span tabIndex={0} className="inline-flex">
697 <Button variant="outline" type="button" disabled aria-disabled="true">
698 Resolve in the browser
699 <Badge className="px-1.5 py-0 text-[0.625rem] font-normal text-faint">Soon</Badge>
700 </Button>
701 </span>
702 </TooltipTrigger>
703 <TooltipContent>An editor for conflicts in the browser is coming. Until then, use the command line.</TooltipContent>
704 </Tooltip>
705 </div>
706 {error && (
707 <div className="mt-2">
708 <ErrorText>{error}</ErrorText>
709 </div>
710 )}
711 <details className="group mt-3">
712 <summary className="flex cursor-pointer list-none items-center gap-1.5 text-xs text-muted hover:text-fg">
713 <Terminal size={13} />
714 Resolve on the command line
715 <ChevronRight size={13} className="transition-transform group-open:rotate-90" />
716 </summary>
717 <ol className="mt-2 space-y-2 text-xs text-muted">
718 {steps.map((step, index) => (
719 <li key={step}>
720 <p className="mb-1">
721 {index + 1}.{" "}
722 {step.startsWith("git add")
723 ? "Fix the conflicts in each file, removing the conflict markers, then commit the merge:"
724 : step.startsWith("git push")
725 ? "Push it. The pull request updates, and its checks run again:"
726 : step.includes("merge") || step.includes("pull")
727 ? `Merge ${defaultBranch} in. Git stops on the conflicting files:`
728 : step.startsWith("git clone")
729 ? pull.headRepo && !pull.fork
730 ? `Clone the branch from ${pull.headRepo.namespace}/${pull.headRepo.name}, the fork it is in:`
731 : "Clone the pull request's fork:"
732 : step.startsWith("git checkout")
733 ? "Check out the pull request's branch:"
734 : "Get the latest of both:"}
735 </p>
736 <CopyLine text={step} prompt />
737 </li>
738 ))}
739 </ol>
740 {pull.fork && <p className="mt-2 text-xs text-faint">A pull request's fork takes pushes from whoever opened it.</p>}
741 </details>
742 </div>
743 </div>
744 </div>
745 );
746}
747
748/** Whether the change merges cleanly, when that is not a conflict. */
749export function MergeabilityRow({ mergeable, defaultBranch }: { mergeable: Mergeable; defaultBranch: string }) {
750 if (mergeable === "checking") {
751 return (
752 <div className="flex gap-3 px-4 py-3 text-sm">
753 <LoaderCircle size={16} className="mt-0.5 shrink-0 animate-spin text-faint" />
754 <div>
755 <p className="font-medium">Checking whether this merges cleanly…</p>
756 <p className="mt-0.5 text-muted">
757 It and <span className="font-mono">{defaultBranch}</span> changed some of the same files, so g1t is merging the two in a sandbox to see.
758 </p>
759 </div>
760 </div>
761 );
762 }
763 if (mergeable === "clean") {
764 return (
765 <div className="flex gap-3 px-4 py-3 text-sm">
766 <CircleCheck size={16} className="mt-0.5 shrink-0 text-success" />
767 <p className="font-medium">
768 This branch has no conflicts with <span className="font-mono">{defaultBranch}</span>
769 </p>
770 </div>
771 );
772 }
773 return null;
774}