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.

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