g1t/apps/web/app/routes/repo/compare.tsx

156 lines7,913 bytesCodeBlame
1import { ArrowLeft, GitCommitHorizontal, GitPullRequest } from "lucide-react";
2import { Form, Link } from "react-router";
3
4import type { Comparison } from "@g1t/contracts";
5
6import type { Route } from "./+types/compare";
7import { DiffView } from "../../components/diff-view";
8import { Avatar, ButtonLink, EmptyState, TimeAgo } from "../../components/ui";
9import { page } from "../../lib/meta";
10import { repos } from "../../lib/services.server";
11import { getViewer, unwrap } from "../../lib/session.server";
12
13/** How far back each side's history is read to find what head has that base does not. */
14const HEAD_DEPTH = 100;
15const BASE_DEPTH = 300;
16
17export function meta({ params, ...args }: Route.MetaArgs) {
18 const range = params["*"] ? ` ${params["*"]}` : "";
19 return page(args, { title: `Compare${range} · ${params.owner}/${params.repo} · g1t` });
20}
21
22/** `main...feature` into its two sides; either may be missing. */
23function sides(range: string): { base: string | null; head: string | null } {
24 const at = range.indexOf("...");
25 if (at === -1) return { base: null, head: range || null };
26 return { base: range.slice(0, at) || null, head: range.slice(at + 3) || null };
27}
28
29export async function loader({ params, context, request }: Route.LoaderArgs) {
30 const path = { namespace: params.owner, name: params.repo };
31 const viewer = getViewer(context);
32 const url = new URL(request.url);
33 // The pickers submit as ?base=&head=; the address keeps base...head.
34 if (url.searchParams.has("base") || url.searchParams.has("head")) {
35 const base = url.searchParams.get("base") ?? "";
36 const head = url.searchParams.get("head") ?? "";
37 return Response.redirect(new URL(`/${params.owner}/${params.repo}/compare/${base}...${head}`, url).toString(), 302);
38 }
39 const [repo, list] = await Promise.all([repos.get(path, viewer), repos.branches(path, viewer)]);
40 const found = unwrap(repo);
41 const branches = unwrap(list)
42 .map((branch) => branch.name)
43 .filter((name) => !name.startsWith("g1t-queue/"));
44 const asked = sides(params["*"] ?? "");
45 const base = asked.base ?? found.defaultBranch;
46 const head = asked.head;
47 if (!head || head === base) return { base, head, branches, comparison: null, commits: [], same: head === base };
48 const [headLog, baseLog] = await Promise.all([repos.log(path, viewer, head, HEAD_DEPTH), repos.log(path, viewer, base, BASE_DEPTH)]);
49 if (!headLog.ok || headLog.value.length === 0) throw new Response(`There is no branch, tag or commit named ${head}.`, { status: 404 });
50 // What head has that base does not: its history down to the first commit base also has.
51 const onBase = new Set(baseLog.ok ? baseLog.value.map((commit) => commit.hash) : []);
52 const shared = headLog.value.findIndex((commit) => onBase.has(commit.hash));
53 const commits = (shared === -1 ? headLog.value : headLog.value.slice(0, shared)).map((commit) => ({
54 hash: commit.hash,
55 message: commit.message.split("\n")[0] ?? "",
56 author: commit.author.name,
57 at: commit.authoredAt,
58 }));
59 // The changes from where the two last agreed, as a pull request would
60 // bring them: what base gained since is not head taking it away. When
61 // that point is past what was read, the two tips are compared.
62 const mergeBase = shared === -1 ? base : headLog.value[shared]!.hash;
63 const compared = await repos.compare(found.id, viewer, mergeBase, head);
64 const comparison: Comparison | null = compared.ok ? compared.value : null;
65 return { base, head, branches, comparison, commits, same: false };
66}
67
68function RefPicker({ name, label, value, branches }: { name: string; label: string; value: string | null; branches: string[] }) {
69 const options = value && !branches.includes(value) ? [value, ...branches] : branches;
70 return (
71 <label className="inline-flex items-center gap-2 text-sm">
72 <span className="text-muted">{label}</span>
73 <select
74 name={name}
75 defaultValue={value ?? ""}
76 className="h-8 max-w-56 rounded-md border border-line bg-surface px-2 font-mono text-[0.8125rem] outline-none hover:border-line-strong focus:border-accent-dim"
77 >
78 {value == null && <option value="">Choose a branch</option>}
79 {options.map((option) => (
80 <option key={option} value={option}>
81 {option}
82 </option>
83 ))}
84 </select>
85 </label>
86 );
87}
88
89export default function Compare({ loaderData, params }: Route.ComponentProps) {
90 const { base, head, branches, comparison, commits, same } = loaderData;
91 const repoBase = `/${params.owner}/${params.repo}`;
92 return (
93 <div className="space-y-5">
94 <div>
95 <h2 className="text-lg font-semibold tracking-tight">Compare changes</h2>
96 <p className="mt-1 text-sm text-muted">Choose two branches to see what one has that the other does not, then open a pull request for it.</p>
97 </div>
98 <Form method="get" className="flex flex-wrap items-center gap-3 rounded-xl border border-line bg-surface px-4 py-3">
99 <RefPicker name="base" label="base" value={base} branches={branches} />
100 <ArrowLeft size={14} className="text-faint" aria-hidden="true" />
101 <RefPicker name="head" label="compare" value={head} branches={branches} />
102 <button
103 type="submit"
104 className="h-8 rounded-md border border-line px-3 text-sm text-fg/90 transition-colors hover:border-line-strong hover:bg-raised"
105 >
106 Compare
107 </button>
108 {head && !same && commits.length > 0 && (
109 <ButtonLink to={`${repoBase}/pulls/new?branch=${encodeURIComponent(head)}`} variant="accent">
110 <GitPullRequest size={15} />
111 Open a pull request
112 </ButtonLink>
113 )}
114 </Form>
115
116 {!head ? (
117 <EmptyState title="Pick a branch to compare">Its commits and changes against {base} show here.</EmptyState>
118 ) : same ? (
119 <EmptyState title="Nothing to compare">Both sides are {base}. Choose another branch to compare with it.</EmptyState>
120 ) : commits.length === 0 ? (
121 <EmptyState title={`${base} has everything ${head} has`}>There is nothing on {head} to bring into {base}.</EmptyState>
122 ) : (
123 <>
124 <section>
125 <h3 className="mb-2 text-sm font-medium text-muted">
126 {commits.length === HEAD_DEPTH ? `${HEAD_DEPTH}+` : commits.length} {commits.length === 1 ? "commit" : "commits"}
127 </h3>
128 <ul className="divide-y divide-line overflow-hidden rounded-xl border border-line bg-surface">
129 {commits.map((commit) => (
130 <li key={commit.hash} className="flex items-center gap-3 px-4 py-2.5 text-sm">
131 <GitCommitHorizontal size={15} className="shrink-0 text-faint" />
132 <Avatar name={commit.author} size={16} />
133 <Link to={`${repoBase}/commit/${commit.hash}`} className="min-w-0 grow truncate hover:text-accent" title={commit.message}>
134 {commit.message}
135 </Link>
136 <span className="hidden shrink-0 text-xs text-muted sm:inline">{commit.author}</span>
137 <Link to={`${repoBase}/commit/${commit.hash}`} className="shrink-0 font-mono text-xs text-faint hover:text-fg">
138 {commit.hash.slice(0, 7)}
139 </Link>
140 <span className="shrink-0 text-xs text-faint">
141 <TimeAgo at={commit.at} />
142 </span>
143 </li>
144 ))}
145 </ul>
146 </section>
147 {comparison ? (
148 <DiffView comparison={comparison} fileBase={`${repoBase}/blob/${encodeURIComponent(head)}`} empty="The two sides have the same files." />
149 ) : (
150 <p className="text-sm text-muted">The changes could not be read just now. The commits above are what {head} adds.</p>
151 )}
152 </>
153 )}
154 </div>
155 );
156}