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.

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