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.

351 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 { ClosedIssue, 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 { IssueIcon } 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 issues it closed: never
62 // cached, read beside the commit. Its comments and the issues it closed
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 issues it closed"),
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 issues its message closed (`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/** An issue the commit's message closed when it was pushed. */
194function ClosedIssueRow({ base, issue }: { base: string; issue: ClosedIssue }) {
195 return (
196 <div className="flex items-center gap-2 border-t border-line px-5 py-3 text-sm">
197 <IssueIcon issue={{ state: "closed", reason: "completed" }} size={15} />
198 <span className="text-muted">Closed</span>
199 <RefLink repo={base.slice(1)} number={issue.number} className="min-w-0 truncate font-medium hover:underline">
200 {issue.title} <span className="font-normal text-faint">#{issue.number}</span>
201 </RefLink>
202 </div>
203 );
204}
205
206export default function CommitPage({ loaderData, actionData, params }: Route.ComponentProps) {
207 const { commit, pull, comparison, checks, comments, commentsOn, closed, viewer, canModerate } = loaderData;
208 // Comments that could not be read count as none; the list says so in its place.
209 const said = asComments(isFailed(comments) ? [] : comments);
210 const general = said.filter((comment) => !comment.path);
211 const base = `/${params.owner}/${params.repo}`;
212 const { subject, body, trailers } = parseCommitMessage(commit.message);
213 return (
214 <div>
215 <Card asChild className="overflow-hidden">
216 <section>
217 <div className="p-5">
218 <p className="flex items-center gap-2 text-xs text-faint">
219 <GitCommitHorizontal size={14} />
220 <Link to={`${base}/commits`} className="hover:text-fg">
221 Commit
222 </Link>
223 </p>
224 <h2 className="mt-2 text-xl font-semibold tracking-tight text-balance">
225 <CommitText text={subject} base={base} />
226 </h2>
227 {body && (
228 <p className="mt-3 max-w-3xl text-sm whitespace-pre-wrap text-muted">
229 <CommitText text={body} base={base} />
230 </p>
231 )}
232 {trailers.length > 0 && (
233 <dl className="mt-3 space-y-0.5 font-mono text-xs text-faint">
234 {trailers.map((trailer) => (
235 <div key={`${trailer.key}:${trailer.value}`}>
236 <dt className="inline">{trailer.key}:</dt> <dd className="inline text-muted">{trailer.value}</dd>
237 </div>
238 ))}
239 </dl>
240 )}
241 </div>
242 <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">
243 <span className="flex items-center gap-2">
244 <CommitAvatars commit={commit} size={20} />
245 <span className="font-medium">
246 <CommitNames commit={commit} all />
247 </span>
248 <span className="text-muted">
249 committed <TimeAgo at={commit.authoredAt} />
250 </span>
251 </span>
252 <span className="flex items-center gap-2 text-xs text-muted">
253 {commit.parents.length === 0 ? (
254 "The first commit"
255 ) : (
256 <>
257 {commit.parents.length === 1 ? "Parent" : "Parents"}
258 {commit.parents.map((parent) => (
259 <Link
260 key={parent}
261 to={`${base}/commit/${parent}`}
262 prefetch="intent"
263 className="font-mono text-fg/80 hover:text-accent hover:underline"
264 >
265 {parent.slice(0, 7)}
266 </Link>
267 ))}
268 </>
269 )}
270 </span>
271 <span className="ml-auto flex items-center gap-2">
272 <CommitChecksBadge checks={checks} sha={commit.hash} />
273 <Link
274 to={`${base}/tree/${commit.hash}/`}
275 className="rounded-md px-2 py-1 text-xs text-muted hover:bg-raised hover:text-fg"
276 >
277 Browse files
278 </Link>
279 <CopyHash hash={commit.hash} />
280 </span>
281 </div>
282 <Suspense
283 fallback={
284 <div aria-busy="true" className="flex h-12 items-center gap-3 border-t border-line px-4">
285 <Skeleton className="size-4 rounded-full" />
286 <Skeleton className="h-3 w-64 max-w-[60%]" />
287 </div>
288 }
289 >
290 <Await resolve={pull}>
291 {(pull) =>
292 isFailed(pull) ? (
293 <div className="border-t border-line px-5 py-3">
294 <Unavailable what={pull.what} compact />
295 </div>
296 ) : pull ? (
297 <MergedIn base={base} pull={pull} />
298 ) : null
299 }
300 </Await>
301 </Suspense>
302 {isFailed(closed) ? (
303 <div className="border-t border-line px-5 py-3">
304 <Unavailable what={closed.what} compact />
305 </div>
306 ) : (
307 closed.map((issue) => <ClosedIssueRow key={issue.number} base={base} issue={issue} />)
308 )}
309 </section>
310 </Card>
311 <div className="mt-6">
312 <DiffView
313 comparison={comparison}
314 repo={base}
315 empty="This commit changes no files."
316 fileBase={`${base}/blob/${commit.hash}`}
317 review={{ comments: said.filter((comment) => comment.path), canComment: viewer != null && commentsOn }}
318 />
319 </div>
320 <section aria-labelledby="commit-comments" className="mt-10 space-y-4">
321 <h3 id="commit-comments" className="flex items-center gap-2 text-sm font-medium">
322 <MessagesSquare size={15} className="text-faint" />
323 {general.length === 0 ? "Comments" : `${general.length} ${general.length === 1 ? "comment" : "comments"}`}
324 {said.length > general.length && (
325 <span className="font-normal text-faint">
326 · {said.length - general.length} on lines above
327 </span>
328 )}
329 </h3>
330 {isFailed(comments) && <Unavailable what={comments.what} />}
331 <CommentList
332 comments={general}
333 base={base}
334 // Commit comments name their author by username.
335 viewerId={viewer?.username ?? null}
336 canModerate={canModerate}
337 failed={actionData && "comment" in actionData ? { comment: String(actionData.comment), error: actionData.error } : null}
338 />
339 {commentsOn ? (
340 <CommentForm author={viewer?.username ?? null} resetKey={said.length} />
341 ) : (
342 <Card className="flex items-center gap-2.5 px-4 py-3 text-sm text-muted">
343 <MessageSquareOff size={15} className="shrink-0 text-faint" />
344 Comments on commits are turned off in this repository.
345 </Card>
346 )}
347 {actionData?.action === "comment" && <ErrorText>{actionData.error}</ErrorText>}
348 </section>
349 </div>
350 );
351}