Skip to content

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

162 lines8,087 bytesCodeBlame

Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.

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

This file's history is long; its oldest lines are credited to the oldest commit read.