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