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