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.

354 linesCodeBlameRaw
1import { Check, Copy, GitCommitHorizontal, GitPullRequest, MessageSquareOff, MessagesSquare, Sparkles } from "lucide-react";
2import { Suspense, useState } from "react";
3import { Await, Link, data, redirect } from "react-router";
4
5import type { ClosedItem, Comparison, Pull } from "@g1t/contracts";
6
7import { asComments } from "../../lib/commit-comments";
8
9import { parseCommitMessage } from "../../lib/commit-message";
10import { firstScreens } from "../../lib/diff";
11import type { Route } from "./+types/commit";
12import { page } from "../../lib/meta";
13import { CommitChecksBadge } from "../../components/commit-checks";
14import { CommitText, RefLink } from "../../components/commit-message";
15import { DiffView } from "../../components/diff-view";
16import { CommitAvatars, CommitNames } from "../../components/commit-person";
17import { ErrorText, TimeAgo } from "../../components/ui";
18import { CommentForm, CommentList } from "../../components/work";
19import { ItemIcon } from "../../components/work-icons";
20import { Badge } from "../../components/ui/badge";
21import { Button } from "../../components/ui/button";
22import { Card } from "../../components/ui/card";
23import { Skeleton } from "../../components/ui/skeleton";
24import { commitChecksFor } from "../../lib/commit-checks.server";
25import { immutable } from "../../lib/immutable.server";
26import { pullForCommit } from "../../lib/provenance.server";
27import { showOneCommit } from "../../lib/commit-people.server";
28import { repos, work } from "../../lib/services.server";
29import { assertSameOrigin, getViewer, requireUser, unwrap } from "../../lib/session.server";
30import { accessTo } from "../../lib/access.server";
31import { Unavailable } from "../../components/boundary";
32import { isFailed, part } from "../../lib/partial";
33
34export function headers({ loaderHeaders }: Route.HeadersArgs) {
35 return { "Server-Timing": loaderHeaders.get("Server-Timing") ?? "" };
36}
37
38export function meta({ loaderData, params, ...args }: Route.MetaArgs) {
39 const subject = loaderData?.commit.message.split("\n")[0];
40 return page(args, {
41 title: `${subject ? `${subject} · ` : ""}${params.hash.slice(0, 7)} · ${params.owner}/${params.repo} · g1t`,
42 });
43}
44
45/** How far back a short hash is looked for. */
46const SHORT_HASH_SEARCH = 300;
47
48export async function loader({ params, context }: Route.LoaderArgs) {
49 const viewer = getViewer(context);
50 const path = { namespace: params.owner, name: params.repo };
51 const hash = params.hash.toLowerCase();
52 if (!/^[0-9a-f]{4,40}$/.test(hash)) throw data(null, { status: 404 });
53 if (hash.length < 40) {
54 // A short hash: find the commit it names and go to its full address.
55 const log = await repos.log(path, viewer, null, SHORT_HASH_SEARCH);
56 const matches = log.ok ? log.value.filter((commit) => commit.hash.startsWith(hash)) : [];
57 if (matches.length === 1) throw redirect(`/${params.owner}/${params.repo}/commit/${matches[0]!.hash}`);
58 throw new Response("Commit not found.", { status: 404 });
59 }
60 const started = Date.now();
61 // Its comments, whether more may be added and the work items it landed: never
62 // cached, read beside the commit. Its comments and the work items it landed
63 // are parts of the page that say so when they fail; without the settings
64 // or the viewer's role, comments stay open and nobody moderates, which
65 // the service checks again when one is sent.
66 const said = Promise.all([
67 part(work.commitComments(viewer, path, hash), "Comments"),
68 work.getSettings(path, viewer).catch(() => null),
69 accessTo(context, params).catch(() => null),
70 part(work.closedByCommit(path, hash, viewer), "The work items it landed"),
71 ]);
72 const found = unwrap(await repos.get(path, viewer));
73 // The viewer may read the repository, and a commit never changes: after
74 // the first visit it and its diff come from the cache.
75 let cached = true;
76 const loaded = await immutable(`commit:${found.id}:${hash}`, async () => {
77 cached = false;
78 // At once: a commit is compared with its first parent, so the diff
79 // does not wait for the commit.
80 const [log, compared] = await Promise.all([
81 repos.log(path, viewer, hash, 1),
82 repos.compare(found.id, viewer, null, hash),
83 ]);
84 const commit = log.ok ? log.value[0] : undefined;
85 if (!commit) return null;
86 const comparison: Comparison = compared.ok
87 ? compared.value
88 : { base: null, head: commit.hash, files: [], truncated: false };
89 return { commit, comparison };
90 });
91 if (!loaded) throw new Response("Commit not found.", { status: 404 });
92 // Its people, as their accounts where there are any; not kept with the
93 // commit, since an address can be confirmed or removed later.
94 const commit = (await showOneCommit(loaded.commit))!;
95 const [comments, settings, access, closed] = await said;
96 return data(
97 {
98 ...loaded,
99 // Its first screens with their lines; the rest load as they are reached.
100 comparison: firstScreens(loaded.comparison),
101 commit,
102 // Streamed: the page shows the commit while this is worked out.
103 pull: part(pullForCommit(path, viewer, loaded.commit.hash), "The pull request it came in"),
104 // Never cached: checks report on a commit long after it was made.
105 checks: commitChecksFor(path, viewer, [loaded.commit.hash]),
106 comments: isFailed(comments) ? comments : comments.ok ? comments.value : [],
107 // Off, the comments made stay readable and no more can be added.
108 commentsOn: settings?.ok ? settings.value.allowCommitComments : true,
109 // The work items its message landed (`Closes #12`) when it was pushed.
110 closed: isFailed(closed) ? closed : closed.ok ? closed.value : [],
111 viewer: viewer ? { username: viewer.username } : null,
112 // Maintain and up edit and delete anyone's comments; everyone, their own.
113 canModerate: access?.can.manage_settings ?? false,
114 },
115 { headers: { "Server-Timing": `load;dur=${Date.now() - started};desc="${cached ? "cached" : "read"}"` } },
116 );
117}
118
119export async function action({ request, params, context }: Route.ActionArgs) {
120 assertSameOrigin(request);
121 const user = requireUser(context, request);
122 const form = await request.formData();
123 const path = { namespace: params.owner, name: params.repo };
124 const action = String(form.get("action") ?? "");
125 const body = String(form.get("body") ?? "");
126 if (action === "edit-comment" || action === "delete-comment") {
127 const id = String(form.get("comment") ?? "");
128 const changed =
129 action === "edit-comment" ? await work.editCommitComment(user, path, id, body) : await work.deleteCommitComment(user, path, id);
130 return changed.ok ? null : { action, comment: id, error: changed.error.message };
131 }
132 if (action !== "comment") return { action, error: "Unknown action." };
133 if (!body.trim()) return { action, error: "Write something first." };
134 // On one line of a file it changed, from the diff, or on the whole commit.
135 const file = String(form.get("path") ?? "");
136 const line = Number(form.get("line"));
137 const added = await work.addCommitComment(
138 user,
139 path,
140 params.hash.toLowerCase(),
141 body,
142 file && line > 0 ? { path: file, line } : undefined,
143 );
144 return added.ok ? null : { action, error: added.error.message };
145}
146
147function CopyHash({ hash }: { hash: string }) {
148 const [copied, setCopied] = useState(false);
149 return (
150 <Button
151 type="button"
152 onClick={() => {
153 void navigator.clipboard?.writeText(hash).then(() => {
154 setCopied(true);
155 setTimeout(() => setCopied(false), 1500);
156 });
157 }} variant="outline" size="inline" className="bg-bg px-2 py-1 font-mono text-xs text-muted" aria-label="Copy the full hash">
158 {hash.slice(0, 12)}
159 {copied ? <Check size={12} className="text-success" /> : <Copy size={12} />}
160 </Button>
161 );
162}
163
164/** The pull request a commit arrived in, once it has been worked out. */
165function MergedIn({ base, pull }: { base: string; pull: Pull }) {
166 const byAgent = pull.runtime === "hosted";
167 return (
168 <div className="flex flex-wrap items-center gap-x-4 gap-y-2 border-t border-line px-5 py-3 text-sm">
169 <span className="flex items-center gap-2">
170 <GitPullRequest size={15} className="text-merged" />
171 <span className="text-muted">Merged in</span>
172 <Link to={`${base}/pull/${pull.number}`} className="font-medium hover:underline">
173 {pull.title} <span className="font-normal text-faint">#{pull.number}</span>
174 </Link>
175 </span>
176 {byAgent && (
177 <Badge tone="accent" size="md" className="gap-1.5">
178 <Sparkles size={12} />
179 written by {pull.agent}
180 </Badge>
181 )}
182 <Link
183 to={`${base}/pull/${pull.number}/session`}
184 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"
185 >
186 <MessagesSquare size={13} />
187 Why it was written
188 </Link>
189 </div>
190 );
191}
192
193/**
194 * A work item the commit's message named after a closing keyword when it
195 * was pushed: it landed here, and closed if nothing else was left to land.
196 */
197function ClosedItemRow({ item }: { item: ClosedItem }) {
198 return (
199 <div className="flex items-center gap-2 border-t border-line px-5 py-3 text-sm">
200 <ItemIcon item={{ state: item.closed ? "closed" : "open", reason: item.closed ? "completed" : null }} size={15} />
201 <span className="shrink-0 text-muted">{item.closed ? "Closed" : "Landed here for"}</span>
202 <RefLink scope={{ workspace: item.workspace }} number={item.number} className="min-w-0 truncate font-medium hover:underline">
203 {item.title} <span className="font-normal text-faint">#{item.number}</span>
204 </RefLink>
205 </div>
206 );
207}
208
209export default function CommitPage({ loaderData, actionData, params }: Route.ComponentProps) {
210 const { commit, pull, comparison, checks, comments, commentsOn, closed, viewer, canModerate } = loaderData;
211 // Comments that could not be read count as none; the list says so in its place.
212 const said = asComments(isFailed(comments) ? [] : comments);
213 const general = said.filter((comment) => !comment.path);
214 const base = `/${params.owner}/${params.repo}`;
215 const { subject, body, trailers } = parseCommitMessage(commit.message);
216 return (
217 <div>
218 <Card asChild className="overflow-hidden">
219 <section>
220 <div className="p-5">
221 <p className="flex items-center gap-2 text-xs text-faint">
222 <GitCommitHorizontal size={14} />
223 <Link to={`${base}/commits`} className="hover:text-fg">
224 Commit
225 </Link>
226 </p>
227 <h2 className="mt-2 text-xl font-semibold tracking-tight text-balance">
228 <CommitText text={subject} base={base} />
229 </h2>
230 {body && (
231 <p className="mt-3 max-w-3xl text-sm whitespace-pre-wrap text-muted">
232 <CommitText text={body} base={base} />
233 </p>
234 )}
235 {trailers.length > 0 && (
236 <dl className="mt-3 space-y-0.5 font-mono text-xs text-faint">
237 {trailers.map((trailer) => (
238 <div key={`${trailer.key}:${trailer.value}`}>
239 <dt className="inline">{trailer.key}:</dt> <dd className="inline text-muted">{trailer.value}</dd>
240 </div>
241 ))}
242 </dl>
243 )}
244 </div>
245 <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">
246 <span className="flex items-center gap-2">
247 <CommitAvatars commit={commit} size={20} />
248 <span className="font-medium">
249 <CommitNames commit={commit} all />
250 </span>
251 <span className="text-muted">
252 committed <TimeAgo at={commit.authoredAt} />
253 </span>
254 </span>
255 <span className="flex items-center gap-2 text-xs text-muted">
256 {commit.parents.length === 0 ? (
257 "The first commit"
258 ) : (
259 <>
260 {commit.parents.length === 1 ? "Parent" : "Parents"}
261 {commit.parents.map((parent) => (
262 <Link
263 key={parent}
264 to={`${base}/commit/${parent}`}
265 prefetch="intent"
266 className="font-mono text-fg/80 hover:text-accent hover:underline"
267 >
268 {parent.slice(0, 7)}
269 </Link>
270 ))}
271 </>
272 )}
273 </span>
274 <span className="ml-auto flex items-center gap-2">
275 <CommitChecksBadge checks={checks} sha={commit.hash} />
276 <Link
277 to={`${base}/tree/${commit.hash}/`}
278 className="rounded-md px-2 py-1 text-xs text-muted hover:bg-raised hover:text-fg"
279 >
280 Browse files
281 </Link>
282 <CopyHash hash={commit.hash} />
283 </span>
284 </div>
285 <Suspense
286 fallback={
287 <div aria-busy="true" className="flex h-12 items-center gap-3 border-t border-line px-4">
288 <Skeleton className="size-4 rounded-full" />
289 <Skeleton className="h-3 w-64 max-w-[60%]" />
290 </div>
291 }
292 >
293 <Await resolve={pull}>
294 {(pull) =>
295 isFailed(pull) ? (
296 <div className="border-t border-line px-5 py-3">
297 <Unavailable what={pull.what} compact />
298 </div>
299 ) : pull ? (
300 <MergedIn base={base} pull={pull} />
301 ) : null
302 }
303 </Await>
304 </Suspense>
305 {isFailed(closed) ? (
306 <div className="border-t border-line px-5 py-3">
307 <Unavailable what={closed.what} compact />
308 </div>
309 ) : (
310 closed.map((item) => <ClosedItemRow key={`${item.workspace}#${item.number}`} item={item} />)
311 )}
312 </section>
313 </Card>
314 <div className="mt-6">
315 <DiffView
316 comparison={comparison}
317 repo={base}
318 empty="This commit changes no files."
319 fileBase={`${base}/blob/${commit.hash}`}
320 review={{ comments: said.filter((comment) => comment.path), canComment: viewer != null && commentsOn }}
321 />
322 </div>
323 <section aria-labelledby="commit-comments" className="mt-10 space-y-4">
324 <h3 id="commit-comments" className="flex items-center gap-2 text-sm font-medium">
325 <MessagesSquare size={15} className="text-faint" />
326 {general.length === 0 ? "Comments" : `${general.length} ${general.length === 1 ? "comment" : "comments"}`}
327 {said.length > general.length && (
328 <span className="font-normal text-faint">
329 · {said.length - general.length} on lines above
330 </span>
331 )}
332 </h3>
333 {isFailed(comments) && <Unavailable what={comments.what} />}
334 <CommentList
335 comments={general}
336 base={base}
337 // Commit comments name their author by username.
338 viewerId={viewer?.username ?? null}
339 canModerate={canModerate}
340 failed={actionData && "comment" in actionData ? { comment: String(actionData.comment), error: actionData.error } : null}
341 />
342 {commentsOn ? (
343 <CommentForm author={viewer?.username ?? null} resetKey={said.length} />
344 ) : (
345 <Card className="flex items-center gap-2.5 px-4 py-3 text-sm text-muted">
346 <MessageSquareOff size={15} className="shrink-0 text-faint" />
347 Comments on commits are turned off in this repository.
348 </Card>
349 )}
350 {actionData?.action === "comment" && <ErrorText>{actionData.error}</ErrorText>}
351 </section>
352 </div>
353 );
354}