flagon-io/g1t

public

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/apps/web/app/routes/repo/commit.tsx

185 lines7,946 bytesCodeBlame
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 type { Route } from "./+types/commit";
8import { DiffView } from "../../components/diff-view";
9import { Avatar, TimeAgo } from "../../components/ui";
10import { immutable } from "../../lib/immutable.server";
11import { pullForCommit } from "../../lib/provenance.server";
12import { repos } from "../../lib/services.server";
13import { getViewer, unwrap } from "../../lib/session.server";
14
15export function headers({ loaderHeaders }: Route.HeadersArgs) {
16 return { "Server-Timing": loaderHeaders.get("Server-Timing") ?? "" };
17}
18
19export function meta({ loaderData, params }: Route.MetaArgs) {
20 const subject = loaderData?.commit.message.split("\n")[0];
21 return [
22 { title: `${subject ? `${subject} · ` : ""}${params.hash.slice(0, 7)} · ${params.owner}/${params.repo} · g1t` },
23 ];
24}
25
26/** How far back a short hash is looked for. */
27const SHORT_HASH_SEARCH = 300;
28
29export async function loader({ params, context }: Route.LoaderArgs) {
30 const viewer = getViewer(context);
31 const path = { namespace: params.owner, name: params.repo };
32 const hash = params.hash.toLowerCase();
33 if (!/^[0-9a-f]{4,40}$/.test(hash)) throw data(null, { status: 404 });
34 if (hash.length < 40) {
35 // A short hash: find the commit it names and go to its full address.
36 const log = await repos.log(path, viewer, null, SHORT_HASH_SEARCH);
37 const matches = log.ok ? log.value.filter((commit) => commit.hash.startsWith(hash)) : [];
38 if (matches.length === 1) throw redirect(`/${params.owner}/${params.repo}/commit/${matches[0]!.hash}`);
39 throw new Response("Commit not found.", { status: 404 });
40 }
41 const started = Date.now();
42 const found = unwrap(await repos.get(path, viewer));
43 // The viewer may read the repository, and a commit never changes: after
44 // the first visit it and its diff come from the cache.
45 let cached = true;
46 const loaded = await immutable(`commit:${found.id}:${hash}`, async () => {
47 cached = false;
48 // At once: a commit is compared with its first parent, so the diff
49 // does not wait for the commit.
50 const [log, compared] = await Promise.all([
51 repos.log(path, viewer, hash, 1),
52 repos.compare(found.id, viewer, null, hash),
53 ]);
54 const commit = log.ok ? log.value[0] : undefined;
55 if (!commit) return null;
56 const comparison: Comparison = compared.ok
57 ? compared.value
58 : { base: null, head: commit.hash, files: [], truncated: false };
59 return { commit, comparison };
60 });
61 if (!loaded) throw new Response("Commit not found.", { status: 404 });
62 return data(
63 {
64 ...loaded,
65 // Streamed: the page shows the commit while this is worked out.
66 pull: pullForCommit(path, viewer, loaded.commit.hash),
67 },
68 { headers: { "Server-Timing": `load;dur=${Date.now() - started};desc="${cached ? "cached" : "read"}"` } },
69 );
70}
71
72function CopyHash({ hash }: { hash: string }) {
73 const [copied, setCopied] = useState(false);
74 return (
75 <button
76 type="button"
77 onClick={() => {
78 void navigator.clipboard?.writeText(hash).then(() => {
79 setCopied(true);
80 setTimeout(() => setCopied(false), 1500);
81 });
82 }}
83 className="flex items-center gap-1.5 rounded-md border border-line bg-bg px-2 py-1 font-mono text-xs text-muted transition-colors hover:border-line-strong hover:text-fg"
84 aria-label="Copy the full hash"
85 >
86 {hash.slice(0, 12)}
87 {copied ? <Check size={12} className="text-accent" /> : <Copy size={12} />}
88 </button>
89 );
90}
91
92/** The pull request a commit arrived in, once it has been worked out. */
93function MergedIn({ base, pull }: { base: string; pull: Pull }) {
94 const byAgent = pull.runtime === "hosted";
95 return (
96 <div className="flex flex-wrap items-center gap-x-4 gap-y-2 border-t border-line px-5 py-3 text-sm">
97 <span className="flex items-center gap-2">
98 <GitPullRequest size={15} className="text-merged" />
99 <span className="text-muted">Merged in</span>
100 <Link to={`${base}/pull/${pull.number}`} className="font-medium hover:underline">
101 {pull.title} <span className="font-normal text-faint">#{pull.number}</span>
102 </Link>
103 </span>
104 {byAgent && (
105 <span className="flex items-center gap-1.5 rounded-full border border-merged/30 bg-merged/10 px-2 py-0.5 text-xs text-merged">
106 <Sparkles size={12} />
107 written by {pull.agent}
108 </span>
109 )}
110 <Link
111 to={`${base}/pull/${pull.number}?tab=session`}
112 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"
113 >
114 <MessagesSquare size={13} />
115 Why it was written
116 </Link>
117 </div>
118 );
119}
120
121export default function CommitPage({ loaderData, params }: Route.ComponentProps) {
122 const { commit, pull, comparison } = loaderData;
123 const base = `/${params.owner}/${params.repo}`;
124 const [subject, ...rest] = commit.message.split("\n");
125 const body = rest.join("\n").trim();
126 return (
127 <div>
128 <section className="overflow-hidden rounded-xl border border-line bg-surface">
129 <div className="p-5">
130 <p className="flex items-center gap-2 text-xs text-faint">
131 <GitCommitHorizontal size={14} />
132 <Link to={`${base}/commits`} className="hover:text-fg">
133 Commit
134 </Link>
135 </p>
136 <h2 className="mt-2 text-xl font-semibold tracking-tight text-balance">{subject}</h2>
137 {body && <p className="mt-3 max-w-3xl text-sm whitespace-pre-wrap text-muted">{body}</p>}
138 </div>
139 <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">
140 <span className="flex items-center gap-2">
141 <Avatar name={commit.author.name} size={20} />
142 <span className="font-medium">{commit.author.name}</span>
143 <span className="text-muted">
144 committed <TimeAgo at={commit.authoredAt} />
145 </span>
146 </span>
147 <span className="flex items-center gap-2 text-xs text-muted">
148 {commit.parents.length === 0 ? (
149 "The first commit"
150 ) : (
151 <>
152 {commit.parents.length === 1 ? "Parent" : "Parents"}
153 {commit.parents.map((parent) => (
154 <Link
155 key={parent}
156 to={`${base}/commit/${parent}`}
157 prefetch="intent"
158 className="font-mono text-fg/80 hover:text-accent hover:underline"
159 >
160 {parent.slice(0, 7)}
161 </Link>
162 ))}
163 </>
164 )}
165 </span>
166 <span className="ml-auto flex items-center gap-2">
167 <Link
168 to={`${base}/tree/${commit.hash}/`}
169 className="rounded-md px-2 py-1 text-xs text-muted hover:bg-raised hover:text-fg"
170 >
171 Browse files
172 </Link>
173 <CopyHash hash={commit.hash} />
174 </span>
175 </div>
176 <Suspense fallback={<div className="h-12 animate-pulse border-t border-line bg-raised/30" />}>
177 <Await resolve={pull}>{(pull) => (pull ? <MergedIn base={base} pull={pull} /> : null)}</Await>
178 </Suspense>
179 </section>
180 <div className="mt-6">
181 <DiffView comparison={comparison} empty="This commit changes no files." fileBase={`${base}/blob/${commit.hash}`} />
182 </div>
183 </div>
184 );
185}