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.

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