Skip to content

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

223 lines9,691 bytesCodeBlame
1import { Check, Copy, GitCommitHorizontal, GitPullRequest, MessagesSquare, Sparkles } from "lucide-react";
2import { Suspense, useState } from "react";
3import { Await, Link, data, redirect } from "react-router";
4
5import type { Comparison, Pull } from "@g1t/contracts";
6
7import { parseCommitMessage } from "../../lib/commit-message";
8import type { Route } from "./+types/commit";
9import { page } from "../../lib/meta";
10import { DiffView } from "../../components/diff-view";
11import { Avatar, TimeAgo } from "../../components/ui";
12import { Hint } from "../../components/ui/hint";
13import { Skeleton } from "../../components/ui/skeleton";
14import { immutable } from "../../lib/immutable.server";
15import { pullForCommit } from "../../lib/provenance.server";
16import { accounts, repos } from "../../lib/services.server";
17import { getViewer, unwrap } from "../../lib/session.server";
18
19export function headers({ loaderHeaders }: Route.HeadersArgs) {
20 return { "Server-Timing": loaderHeaders.get("Server-Timing") ?? "" };
21}
22
23export function meta({ loaderData, params, ...args }: Route.MetaArgs) {
24 const subject = loaderData?.commit.message.split("\n")[0];
25 return page(args, {
26 title: `${subject ? `${subject} · ` : ""}${params.hash.slice(0, 7)} · ${params.owner}/${params.repo} · g1t`,
27 });
28}
29
30/** How far back a short hash is looked for. */
31const SHORT_HASH_SEARCH = 300;
32
33export async function loader({ params, context }: Route.LoaderArgs) {
34 const viewer = getViewer(context);
35 const path = { namespace: params.owner, name: params.repo };
36 const hash = params.hash.toLowerCase();
37 if (!/^[0-9a-f]{4,40}$/.test(hash)) throw data(null, { status: 404 });
38 if (hash.length < 40) {
39 // A short hash: find the commit it names and go to its full address.
40 const log = await repos.log(path, viewer, null, SHORT_HASH_SEARCH);
41 const matches = log.ok ? log.value.filter((commit) => commit.hash.startsWith(hash)) : [];
42 if (matches.length === 1) throw redirect(`/${params.owner}/${params.repo}/commit/${matches[0]!.hash}`);
43 throw new Response("Commit not found.", { status: 404 });
44 }
45 const started = Date.now();
46 const found = unwrap(await repos.get(path, viewer));
47 // The viewer may read the repository, and a commit never changes: after
48 // the first visit it and its diff come from the cache.
49 let cached = true;
50 const loaded = await immutable(`commit:${found.id}:${hash}`, async () => {
51 cached = false;
52 // At once: a commit is compared with its first parent, so the diff
53 // does not wait for the commit.
54 const [log, compared] = await Promise.all([
55 repos.log(path, viewer, hash, 1),
56 repos.compare(found.id, viewer, null, hash),
57 ]);
58 const commit = log.ok ? log.value[0] : undefined;
59 if (!commit) return null;
60 const comparison: Comparison = compared.ok
61 ? compared.value
62 : { base: null, head: commit.hash, files: [], truncated: false };
63 return { commit, comparison };
64 });
65 if (!loaded) throw new Response("Commit not found.", { status: 404 });
66 // The account the author address belongs to, if any; not cached, since
67 // an address can be confirmed or removed later.
68 const email = loaded.commit.author.email.toLowerCase();
69 const owners = await accounts.emailOwners([email]).catch(() => ({}) as Record<string, never>);
70 const owner: { username: string; avatar: string | null } | null = owners[email] ?? null;
71 return data(
72 {
73 ...loaded,
74 owner,
75 // Streamed: the page shows the commit while this is worked out.
76 pull: pullForCommit(path, viewer, loaded.commit.hash),
77 },
78 { headers: { "Server-Timing": `load;dur=${Date.now() - started};desc="${cached ? "cached" : "read"}"` } },
79 );
80}
81
82function CopyHash({ hash }: { hash: string }) {
83 const [copied, setCopied] = useState(false);
84 return (
85 <button
86 type="button"
87 onClick={() => {
88 void navigator.clipboard?.writeText(hash).then(() => {
89 setCopied(true);
90 setTimeout(() => setCopied(false), 1500);
91 });
92 }}
93 className="flex items-center gap-1.5 rounded-md border border-line bg-bg px-2 py-1 font-mono text-xs text-muted transition-colors hover:border-line-strong hover:text-fg"
94 aria-label="Copy the full hash"
95 >
96 {hash.slice(0, 12)}
97 {copied ? <Check size={12} className="text-success" /> : <Copy size={12} />}
98 </button>
99 );
100}
101
102/** The pull request a commit arrived in, once it has been worked out. */
103function MergedIn({ base, pull }: { base: string; pull: Pull }) {
104 const byAgent = pull.runtime === "hosted";
105 return (
106 <div className="flex flex-wrap items-center gap-x-4 gap-y-2 border-t border-line px-5 py-3 text-sm">
107 <span className="flex items-center gap-2">
108 <GitPullRequest size={15} className="text-merged" />
109 <span className="text-muted">Merged in</span>
110 <Link to={`${base}/pull/${pull.number}`} className="font-medium hover:underline">
111 {pull.title} <span className="font-normal text-faint">#{pull.number}</span>
112 </Link>
113 </span>
114 {byAgent && (
115 <span className="flex items-center gap-1.5 rounded-full border border-accent/30 bg-accent/10 px-2 py-0.5 text-xs text-accent">
116 <Sparkles size={12} />
117 written by {pull.agent}
118 </span>
119 )}
120 <Link
121 to={`${base}/pull/${pull.number}?tab=session`}
122 className="ml-auto flex items-center gap-1.5 rounded-md border border-line px-2.5 py-1 text-xs text-muted transition-colors hover:border-line-strong hover:text-fg"
123 >
124 <MessagesSquare size={13} />
125 Why it was written
126 </Link>
127 </div>
128 );
129}
130
131export default function CommitPage({ loaderData, params }: Route.ComponentProps) {
132 const { commit, pull, comparison, owner } = loaderData;
133 const base = `/${params.owner}/${params.repo}`;
134 const { subject, body, coAuthors, trailers } = parseCommitMessage(commit.message);
135 return (
136 <div>
137 <section className="overflow-hidden rounded-xl border border-line bg-surface">
138 <div className="p-5">
139 <p className="flex items-center gap-2 text-xs text-faint">
140 <GitCommitHorizontal size={14} />
141 <Link to={`${base}/commits`} className="hover:text-fg">
142 Commit
143 </Link>
144 </p>
145 <h2 className="mt-2 text-xl font-semibold tracking-tight text-balance">{subject}</h2>
146 {body && <p className="mt-3 max-w-3xl text-sm whitespace-pre-wrap text-muted">{body}</p>}
147 {trailers.length > 0 && (
148 <dl className="mt-3 space-y-0.5 font-mono text-xs text-faint">
149 {trailers.map((trailer) => (
150 <div key={`${trailer.key}:${trailer.value}`}>
151 <dt className="inline">{trailer.key}:</dt> <dd className="inline text-muted">{trailer.value}</dd>
152 </div>
153 ))}
154 </dl>
155 )}
156 </div>
157 <div className="flex flex-wrap items-center gap-x-5 gap-y-3 border-t border-line bg-bg/40 px-5 py-3 text-sm">
158 <span className="flex items-center gap-2">
159 <Avatar name={owner?.username ?? commit.author.name} image={owner?.avatar} size={20} />
160 {owner ? (
161 <Hint label={commit.author.name}>
162 <Link to={`/u/${owner.username}`} className="font-medium hover:underline">
163 {owner.username}
164 </Link>
165 </Hint>
166 ) : (
167 <span className="font-medium">{commit.author.name}</span>
168 )}
169 {coAuthors.length > 0 && (
170 <span className="text-muted">
171 and <span className="font-medium text-fg">{coAuthors.join(", ")}</span>
172 </span>
173 )}
174 <span className="text-muted">
175 committed <TimeAgo at={commit.authoredAt} />
176 </span>
177 </span>
178 <span className="flex items-center gap-2 text-xs text-muted">
179 {commit.parents.length === 0 ? (
180 "The first commit"
181 ) : (
182 <>
183 {commit.parents.length === 1 ? "Parent" : "Parents"}
184 {commit.parents.map((parent) => (
185 <Link
186 key={parent}
187 to={`${base}/commit/${parent}`}
188 prefetch="intent"
189 className="font-mono text-fg/80 hover:text-accent hover:underline"
190 >
191 {parent.slice(0, 7)}
192 </Link>
193 ))}
194 </>
195 )}
196 </span>
197 <span className="ml-auto flex items-center gap-2">
198 <Link
199 to={`${base}/tree/${commit.hash}/`}
200 className="rounded-md px-2 py-1 text-xs text-muted hover:bg-raised hover:text-fg"
201 >
202 Browse files
203 </Link>
204 <CopyHash hash={commit.hash} />
205 </span>
206 </div>
207 <Suspense
208 fallback={
209 <div aria-busy="true" className="flex h-12 items-center gap-3 border-t border-line px-4">
210 <Skeleton className="size-4 rounded-full" />
211 <Skeleton className="h-3 w-64 max-w-[60%]" />
212 </div>
213 }
214 >
215 <Await resolve={pull}>{(pull) => (pull ? <MergedIn base={base} pull={pull} /> : null)}</Await>
216 </Suspense>
217 </section>
218 <div className="mt-6">
219 <DiffView comparison={comparison} empty="This commit changes no files." fileBase={`${base}/blob/${commit.hash}`} />
220 </div>
221 </div>
222 );
223}