| 1 | /** @jsxImportSource hono/jsx */ |
| 2 | import { raw } from "hono/html"; |
| 3 | import type { Child, FC } from "hono/jsx"; |
| 4 | import type { AppContext } from "../auth/principal.js"; |
| 5 | import { loadRepo } from "../http/common.js"; |
| 6 | import { topicsOf } from "../http/gh.js"; |
| 7 | import type { Repo } from "../lib/directory.js"; |
| 8 | import { HttpError } from "../lib/util.js"; |
| 9 | import { parseAutoMergeDefault } from "../repo/auto-merge.js"; |
| 10 | import { atLeast, globToRegExp } from "../repo/types.js"; |
| 11 | import { ICONS } from "./assets.js"; |
| 12 | import { KCheckbox, KRadio, KSelect } from "./kumo.js"; |
| 13 | import { csrfToken, type FormData } from "./csrf.js"; |
| 14 | import { CheckName } from "./checks.js"; |
| 15 | import { ReleasesSection } from "./releases.js"; |
| 16 | import { highlightLines, langForPath } from "./highlight.js"; |
| 17 | import { |
| 18 | CommitRow, |
| 19 | CopyButton, |
| 20 | DiffStats, |
| 21 | DiffView, |
| 22 | FileSummary, |
| 23 | Form, |
| 24 | Markdown, |
| 25 | Pager, |
| 26 | RefSwitcher, |
| 27 | Time, |
| 28 | act, |
| 29 | cloneUrl, |
| 30 | encPath, |
| 31 | firstLine, |
| 32 | fmtBytes, |
| 33 | pageNum, |
| 34 | post, |
| 35 | qs, |
| 36 | refNames, |
| 37 | render, |
| 38 | repoUrl, |
| 39 | restOfPath, |
| 40 | shortSha, |
| 41 | splitRefPath, |
| 42 | statusOf, |
| 43 | Status, |
| 44 | tokens, |
| 45 | type DiffFile, |
| 46 | type WebApp, |
| 47 | prm, |
| 48 | } from "./ui.js"; |
| 49 | |
| 50 | type Loaded = Awaited<ReturnType<typeof loadRepo>>; |
| 51 | |
| 52 | const IMAGE_TYPES: Record<string, string> = { png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp", avif: "image/avif", ico: "image/x-icon", bmp: "image/bmp", svg: "image/svg+xml" }; |
| 53 | const MAX_RENDER = 1024 * 1024; |
| 54 | |
| 55 | const extOf = (path: string): string => (/\.([A-Za-z0-9]+)$/.exec(path)?.[1] ?? "").toLowerCase(); |
| 56 | const isMarkdown = (path: string): boolean => /\.(md|markdown|mdown|mkd)$/i.test(path); |
| 57 | const decoder = () => new TextDecoder(); |
| 58 | |
| 59 | /** Normalise a user-supplied repository path; null when invalid. */ |
| 60 | function cleanPath(p: string): string | null { |
| 61 | const segs = p.replace(/\\/g, "/").split("/").filter((s) => s && s !== "."); |
| 62 | if (!segs.length || segs.some((s) => s === ".." || s === ".git")) return null; |
| 63 | return segs.join("/"); |
| 64 | } |
| 65 | |
| 66 | const Crumbs: FC<{ base: string; ref: string; path: string; last?: boolean }> = ({ base, ref, path, last }) => { |
| 67 | const segs = path ? path.split("/") : []; |
| 68 | return ( |
| 69 | <div class="crumbs"> |
| 70 | <a href={`${base}/tree/${encPath(ref)}`}>{base.split("/")[2]}</a> |
| 71 | {segs.map((s, i) => ( |
| 72 | <> |
| 73 | <span class="faint">/</span> |
| 74 | {i === segs.length - 1 && last !== false ? <b>{s}</b> : <a href={`${base}/tree/${encPath(ref)}/${encPath(segs.slice(0, i + 1).join("/"))}`}>{s}</a>} |
| 75 | </> |
| 76 | ))} |
| 77 | </div> |
| 78 | ); |
| 79 | }; |
| 80 | |
| 81 | const CloneBox: FC<{ url: string }> = ({ url }) => ( |
| 82 | <div class="clone"> |
| 83 | <input type="text" readonly value={url} aria-label="Clone URL" /> |
| 84 | <CopyButton text={url} size="base" /> |
| 85 | </div> |
| 86 | ); |
| 87 | |
| 88 | /** |
| 89 | * Clone straight into an editor: the editors' own clone links (VS Code's Git extension handles /clone in VS Code and |
| 90 | * the editors built on it; JetBrains Toolbox handles jetbrains://). They work without Diffinery's extension, which |
| 91 | * adds sign-in for private repositories (docs/repositories/clone-in-your-editor.md). |
| 92 | */ |
| 93 | export const EDITORS: Array<{ label: string; link: (url: string) => string }> = [ |
| 94 | { label: "VS Code", link: (u) => `vscode://vscode.git/clone?url=${encodeURIComponent(u)}` }, |
| 95 | { label: "Cursor", link: (u) => `cursor://vscode.git/clone?url=${encodeURIComponent(u)}` }, |
| 96 | { label: "Windsurf", link: (u) => `windsurf://vscode.git/clone?url=${encodeURIComponent(u)}` }, |
| 97 | { label: "IntelliJ IDEA", link: (u) => `jetbrains://idea/checkout/git?idea.required.plugins.id=Git4Idea&checkout.repo=${encodeURIComponent(u)}` }, |
| 98 | ]; |
| 99 | |
| 100 | const OpenInEditor: FC<{ url: string }> = ({ url }) => ( |
| 101 | <div class="openin"> |
| 102 | <span class="small muted">Open in</span> |
| 103 | {EDITORS.map((e) => ( |
| 104 | <a class="btn sm" href={e.link(url)} rel="nofollow"> |
| 105 | {e.label} |
| 106 | </a> |
| 107 | ))} |
| 108 | </div> |
| 109 | ); |
| 110 | |
| 111 | const QuickSetup: FC<{ c: AppContext; l: Loaded }> = ({ c, l }) => { |
| 112 | const url = cloneUrl(c, l.repo); |
| 113 | const b = l.repo.default_branch; |
| 114 | const base = repoUrl(l.repo); |
| 115 | const canWrite = atLeast(l.caller.role, "write"); |
| 116 | return ( |
| 117 | <div style="max-width:900px"> |
| 118 | <div class="box"> |
| 119 | <div class="head"> |
| 120 | <h2>Quick setup</h2> |
| 121 | <span class="muted small">This repository is empty.</span> |
| 122 | </div> |
| 123 | <div class="body"> |
| 124 | <CloneBox url={url} /> |
| 125 | <OpenInEditor url={url} /> |
| 126 | {canWrite ? ( |
| 127 | <p class="mt muted"> |
| 128 | Get started by <a href={`${base}/new/${encPath(b)}?filename=README.md`}>creating a README on the web</a>, or push an existing repository from the command line. |
| 129 | </p> |
| 130 | ) : null} |
| 131 | <h3 class="mt">…create a new repository on the command line</h3> |
| 132 | <pre class="cmd">{`echo "# ${l.repo.name}" >> README.md\ngit init -b ${b}\ngit add README.md\ngit commit -m "first commit"\ngit remote add origin ${url}\ngit push -u origin ${b}`}</pre> |
| 133 | <h3>…or push an existing repository</h3> |
| 134 | <pre class="cmd">{`git remote add origin ${url}\ngit push -u origin ${b}`}</pre> |
| 135 | <h3>Authentication</h3> |
| 136 | <p class="muted"> |
| 137 | When Git asks for credentials, use your username and a <a href="/settings/tokens">personal access token</a> as the password. To avoid typing it every time, run <code>git config --global credential.helper store</code> (or use |
| 138 | your OS keychain helper). Git 2.26 or newer is required. In VS Code, Cursor or Windsurf, the <a href="/docs/repositories/clone-in-your-editor">Diffinery extension</a> signs Git in for you. |
| 139 | </p> |
| 140 | <p class="muted m0"> |
| 141 | Workflows in <code>.github/workflows/*.yml</code> run automatically on push. AI agents should use their own <a href="/settings/agents">agent account and token</a>. |
| 142 | </p> |
| 143 | </div> |
| 144 | </div> |
| 145 | </div> |
| 146 | ); |
| 147 | }; |
| 148 | |
| 149 | const NoDefaultBranch: FC<{ base: string; branch: string; names: { branches: string[]; tags: string[] } }> = ({ base, branch, names }) => ( |
| 150 | <div class="box" style="max-width:900px"> |
| 151 | <div class="head"> |
| 152 | <h2>No {branch} branch yet</h2> |
| 153 | <span class="muted small"> |
| 154 | The default branch, <code>{branch}</code>, hasn't been pushed. Other branches have: |
| 155 | </span> |
| 156 | </div> |
| 157 | <div class="body"> |
| 158 | <ul class="m0"> |
| 159 | {names.branches.slice(0, 100).map((b) => ( |
| 160 | <li> |
| 161 | <a href={`${base}/tree/${encPath(b)}`}>{b}</a> |
| 162 | </li> |
| 163 | ))} |
| 164 | </ul> |
| 165 | </div> |
| 166 | </div> |
| 167 | ); |
| 168 | |
| 169 | async function treePage(c: AppContext, l: Loaded, ref: string, path: string, root: boolean): Promise<Response> { |
| 170 | const { repo, caller, stub } = l; |
| 171 | const base = repoUrl(repo); |
| 172 | const [tree, names, stats, last, releases] = await Promise.all([ |
| 173 | stub.tree(ref, path), |
| 174 | refNames(stub), |
| 175 | root && !path ? stub.stats() : Promise.resolve(null), |
| 176 | !path ? stub.log(ref, { limit: 1 }).catch(() => []) : Promise.resolve([]), |
| 177 | root && !path ? stub.releaseSummary(caller).catch(() => null) : Promise.resolve(null), |
| 178 | ]); |
| 179 | const counts = stats ? { issues: stats.openIssues, pulls: stats.openPulls } : undefined; |
| 180 | if (!tree) { |
| 181 | if (!names.branches.length && !names.tags.length) { |
| 182 | return render(c, { title: `${repo.owner_login}/${repo.name}`, repo: { repo, caller, tab: "code", counts } }, <QuickSetup c={c} l={l} />); |
| 183 | } |
| 184 | // Branches were pushed, but not the default one: say so and list them rather than answer 404. |
| 185 | if (root && !path && ref === repo.default_branch) { |
| 186 | return render(c, { title: `${repo.owner_login}/${repo.name}`, repo: { repo, caller, tab: "code", counts } }, <NoDefaultBranch base={base} branch={ref} names={names} />); |
| 187 | } |
| 188 | const blob = path ? await stub.blob(ref, path).catch(() => null) : null; |
| 189 | if (blob) return c.redirect(`${base}/blob/${encPath(ref)}/${encPath(path)}`, 302); |
| 190 | throw new HttpError(404, "path not found"); |
| 191 | } |
| 192 | const readme = tree.items.find((i) => i.type === "blob" && /^readme(\.(md|markdown|txt))?$/i.test(i.name)); |
| 193 | const readmeBlob = readme && (readme.size ?? 0) < MAX_RENDER ? await stub.blob(ref, readme.path).catch(() => null) : null; |
| 194 | const head = last[0]; |
| 195 | const canWrite = atLeast(caller.role, "write") && names.branches.includes(ref); |
| 196 | const main = ( |
| 197 | <div> |
| 198 | <div class="row between mb"> |
| 199 | <div class="row"> |
| 200 | <RefSwitcher current={ref} branches={names.branches} tags={names.tags} to={(r) => `${base}/tree/${encPath(r)}${path ? `/${encPath(path)}` : ""}`} /> |
| 201 | {path ? <Crumbs base={base} ref={ref} path={path} /> : null} |
| 202 | {!path ? ( |
| 203 | <span class="muted small"> |
| 204 | <a href={`${base}/branches`}> |
| 205 | {raw(ICONS.branch)} {names.branches.length} branch{names.branches.length === 1 ? "" : "es"} |
| 206 | </a>{" "} |
| 207 | ·{" "} |
| 208 | <a href={`${base}/tags`}> |
| 209 | {raw(ICONS.tag)} {names.tags.length} tag{names.tags.length === 1 ? "" : "s"} |
| 210 | </a> |
| 211 | </span> |
| 212 | ) : null} |
| 213 | </div> |
| 214 | <div class="row"> |
| 215 | {canWrite ? ( |
| 216 | <a class="btn sm" href={`${base}/new/${encPath(ref)}${path ? `/${encPath(path)}` : ""}`}> |
| 217 | {raw(ICONS.plus)} Add file |
| 218 | </a> |
| 219 | ) : null} |
| 220 | <a class="btn sm" href={`${base}/commits/${encPath(ref)}${path ? qs({ path }) : ""}`}> |
| 221 | {raw(ICONS.history)} History |
| 222 | </a> |
| 223 | </div> |
| 224 | </div> |
| 225 | <div class="box"> |
| 226 | {head ? ( |
| 227 | <div class="head small"> |
| 228 | <b>{head.author.name}</b> |
| 229 | <a href={`${base}/commit/${head.sha}`} class="grow" style="color:var(--fg);overflow:hidden;text-overflow:ellipsis;white-space:nowrap"> |
| 230 | {firstLine(head.message)} |
| 231 | </a> |
| 232 | <a class="sha" href={`${base}/commit/${head.sha}`}> |
| 233 | {shortSha(head.sha)} |
| 234 | </a> |
| 235 | <Time at={new Date(head.committer.timestamp * 1000).toISOString()} /> |
| 236 | </div> |
| 237 | ) : null} |
| 238 | <table class="files"> |
| 239 | {path ? ( |
| 240 | <tr> |
| 241 | <td class="ic" /> |
| 242 | <td colspan={2}> |
| 243 | <a href={`${base}/tree/${encPath(ref)}${path.includes("/") ? `/${encPath(path.split("/").slice(0, -1).join("/"))}` : ""}`}>..</a> |
| 244 | </td> |
| 245 | </tr> |
| 246 | ) : null} |
| 247 | {tree.items.map((it) => ( |
| 248 | <tr> |
| 249 | <td class={`ic ${it.type === "tree" ? "ic-dir" : ""}`}>{raw(it.type === "tree" ? ICONS.dir : it.type === "commit" ? ICONS.submodule : ICONS.file)}</td> |
| 250 | <td> |
| 251 | {it.type === "commit" ? ( |
| 252 | <span> |
| 253 | {it.name} <span class="faint mono small">@ {shortSha(it.oid)}</span> |
| 254 | </span> |
| 255 | ) : ( |
| 256 | <a href={`${base}/${it.type === "tree" ? "tree" : "blob"}/${encPath(ref)}/${encPath(it.path)}`}>{it.name}</a> |
| 257 | )} |
| 258 | </td> |
| 259 | <td class="sz">{it.type === "blob" ? fmtBytes(it.size) : ""}</td> |
| 260 | </tr> |
| 261 | ))} |
| 262 | </table> |
| 263 | {tree.items.length === 0 ? <div class="empty">This directory is empty.</div> : null} |
| 264 | </div> |
| 265 | {readmeBlob && !readmeBlob.binary ? ( |
| 266 | <div class="box readme"> |
| 267 | <div class="head"> |
| 268 | {raw(ICONS.file)} <b>{readme!.name}</b> |
| 269 | </div> |
| 270 | <div class="body"> |
| 271 | {isMarkdown(readme!.name) ? ( |
| 272 | <Markdown text={decoder().decode(readmeBlob.content)} base={{ owner: repo.owner_login, repo: repo.name, ref, dir: path }} /> |
| 273 | ) : ( |
| 274 | <pre style="white-space:pre-wrap;margin:0">{decoder().decode(readmeBlob.content)}</pre> |
| 275 | )} |
| 276 | </div> |
| 277 | </div> |
| 278 | ) : null} |
| 279 | </div> |
| 280 | ); |
| 281 | if (path) return render(c, { title: `${path} at ${ref} · ${repo.owner_login}/${repo.name}`, repo: { repo, caller, tab: "code", ref } }, main); |
| 282 | return render( |
| 283 | c, |
| 284 | { title: `${repo.owner_login}/${repo.name}`, repo: { repo, caller, tab: "code", ref, counts }, jsonLd: repo.visibility === "public" ? [sourceCodeLd(c, repo, tree.items, ref)] : undefined }, |
| 285 | <div class="grid"> |
| 286 | {main} |
| 287 | <aside class="side"> |
| 288 | <section> |
| 289 | <h3>Clone</h3> |
| 290 | <CloneBox url={cloneUrl(c, repo)} /> |
| 291 | <OpenInEditor url={cloneUrl(c, repo)} /> |
| 292 | <p class="small muted" style="margin-top:6px"> |
| 293 | Use a <a href="/settings/tokens">token</a> as the password, or <a href="/docs/repositories/clone-in-your-editor">sign in from your editor</a>. |
| 294 | </p> |
| 295 | </section> |
| 296 | <section> |
| 297 | <h3>About</h3> |
| 298 | <p class={repo.description ? "" : "muted"}>{repo.description || "No description."}</p> |
| 299 | {repo.homepage ? ( |
| 300 | <p> |
| 301 | <a href={repo.homepage} rel="noopener nofollow ugc"> |
| 302 | {repo.homepage.replace(/^https?:\/\//, "").replace(/\/$/, "")} |
| 303 | </a> |
| 304 | </p> |
| 305 | ) : null} |
| 306 | {stats ? ( |
| 307 | <dl class="kv"> |
| 308 | <dt>Default branch</dt> |
| 309 | <dd class="mono">{repo.default_branch}</dd> |
| 310 | <dt>Open issues</dt> |
| 311 | <dd> |
| 312 | <a href={`${base}/issues`}>{stats.openIssues}</a> |
| 313 | </dd> |
| 314 | <dt>Open pull requests</dt> |
| 315 | <dd> |
| 316 | <a href={`${base}/pulls`}>{stats.openPulls}</a> |
| 317 | </dd> |
| 318 | <dt>Refs</dt> |
| 319 | <dd>{stats.refs}</dd> |
| 320 | <dt>Objects</dt> |
| 321 | <dd>{stats.objects.toLocaleString("en-US")}</dd> |
| 322 | <dt>Size</dt> |
| 323 | <dd>{fmtBytes(stats.bytes)}</dd> |
| 324 | <dt>Last push</dt> |
| 325 | <dd>{repo.pushed_at ? <Time at={repo.pushed_at} /> : "never"}</dd> |
| 326 | </dl> |
| 327 | ) : null} |
| 328 | </section> |
| 329 | <ReleasesSection base={base} summary={releases} canWrite={atLeast(caller.role, "write") && !repo.archived} topics={repo.topics} /> |
| 330 | <section> |
| 331 | <h3>Shortcuts</h3> |
| 332 | <p class="small muted m0"> |
| 333 | <kbd>Ctrl</kbd> <kbd>K</kbd> jump anywhere · <kbd>t</kbd> find a file · <kbd>g</kbd> <kbd>i</kbd> issues · <kbd>g</kbd> <kbd>p</kbd> pull requests · <kbd>g</kbd> <kbd>a</kbd> actions |
| 334 | </p> |
| 335 | </section> |
| 336 | </aside> |
| 337 | </div>, |
| 338 | ); |
| 339 | } |
| 340 | |
| 341 | /** schema.org data for a public repository's home page, so search engines and AI assistants can tell what it is. */ |
| 342 | function sourceCodeLd(c: AppContext, repo: Repo, items: { name: string; type: string }[], ref: string): object { |
| 343 | const origin = c.env.PUBLIC_URL.replace(/\/$/, ""); |
| 344 | const url = `${origin}/${repo.owner_login}/${repo.name}`; |
| 345 | const license = items.find((i) => i.type === "blob" && /^(license|licence|copying)(\.(md|txt))?$/i.test(i.name)); |
| 346 | const topics = topicsOf(repo); |
| 347 | return { |
| 348 | "@type": "SoftwareSourceCode", |
| 349 | "@id": `${url}#code`, |
| 350 | name: repo.name, |
| 351 | url, |
| 352 | codeRepository: url, |
| 353 | ...(repo.description ? { description: repo.description } : {}), |
| 354 | ...(topics.length ? { keywords: topics.join(", ") } : {}), |
| 355 | ...(license ? { license: `${url}/blob/${encPath(ref)}/${encPath(license.name)}` } : {}), |
| 356 | ...(repo.pushed_at ? { dateModified: repo.pushed_at } : {}), |
| 357 | author: { "@type": "Organization", name: repo.owner_login, url: `${origin}/${repo.owner_login}` }, |
| 358 | }; |
| 359 | } |
| 360 | |
| 361 | // ---------------------------------------------------------------- editor |
| 362 | |
| 363 | interface EditorValues { |
| 364 | path: string; |
| 365 | content: string; |
| 366 | message: string; |
| 367 | description: string; |
| 368 | choice: "direct" | "branch"; |
| 369 | newBranch: string; |
| 370 | head: string; |
| 371 | } |
| 372 | |
| 373 | const Editor: FC<{ c: AppContext; l: Loaded; ref: string; mode: "edit" | "new"; orig: string; dir: string; v: EditorValues; error?: string; canDirect: boolean }> = ({ c, l, ref, mode, orig, dir, v, error, canDirect }) => { |
| 374 | const base = repoUrl(l.repo); |
| 375 | const t = csrfToken(c); |
| 376 | const action = mode === "edit" ? `${base}/edit/${encPath(ref)}/${encPath(orig)}` : `${base}/new/${encPath(ref)}${dir ? `/${encPath(dir)}` : ""}`; |
| 377 | return ( |
| 378 | <div> |
| 379 | {error ? <div class="flash error">{error}</div> : null} |
| 380 | <Form action={action} t={t}> |
| 381 | <input type="hidden" name="head" value={v.head} /> |
| 382 | <div class="row mb"> |
| 383 | <span class="badge">{raw(ICONS.branch)} {ref}</span> |
| 384 | <div class="grow"> |
| 385 | <input type="text" name="path" value={v.path} required placeholder="path/to/file.ext" aria-label="File path" class="mono" /> |
| 386 | </div> |
| 387 | {mode === "edit" ? ( |
| 388 | <a class="btn sm" href={`${base}/blob/${encPath(ref)}/${encPath(orig)}`}> |
| 389 | Cancel |
| 390 | </a> |
| 391 | ) : null} |
| 392 | </div> |
| 393 | <div class="box"> |
| 394 | <textarea name="content" class="code" spellcheck={false} style="border:0;border-radius:0;min-height:480px" aria-label="File contents"> |
| 395 | {`\n${v.content}`} |
| 396 | </textarea> |
| 397 | </div> |
| 398 | <div class="box"> |
| 399 | <div class="head"> |
| 400 | <h3>Commit changes</h3> |
| 401 | </div> |
| 402 | <div class="body"> |
| 403 | <div class="field"> |
| 404 | <input type="text" name="message" value={v.message} required aria-label="Commit message" /> |
| 405 | </div> |
| 406 | <div class="field"> |
| 407 | <textarea name="description" placeholder="Add an optional extended description…" style="min-height:70px"> |
| 408 | {v.description} |
| 409 | </textarea> |
| 410 | </div> |
| 411 | <div class="field"> |
| 412 | {canDirect ? null : ( |
| 413 | <p class="muted small"> |
| 414 | {raw(ICONS.shield)} <code>{ref}</code> is protected; your change goes to a new branch and a pull request. |
| 415 | </p> |
| 416 | )} |
| 417 | <KRadio |
| 418 | name="choice" |
| 419 | label="Where to commit" |
| 420 | value={canDirect && v.choice === "direct" ? "direct" : "branch"} |
| 421 | items={[ |
| 422 | ...(canDirect |
| 423 | ? [ |
| 424 | { |
| 425 | value: "direct", |
| 426 | label: ( |
| 427 | <> |
| 428 | Commit directly to the <code>{ref}</code> branch |
| 429 | </> |
| 430 | ), |
| 431 | }, |
| 432 | ] |
| 433 | : []), |
| 434 | { value: "branch", label: "Create a new branch for this commit and start a pull request:" }, |
| 435 | ]} |
| 436 | /> |
| 437 | <input type="text" name="new_branch" value={v.newBranch} style="max-width:320px;margin:6px 0 0 24px" class="mono" aria-label="New branch name" /> |
| 438 | </div> |
| 439 | <button class="btn primary">Commit changes</button> |
| 440 | </div> |
| 441 | </div> |
| 442 | </Form> |
| 443 | {mode === "edit" ? ( |
| 444 | <Form action={action} t={t} class="box" confirm={`Delete ${orig}?`}> |
| 445 | <input type="hidden" name="_delete" value="1" /> |
| 446 | <input type="hidden" name="head" value={v.head} /> |
| 447 | <div class="body row between"> |
| 448 | <span class="muted">Delete this file in a new commit on {ref}.</span> |
| 449 | <button class="btn sm danger">Delete file</button> |
| 450 | </div> |
| 451 | </Form> |
| 452 | ) : null} |
| 453 | </div> |
| 454 | ); |
| 455 | }; |
| 456 | |
| 457 | // ---------------------------------------------------------------- compare and pull request creation |
| 458 | |
| 459 | export interface PullFormValues { |
| 460 | title: string; |
| 461 | body: string; |
| 462 | intent: string; |
| 463 | draft: boolean; |
| 464 | /** Turn auto-merge on as it opens; offered only where the base branch has required checks. */ |
| 465 | autoMerge?: boolean; |
| 466 | } |
| 467 | |
| 468 | async function comparePage(c: AppContext, l: Loaded, baseRef: string, headRef: string, form?: { values: PullFormValues; error: string }): Promise<Response> { |
| 469 | const { repo, caller, stub } = l; |
| 470 | const base = repoUrl(repo); |
| 471 | const t = csrfToken(c); |
| 472 | const names = await refNames(stub); |
| 473 | const all = [...names.branches, ...names.tags.filter((x) => !names.branches.includes(x))]; |
| 474 | let cmp: Awaited<ReturnType<typeof stub.compare>> | null = null; |
| 475 | let error: string | null = null; |
| 476 | try { |
| 477 | cmp = await stub.compare(baseRef, headRef); |
| 478 | } catch (e) { |
| 479 | const s = statusOf(e); |
| 480 | if (s.status >= 500) throw e; |
| 481 | error = s.message; |
| 482 | } |
| 483 | const bothBranches = names.branches.includes(baseRef) && names.branches.includes(headRef); |
| 484 | const canPr = c.get("principal").type === "account" && atLeast(caller.role, "write") && bothBranches && !!cmp && cmp.aheadBy > 0; |
| 485 | let existing: number | null = null; |
| 486 | // Auto-merge as it opens: offered where the base has a required check, ticked by the person's own setting. |
| 487 | let offerAutoMerge = false; |
| 488 | if (canPr) { |
| 489 | const [open, rules] = await Promise.all([stub.issues({ kind: "pull", state: "open", limit: 100 }), stub.protectionFor(baseRef)]); |
| 490 | existing = open.items.find((i) => i.pull?.head === headRef && i.pull?.base === baseRef)?.number ?? null; |
| 491 | offerAutoMerge = !!rules?.requiredChecks?.length; |
| 492 | } |
| 493 | const principal = c.get("principal"); |
| 494 | const mySetting = principal.type === "account" ? parseAutoMergeDefault(principal.account.auto_merge) : null; |
| 495 | const defaultTitle = cmp && cmp.commits.length === 1 ? firstLine(cmp.commits[0]!.message) : headRef.replace(/[-_/]+/g, " ").replace(/^\w/, (m) => m.toUpperCase()); |
| 496 | const v = form?.values ?? { title: defaultTitle, body: cmp && cmp.commits.length === 1 ? cmp.commits[0]!.message.split("\n").slice(1).join("\n").trim() : "", intent: "", draft: false }; |
| 497 | return render( |
| 498 | c, |
| 499 | { title: `Comparing ${baseRef}...${headRef}`, repo: { repo, caller, tab: "pulls", ref: headRef }, wide: !!cmp && cmp.files.length > 0 }, |
| 500 | <div> |
| 501 | <h1>Compare changes</h1> |
| 502 | <p class="muted">Choose two branches to see what changed or to start a new pull request.</p> |
| 503 | <form method="get" action={`${base}/compare`} class="box"> |
| 504 | <div class="body row"> |
| 505 | {raw(ICONS.branch)} |
| 506 | <span class="row" style="gap:6px"> |
| 507 | base: |
| 508 | <KSelect name="base" size="sm" label="Base branch" value={all.includes(baseRef) ? baseRef : undefined} options={all.map((n) => ({ value: n, label: n }))} /> |
| 509 | </span> |
| 510 | <span class="faint">←</span> |
| 511 | <span class="row" style="gap:6px"> |
| 512 | compare: |
| 513 | <KSelect name="head" size="sm" label="Compare branch" value={all.includes(headRef) ? headRef : undefined} options={all.map((n) => ({ value: n, label: n }))} /> |
| 514 | </span> |
| 515 | <button class="btn sm">Compare</button> |
| 516 | {cmp ? ( |
| 517 | <span class="muted small" style="margin-left:auto"> |
| 518 | {cmp.aheadBy} commit{cmp.aheadBy === 1 ? "" : "s"} ahead, {cmp.behindBy} behind {baseRef} |
| 519 | </span> |
| 520 | ) : null} |
| 521 | </div> |
| 522 | </form> |
| 523 | {error ? <div class="flash error">{error}</div> : null} |
| 524 | {cmp && cmp.aheadBy === 0 ? ( |
| 525 | <div class="blank mb"> |
| 526 | <h3>There isn't anything to compare.</h3> |
| 527 | <p class="m0"> |
| 528 | <b>{baseRef}</b> is up to date with all commits from <b>{headRef}</b>. |
| 529 | </p> |
| 530 | </div> |
| 531 | ) : null} |
| 532 | {existing ? ( |
| 533 | <div class="flash info"> |
| 534 | A pull request for these branches already exists:{" "} |
| 535 | <a href={`${base}/pull/${existing}`}> |
| 536 | #{existing} |
| 537 | </a> |
| 538 | </div> |
| 539 | ) : canPr ? ( |
| 540 | <Form action={`${base}/pulls`} t={t} class="box" style="max-width:980px"> |
| 541 | <input type="hidden" name="base" value={baseRef} /> |
| 542 | <input type="hidden" name="head" value={headRef} /> |
| 543 | <div class="head"> |
| 544 | <h2>Open a pull request</h2> |
| 545 | <span class="muted small"> |
| 546 | {headRef} → {baseRef} |
| 547 | </span> |
| 548 | </div> |
| 549 | <div class="body"> |
| 550 | {form?.error ? <div class="flash error">{form.error}</div> : null} |
| 551 | <div class="field"> |
| 552 | <label for="pt">Title</label> |
| 553 | <input id="pt" name="title" type="text" required value={v.title} /> |
| 554 | </div> |
| 555 | <div class="field"> |
| 556 | <label for="pi">Intent (what this change is meant to do — helps reviewers and AI reviewers)</label> |
| 557 | <textarea id="pi" name="intent" style="min-height:80px" placeholder="e.g. Fix the race in token refresh without changing the public API."> |
| 558 | {v.intent} |
| 559 | </textarea> |
| 560 | </div> |
| 561 | <div class="field"> |
| 562 | <label for="pb">Description</label> |
| 563 | <textarea id="pb" name="body" placeholder="Markdown is supported."> |
| 564 | {v.body} |
| 565 | </textarea> |
| 566 | </div> |
| 567 | {offerAutoMerge ? ( |
| 568 | <div class="field"> |
| 569 | <input type="hidden" name="auto_merge_offered" value="1" /> |
| 570 | <KCheckbox |
| 571 | name="auto_merge" |
| 572 | checked={v.autoMerge ?? !!mySetting} |
| 573 | label="Merge by itself once checks pass" |
| 574 | description={ |
| 575 | <> |
| 576 | Turns on auto-merge: it merges once {baseRef}'s required checks pass and every rule of the branch is met, approvals included. {mySetting ? "Ticked by your setting in " : "Tick it for every pull request you open in "} |
| 577 | <a href="/settings/pull-requests">Settings → Pull requests</a>. |
| 578 | </> |
| 579 | } |
| 580 | /> |
| 581 | </div> |
| 582 | ) : null} |
| 583 | <div class="row between"> |
| 584 | <KCheckbox name="draft" checked={v.draft} label="Create as draft" /> |
| 585 | <button class="btn green">Create pull request</button> |
| 586 | </div> |
| 587 | </div> |
| 588 | </Form> |
| 589 | ) : null} |
| 590 | {cmp && cmp.commits.length ? ( |
| 591 | <div class="box"> |
| 592 | <div class="head"> |
| 593 | <h3> |
| 594 | {raw(ICONS.commit)} {cmp.commits.length} commit{cmp.commits.length === 1 ? "" : "s"} |
| 595 | </h3> |
| 596 | </div> |
| 597 | <ul class="list"> |
| 598 | {cmp.commits.map((cm) => ( |
| 599 | <CommitRow base={base} sha={cm.sha} message={cm.message} author={cm.author} signed={cm.signed} /> |
| 600 | ))} |
| 601 | </ul> |
| 602 | </div> |
| 603 | ) : null} |
| 604 | {cmp && cmp.files.length ? ( |
| 605 | <> |
| 606 | <div class="row between mb"> |
| 607 | <DiffStats files={cmp.totalFiles} additions={cmp.additions} deletions={cmp.deletions} /> |
| 608 | {cmp.truncated ? <span class="badge amber">showing the first {cmp.files.length} files</span> : null} |
| 609 | </div> |
| 610 | <FileSummary files={cmp.files as DiffFile[]} /> |
| 611 | <DiffView files={cmp.files as DiffFile[]} opts={{ viewHref: (p) => `${base}/blob/${encPath(headRef)}/${encPath(p)}` }} /> |
| 612 | </> |
| 613 | ) : null} |
| 614 | </div>, |
| 615 | ); |
| 616 | } |
| 617 | |
| 618 | // ---------------------------------------------------------------- routes |
| 619 | |
| 620 | export function registerCode(web: WebApp): void { |
| 621 | web.get("/:owner/:repo", async (c) => { |
| 622 | const name = prm(c, "repo"); |
| 623 | if (name.endsWith(".git")) return c.redirect(`/${prm(c, "owner")}/${name.slice(0, -4)}`, 301); |
| 624 | const l = await loadRepo(c, prm(c, "owner"), name, "read"); |
| 625 | if (l.repo.owner_login !== prm(c, "owner") || l.repo.name !== name) return c.redirect(repoUrl(l.repo), 301); |
| 626 | return treePage(c, l, l.repo.default_branch, "", true); |
| 627 | }); |
| 628 | |
| 629 | web.get("/:owner/:repo/tree/*", async (c) => { |
| 630 | const l = await loadRepo(c, prm(c, "owner"), prm(c, "repo"), "read"); |
| 631 | const rest = restOfPath(c, 3); |
| 632 | if (!rest) return c.redirect(repoUrl(l.repo), 302); |
| 633 | const { ref, path } = await splitRefPath(l.stub, rest); |
| 634 | return treePage(c, l, ref, path, !path); |
| 635 | }); |
| 636 | |
| 637 | web.get("/:owner/:repo/blob/*", async (c) => { |
| 638 | const l = await loadRepo(c, prm(c, "owner"), prm(c, "repo"), "read"); |
| 639 | const { repo, caller, stub } = l; |
| 640 | const base = repoUrl(repo); |
| 641 | const { ref, path } = await splitRefPath(stub, restOfPath(c, 3)); |
| 642 | if (!path) return c.redirect(`${base}/tree/${encPath(ref)}`, 302); |
| 643 | const [blob, names] = await Promise.all([stub.blob(ref, path), refNames(stub)]); |
| 644 | if (!blob) { |
| 645 | const tree = await stub.tree(ref, path); |
| 646 | if (tree) return c.redirect(`${base}/tree/${encPath(ref)}/${encPath(path)}`, 302); |
| 647 | throw new HttpError(404, "file not found"); |
| 648 | } |
| 649 | const ext = extOf(path); |
| 650 | const rawUrl = `${base}/raw/${encPath(ref)}/${encPath(path)}`; |
| 651 | const plain = c.req.query("plain") === "1"; |
| 652 | const canEdit = atLeast(caller.role, "write") && names.branches.includes(ref) && !blob.binary && blob.size <= MAX_RENDER && !repo.archived; |
| 653 | let content: Child; |
| 654 | let lineCount = 0; |
| 655 | if (IMAGE_TYPES[ext] && ext !== "svg") { |
| 656 | content = ( |
| 657 | <div class="body" style="text-align:center;background:var(--bg2)"> |
| 658 | <img src={rawUrl} alt={path} style="max-width:100%" /> |
| 659 | </div> |
| 660 | ); |
| 661 | } else if (blob.binary) { |
| 662 | content = ( |
| 663 | <div class="empty"> |
| 664 | Binary file, {fmtBytes(blob.size)} ({blob.size.toLocaleString("en-US")} bytes).{" "} |
| 665 | <a class="btn sm" href={rawUrl}> |
| 666 | {raw(ICONS.download)} Download |
| 667 | </a> |
| 668 | </div> |
| 669 | ); |
| 670 | } else if (blob.size > MAX_RENDER) { |
| 671 | content = ( |
| 672 | <div class="empty"> |
| 673 | This file is too large to display ({fmtBytes(blob.size)}). <a href={rawUrl}>View raw</a> |
| 674 | </div> |
| 675 | ); |
| 676 | } else { |
| 677 | const text = decoder().decode(blob.content); |
| 678 | const lines = text.split("\n"); |
| 679 | if (lines.length > 1 && lines[lines.length - 1] === "") lines.pop(); |
| 680 | lineCount = lines.length; |
| 681 | if (isMarkdown(path) && !plain) { |
| 682 | content = ( |
| 683 | <div class="body readme" style="margin:0;padding:24px 32px"> |
| 684 | <Markdown text={text} base={{ owner: repo.owner_login, repo: repo.name, ref, dir: path.split("/").slice(0, -1).join("/") }} empty="Empty file." /> |
| 685 | </div> |
| 686 | ); |
| 687 | } else { |
| 688 | const shown = lines.map((l) => l.replace(/\r$/, "")); |
| 689 | const toks = await highlightLines(shown, langForPath(path)); |
| 690 | content = ( |
| 691 | <div class="code-wrap"> |
| 692 | <table class="blob"> |
| 693 | {shown.map((line, i) => ( |
| 694 | <tr id={`L${i + 1}`}> |
| 695 | <td class="ln"> |
| 696 | <a href={`#L${i + 1}`}>{i + 1}</a> |
| 697 | </td> |
| 698 | {toks?.[i] ? <td class="sh">{tokens(toks[i])}</td> : <td>{line}</td>} |
| 699 | </tr> |
| 700 | ))} |
| 701 | </table> |
| 702 | </div> |
| 703 | ); |
| 704 | } |
| 705 | } |
| 706 | return render( |
| 707 | c, |
| 708 | { title: `${path} at ${ref} · ${repo.owner_login}/${repo.name}`, repo: { repo, caller, tab: "code", ref } }, |
| 709 | <div> |
| 710 | <div class="row between mb"> |
| 711 | <div class="row"> |
| 712 | <RefSwitcher current={ref} branches={names.branches} tags={names.tags} to={(r) => `${base}/blob/${encPath(r)}/${encPath(path)}`} /> |
| 713 | <Crumbs base={base} ref={ref} path={path} /> |
| 714 | <CopyButton text={path} label="Copy path" /> |
| 715 | </div> |
| 716 | </div> |
| 717 | <div class="box"> |
| 718 | <div class="head small"> |
| 719 | <span class="muted"> |
| 720 | {lineCount ? `${lineCount} line${lineCount === 1 ? "" : "s"} · ` : ""} |
| 721 | {fmtBytes(blob.size)} |
| 722 | {blob.mode === "100755" ? " · executable" : ""} |
| 723 | </span> |
| 724 | <span class="grow" /> |
| 725 | {isMarkdown(path) && !blob.binary ? ( |
| 726 | <div class="subnav"> |
| 727 | <a href={`?`} class={!plain ? "on" : ""}> |
| 728 | Preview |
| 729 | </a> |
| 730 | <a href={`?plain=1`} class={plain ? "on" : ""}> |
| 731 | Code |
| 732 | </a> |
| 733 | </div> |
| 734 | ) : null} |
| 735 | <a class="btn sm" href={rawUrl}> |
| 736 | Raw |
| 737 | </a> |
| 738 | <a class="btn sm" href={`${base}/commits/${encPath(ref)}${qs({ path })}`}> |
| 739 | {raw(ICONS.history)} History |
| 740 | </a> |
| 741 | {canEdit ? ( |
| 742 | <a class="btn sm" href={`${base}/edit/${encPath(ref)}/${encPath(path)}`}> |
| 743 | {raw(ICONS.edit)} Edit |
| 744 | </a> |
| 745 | ) : null} |
| 746 | </div> |
| 747 | {content} |
| 748 | </div> |
| 749 | </div>, |
| 750 | ); |
| 751 | }); |
| 752 | |
| 753 | web.get("/:owner/:repo/raw/*", async (c) => { |
| 754 | const { stub } = await loadRepo(c, prm(c, "owner"), prm(c, "repo"), "read"); |
| 755 | const { ref, path } = await splitRefPath(stub, restOfPath(c, 3)); |
| 756 | const blob = path ? await stub.blob(ref, path) : null; |
| 757 | if (!blob) throw new HttpError(404, "file not found"); |
| 758 | const ext = extOf(path); |
| 759 | const type = IMAGE_TYPES[ext] ?? (blob.binary ? "application/octet-stream" : "text/plain; charset=utf-8"); |
| 760 | const name = path.split("/").pop() ?? "file"; |
| 761 | const headers: Record<string, string> = { |
| 762 | "content-type": type, |
| 763 | "x-content-type-options": "nosniff", |
| 764 | "content-security-policy": "sandbox; default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'", |
| 765 | "cache-control": /^[0-9a-f]{40}$/.test(ref) ? "private, max-age=86400, immutable" : "private, max-age=60", |
| 766 | "content-disposition": `${type === "application/octet-stream" ? "attachment" : "inline"}; filename*=UTF-8''${encodeURIComponent(name)}`, |
| 767 | "x-frame-options": "DENY", |
| 768 | }; |
| 769 | return new Response(blob.content, { headers }); |
| 770 | }); |
| 771 | |
| 772 | // Editor (edit an existing file / create a new one). |
| 773 | const editorGet = async (c: AppContext, mode: "edit" | "new") => { |
| 774 | const l = await loadRepo(c, prm(c, "owner"), prm(c, "repo"), "write"); |
| 775 | const { repo, caller, stub } = l; |
| 776 | const base = repoUrl(repo); |
| 777 | const names = await refNames(stub); |
| 778 | const empty = !names.branches.length && !names.tags.length; |
| 779 | const rest = restOfPath(c, 3); |
| 780 | const split = empty ? { ref: rest.split("/")[0] || repo.default_branch, path: rest.split("/").slice(1).join("/") } : await splitRefPath(stub, rest); |
| 781 | const ref = split.ref; |
| 782 | if (!empty && !names.branches.includes(ref)) throw new HttpError(422, "files can only be edited on a branch"); |
| 783 | const meName = caller.login; |
| 784 | const patchBranch = `${meName}-patch-${Math.floor(Date.now() / 1000) % 100000}`; |
| 785 | const canDirect = await canCommitDirect(l, ref); |
| 786 | if (mode === "edit") { |
| 787 | const blob = split.path ? await stub.blob(ref, split.path) : null; |
| 788 | if (!blob) throw new HttpError(404, "file not found"); |
| 789 | if (blob.binary) throw new HttpError(422, "binary files cannot be edited in the browser"); |
| 790 | return render( |
| 791 | c, |
| 792 | { title: `Editing ${split.path}`, repo: { repo, caller, tab: "code", ref } }, |
| 793 | <Editor |
| 794 | c={c} |
| 795 | l={l} |
| 796 | ref={ref} |
| 797 | mode="edit" |
| 798 | orig={split.path} |
| 799 | dir="" |
| 800 | canDirect={canDirect} |
| 801 | v={{ path: split.path, content: decoder().decode(blob.content), message: `Update ${split.path.split("/").pop()}`, description: "", choice: canDirect ? "direct" : "branch", newBranch: patchBranch, head: blob.sha }} |
| 802 | />, |
| 803 | ); |
| 804 | } |
| 805 | const headSha = empty ? "" : ((await stub.resolve(ref)) ?? ""); |
| 806 | const filename = c.req.query("filename") ?? ""; |
| 807 | const dir = split.path; |
| 808 | return render( |
| 809 | c, |
| 810 | { title: `New file · ${repo.owner_login}/${repo.name}`, repo: { repo, caller, tab: "code", ref } }, |
| 811 | <> |
| 812 | <p class="muted"> |
| 813 | Create a new file in <a href={`${base}/tree/${encPath(ref)}${dir ? `/${encPath(dir)}` : ""}`}>{dir || repo.name}</a>. |
| 814 | </p> |
| 815 | <Editor |
| 816 | c={c} |
| 817 | l={l} |
| 818 | ref={ref} |
| 819 | mode="new" |
| 820 | orig="" |
| 821 | dir={dir} |
| 822 | canDirect={canDirect || empty} |
| 823 | v={{ path: `${dir ? `${dir}/` : ""}${cleanPath(filename) ?? ""}`, content: "", message: filename ? `Create ${filename}` : "Create new file", description: "", choice: canDirect || empty ? "direct" : "branch", newBranch: patchBranch, head: headSha }} |
| 824 | /> |
| 825 | </>, |
| 826 | ); |
| 827 | }; |
| 828 | |
| 829 | const editorPost = async (c: AppContext, mode: "edit" | "new", f: FormData) => { |
| 830 | const l = await loadRepo(c, prm(c, "owner"), prm(c, "repo"), "write"); |
| 831 | const { repo, caller, stub } = l; |
| 832 | const base = repoUrl(repo); |
| 833 | const names = await refNames(stub); |
| 834 | const empty = !names.branches.length && !names.tags.length; |
| 835 | const rest = restOfPath(c, 3); |
| 836 | const split = empty ? { ref: rest.split("/")[0] || repo.default_branch, path: rest.split("/").slice(1).join("/") } : await splitRefPath(stub, rest); |
| 837 | const ref = split.ref; |
| 838 | const orig = mode === "edit" ? split.path : ""; |
| 839 | const head = f.s("head"); |
| 840 | |
| 841 | if (mode === "edit" && f.b("_delete")) { |
| 842 | return act(c, `${base}/blob/${encPath(ref)}/${encPath(orig)}`, async () => { |
| 843 | await stub.commitFiles({ branch: ref, message: `Delete ${orig}`, changes: [{ path: orig, delete: true }], expectedHeadSha: head || undefined }, caller); |
| 844 | const parent = orig.split("/").slice(0, -1).join("/"); |
| 845 | return `${base}/tree/${encPath(ref)}${parent ? `/${encPath(parent)}` : ""}`; |
| 846 | }); |
| 847 | } |
| 848 | |
| 849 | let content = f.s("content"); |
| 850 | if (content.startsWith("\r\n")) content = content.slice(2); |
| 851 | else if (content.startsWith("\n")) content = content.slice(1); |
| 852 | let mode100: "100644" | "100755" | "120000" | undefined; |
| 853 | if (mode === "edit") { |
| 854 | const old = await stub.blob(ref, orig); |
| 855 | const crlf = !!old && decoder().decode(old.content.slice(0, 65536)).includes("\r\n"); |
| 856 | if (!crlf) content = content.replace(/\r\n/g, "\n"); |
| 857 | if (old && (old.mode === "100755" || old.mode === "120000")) mode100 = old.mode; |
| 858 | } else content = content.replace(/\r\n/g, "\n"); |
| 859 | const values: EditorValues = { |
| 860 | path: f.s("path"), |
| 861 | content, |
| 862 | message: f.s("message"), |
| 863 | description: f.s("description"), |
| 864 | choice: f.s("choice") === "direct" ? "direct" : "branch", |
| 865 | newBranch: f.s("new_branch").trim(), |
| 866 | head, |
| 867 | }; |
| 868 | const canDirect = empty || (await canCommitDirect(l, ref)); |
| 869 | try { |
| 870 | const path = cleanPath(values.path); |
| 871 | if (!path) throw new HttpError(422, "enter a valid file path"); |
| 872 | if (!values.message.trim()) throw new HttpError(422, "a commit message is required"); |
| 873 | const toBranch = values.choice === "direct" && canDirect ? ref : values.newBranch; |
| 874 | if (!toBranch) throw new HttpError(422, "enter a branch name"); |
| 875 | const changes: Array<{ path: string; content?: Uint8Array; delete?: boolean; mode?: "100644" | "100755" | "120000" }> = []; |
| 876 | if (mode === "edit" && path !== orig) changes.push({ path: orig, delete: true }); |
| 877 | if (mode === "new" && !empty && (await stub.blob(ref, path))) throw new HttpError(422, `${path} already exists`); |
| 878 | changes.push({ path, content: new TextEncoder().encode(content), mode: mode100 }); |
| 879 | const message = values.description.trim() ? `${values.message.trim()}\n\n${values.description.trim()}` : values.message.trim(); |
| 880 | const newBranch = toBranch !== ref; |
| 881 | if (newBranch && names.branches.includes(toBranch)) throw new HttpError(422, `branch ${toBranch} already exists`); |
| 882 | await stub.commitFiles({ branch: toBranch, message, changes, expectedHeadSha: !newBranch && head ? head : undefined, createBranchFrom: newBranch ? ref : undefined }, caller); |
| 883 | c.executionCtx.waitUntil(c.get("dir").touchPushed(repo.id)); |
| 884 | if (newBranch) return c.redirect(`${base}/compare/${encPath(ref)}...${encPath(toBranch)}`, 303); |
| 885 | return c.redirect(`${base}/blob/${encPath(ref)}/${encPath(path)}`, 303); |
| 886 | } catch (e) { |
| 887 | const s = statusOf(e); |
| 888 | if (s.status >= 500) throw e; |
| 889 | return render( |
| 890 | c, |
| 891 | { title: mode === "edit" ? `Editing ${orig}` : "New file", repo: { repo, caller, tab: "code", ref }, status: s.status }, |
| 892 | <Editor c={c} l={l} ref={ref} mode={mode} orig={orig} dir={mode === "new" ? split.path : ""} canDirect={canDirect} v={values} error={s.message} />, |
| 893 | ); |
| 894 | } |
| 895 | }; |
| 896 | |
| 897 | web.get("/:owner/:repo/edit/*", (c) => editorGet(c, "edit")); |
| 898 | post(web, "/:owner/:repo/edit/*", (c, f) => editorPost(c, "edit", f)); |
| 899 | web.get("/:owner/:repo/new/*", (c) => editorGet(c, "new")); |
| 900 | post(web, "/:owner/:repo/new/*", (c, f) => editorPost(c, "new", f)); |
| 901 | |
| 902 | // History |
| 903 | web.get("/:owner/:repo/commits/*", async (c) => { |
| 904 | const l = await loadRepo(c, prm(c, "owner"), prm(c, "repo"), "read"); |
| 905 | const { repo, caller, stub } = l; |
| 906 | const base = repoUrl(repo); |
| 907 | const ref = restOfPath(c, 3) || repo.default_branch; |
| 908 | const path = c.req.query("path") ?? ""; |
| 909 | const page = pageNum(c); |
| 910 | const per = 30; |
| 911 | const [commits, names] = await Promise.all([stub.log(ref, { path: path || undefined, limit: per + 1, skip: (page - 1) * per }), refNames(stub)]); |
| 912 | const hasNext = commits.length > per; |
| 913 | const shown = commits.slice(0, per); |
| 914 | const groups = new Map<string, typeof shown>(); |
| 915 | for (const cm of shown) { |
| 916 | const day = new Date(cm.committer.timestamp * 1000).toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric" }); |
| 917 | groups.set(day, [...(groups.get(day) ?? []), cm]); |
| 918 | } |
| 919 | return render( |
| 920 | c, |
| 921 | { title: `Commits · ${repo.owner_login}/${repo.name}`, repo: { repo, caller, tab: "code", ref } }, |
| 922 | <div> |
| 923 | <div class="row between mb"> |
| 924 | <div class="row"> |
| 925 | <h1 class="m0">Commits</h1> |
| 926 | <RefSwitcher current={ref} branches={names.branches} tags={names.tags} to={(r) => `${base}/commits/${encPath(r)}${qs({ path })}`} /> |
| 927 | {path ? ( |
| 928 | <span class="muted"> |
| 929 | for <span class="mono">{path}</span> · <a href={`${base}/commits/${encPath(ref)}`}>all files</a> |
| 930 | </span> |
| 931 | ) : null} |
| 932 | </div> |
| 933 | </div> |
| 934 | {shown.length === 0 ? <div class="blank">No commits found.</div> : null} |
| 935 | {[...groups.entries()].map(([day, list]) => ( |
| 936 | <div class="mb"> |
| 937 | <h3 class="muted small" style="font-weight:500"> |
| 938 | {raw(ICONS.commit)} Commits on {day} |
| 939 | </h3> |
| 940 | <div class="box"> |
| 941 | <ul class="list"> |
| 942 | {list.map((cm) => ( |
| 943 | <CommitRow base={base} sha={cm.sha} message={cm.message} author={cm.author} signed={cm.signed} /> |
| 944 | ))} |
| 945 | </ul> |
| 946 | </div> |
| 947 | </div> |
| 948 | ))} |
| 949 | <Pager page={page} hasNext={hasNext} href={(p) => `${base}/commits/${encPath(ref)}${qs({ path, page: p > 1 ? p : undefined })}`} /> |
| 950 | </div>, |
| 951 | ); |
| 952 | }); |
| 953 | web.get("/:owner/:repo/commits", (c) => c.redirect(`/${prm(c, "owner")}/${prm(c, "repo")}/commits/HEAD`, 302)); |
| 954 | |
| 955 | web.get("/:owner/:repo/commit/:sha", async (c) => { |
| 956 | const l = await loadRepo(c, prm(c, "owner"), prm(c, "repo"), "read"); |
| 957 | const { repo, caller, stub } = l; |
| 958 | const base = repoUrl(repo); |
| 959 | const cm = await stub.commitWithDiff(prm(c, "sha")); |
| 960 | const checks = await stub.checksAndStatuses(cm.sha).catch(() => []); |
| 961 | const [title, ...rest] = cm.message.split("\n"); |
| 962 | const body = rest.join("\n").trim(); |
| 963 | const files = cm.files as DiffFile[]; |
| 964 | return render( |
| 965 | c, |
| 966 | { title: `${firstLine(cm.message)} · ${shortSha(cm.sha)}`, repo: { repo, caller, tab: "code", ref: cm.sha }, wide: true }, |
| 967 | <div> |
| 968 | <div class="box"> |
| 969 | <div class="body"> |
| 970 | <h2 style="font-size:18px">{title}</h2> |
| 971 | {body ? <pre style="white-space:pre-wrap;margin:0 0 12px;font-size:13px">{body}</pre> : null} |
| 972 | <div class="row small muted"> |
| 973 | <b style="color:var(--fg)">{cm.author.name}</b> authored <Time at={new Date(cm.author.timestamp * 1000).toISOString()} /> |
| 974 | {cm.committer.name !== cm.author.name ? ( |
| 975 | <span> |
| 976 | · <b style="color:var(--fg)">{cm.committer.name}</b> committed <Time at={new Date(cm.committer.timestamp * 1000).toISOString()} /> |
| 977 | </span> |
| 978 | ) : null} |
| 979 | {cm.signed ? <span class="badge green">signed</span> : null} |
| 980 | <span class="grow" /> |
| 981 | <span> |
| 982 | {cm.parents.length} parent{cm.parents.length === 1 ? "" : "s"}{" "} |
| 983 | {cm.parents.map((p) => ( |
| 984 | <a class="sha" href={`${base}/commit/${p}`} style="margin-left:4px"> |
| 985 | {shortSha(p)} |
| 986 | </a> |
| 987 | ))} |
| 988 | </span> |
| 989 | <span> |
| 990 | commit <span class="sha">{cm.sha}</span> |
| 991 | </span> |
| 992 | <CopyButton text={cm.sha} /> |
| 993 | <a class="btn sm" href={`${base}/tree/${cm.sha}`}> |
| 994 | Browse files |
| 995 | </a> |
| 996 | </div> |
| 997 | {checks.length ? ( |
| 998 | <ul class="checks mt"> |
| 999 | {checks.map((ch) => ( |
| 1000 | <li> |
| 1001 | <Status status={ch.status} conclusion={ch.conclusion} /> |
| 1002 | <CheckName base={base} ch={ch} /> |
| 1003 | <span class="muted small">{ch.output?.title ?? ""}</span> |
| 1004 | </li> |
| 1005 | ))} |
| 1006 | </ul> |
| 1007 | ) : null} |
| 1008 | </div> |
| 1009 | </div> |
| 1010 | <div class="row between mb"> |
| 1011 | <DiffStats files={cm.totalFiles} additions={cm.additions} deletions={cm.deletions} /> |
| 1012 | {cm.truncated ? <span class="badge amber">showing the first {files.length} files</span> : null} |
| 1013 | </div> |
| 1014 | <FileSummary files={files} /> |
| 1015 | <DiffView files={files} opts={{ viewHref: (p) => `${base}/blob/${cm.sha}/${encPath(p)}` }} /> |
| 1016 | </div>, |
| 1017 | ); |
| 1018 | }); |
| 1019 | |
| 1020 | // Branches and tags |
| 1021 | web.get("/:owner/:repo/branches", async (c) => { |
| 1022 | const l = await loadRepo(c, prm(c, "owner"), prm(c, "repo"), "read"); |
| 1023 | const { repo, caller, stub } = l; |
| 1024 | const base = repoUrl(repo); |
| 1025 | const t = csrfToken(c); |
| 1026 | const branches = await stub.branches(); |
| 1027 | branches.sort((a, b) => (a.isDefault ? -1 : b.isDefault ? 1 : a.name.localeCompare(b.name))); |
| 1028 | const infos = await Promise.all(branches.slice(0, 40).map((b) => stub.commitInfo(b.sha).catch(() => null))); |
| 1029 | const canWrite = atLeast(caller.role, "write") && !repo.archived; |
| 1030 | return render( |
| 1031 | c, |
| 1032 | { title: `Branches · ${repo.owner_login}/${repo.name}`, repo: { repo, caller, tab: "code" } }, |
| 1033 | <div> |
| 1034 | <div class="row between mb"> |
| 1035 | <h1 class="m0">Branches</h1> |
| 1036 | </div> |
| 1037 | <div class="box"> |
| 1038 | {branches.length ? ( |
| 1039 | <ul class="list"> |
| 1040 | {branches.map((b, i) => { |
| 1041 | const info = infos[i]; |
| 1042 | return ( |
| 1043 | <li> |
| 1044 | <span class="st faint">{raw(ICONS.branch)}</span> |
| 1045 | <div class="grow"> |
| 1046 | <a class="title mono" href={`${base}/tree/${encPath(b.name)}`}> |
| 1047 | {b.name} |
| 1048 | </a>{" "} |
| 1049 | {b.isDefault ? <span class="badge blue">default</span> : null} {b.protected ? <span class="badge">{raw(ICONS.shield)} protected</span> : null} |
| 1050 | {info ? ( |
| 1051 | <div class="meta"> |
| 1052 | {firstLine(info.message)} · {info.author.name} · <Time at={new Date(info.committer.timestamp * 1000).toISOString()} /> |
| 1053 | </div> |
| 1054 | ) : null} |
| 1055 | </div> |
| 1056 | <a class="sha" href={`${base}/commit/${b.sha}`}> |
| 1057 | {shortSha(b.sha)} |
| 1058 | </a> |
| 1059 | {!b.isDefault ? ( |
| 1060 | <a class="btn sm" href={`${base}/compare/${encPath(repo.default_branch)}...${encPath(b.name)}`}> |
| 1061 | {raw(ICONS.pr)} Compare |
| 1062 | </a> |
| 1063 | ) : null} |
| 1064 | {canWrite && !b.isDefault ? ( |
| 1065 | <Form action={`${base}/branches/delete`} t={t} class="inline" confirm={`Delete branch ${b.name}?`}> |
| 1066 | <input type="hidden" name="name" value={b.name} /> |
| 1067 | <button class="btn sm danger" title="Delete branch"> |
| 1068 | {raw(ICONS.x)} |
| 1069 | </button> |
| 1070 | </Form> |
| 1071 | ) : null} |
| 1072 | </li> |
| 1073 | ); |
| 1074 | })} |
| 1075 | </ul> |
| 1076 | ) : ( |
| 1077 | <div class="empty">No branches yet.</div> |
| 1078 | )} |
| 1079 | </div> |
| 1080 | {canWrite && branches.length ? ( |
| 1081 | <Form action={`${base}/branches`} t={t} class="box"> |
| 1082 | <div class="head"> |
| 1083 | <h3>Create a branch</h3> |
| 1084 | </div> |
| 1085 | <div class="body row" style="align-items:flex-end"> |
| 1086 | <div class="field grow m0"> |
| 1087 | <label>Branch name</label> |
| 1088 | <input name="name" type="text" required class="mono" /> |
| 1089 | </div> |
| 1090 | <div class="field m0"> |
| 1091 | <label>From</label> |
| 1092 | <KSelect name="from" label="From" value={branches.find((b) => b.isDefault)?.name} options={branches.map((b) => ({ value: b.name, label: b.name }))} /> |
| 1093 | </div> |
| 1094 | <button class="btn primary">Create branch</button> |
| 1095 | </div> |
| 1096 | </Form> |
| 1097 | ) : null} |
| 1098 | </div>, |
| 1099 | ); |
| 1100 | }); |
| 1101 | |
| 1102 | post(web, "/:owner/:repo/branches", async (c, f) => { |
| 1103 | const { repo, caller, stub } = await loadRepo(c, prm(c, "owner"), prm(c, "repo"), "write"); |
| 1104 | const base = repoUrl(repo); |
| 1105 | return act(c, `${base}/branches`, async () => { |
| 1106 | const name = f.s("name").trim(); |
| 1107 | const sha = await stub.resolve(f.s("from")); |
| 1108 | if (!sha) throw new HttpError(422, "unknown source branch"); |
| 1109 | await stub.createRef(`refs/heads/${name}`, sha, caller); |
| 1110 | return `${base}/tree/${encPath(name)}`; |
| 1111 | }); |
| 1112 | }); |
| 1113 | |
| 1114 | post(web, "/:owner/:repo/branches/delete", async (c, f) => { |
| 1115 | const { repo, caller, stub } = await loadRepo(c, prm(c, "owner"), prm(c, "repo"), "write"); |
| 1116 | return act(c, `${repoUrl(repo)}/branches`, async () => stub.deleteRef(`refs/heads/${f.s("name")}`, caller), "Branch deleted."); |
| 1117 | }); |
| 1118 | |
| 1119 | web.get("/:owner/:repo/tags", async (c) => { |
| 1120 | const { repo, caller, stub } = await loadRepo(c, prm(c, "owner"), prm(c, "repo"), "read"); |
| 1121 | const base = repoUrl(repo); |
| 1122 | const tags = (await stub.tags()).reverse(); |
| 1123 | const infos = await Promise.all(tags.slice(0, 40).map((tg) => stub.commitInfo(tg.target).catch(() => null))); |
| 1124 | return render( |
| 1125 | c, |
| 1126 | { title: `Tags · ${repo.owner_login}/${repo.name}`, repo: { repo, caller, tab: "code" } }, |
| 1127 | <div> |
| 1128 | <h1>Tags</h1> |
| 1129 | <div class="box"> |
| 1130 | {tags.length ? ( |
| 1131 | <ul class="list"> |
| 1132 | {tags.map((tg, i) => ( |
| 1133 | <li> |
| 1134 | <span class="st faint">{raw(ICONS.tag)}</span> |
| 1135 | <div class="grow"> |
| 1136 | <a class="title mono" href={`${base}/tree/${encPath(tg.name)}`}> |
| 1137 | {tg.name} |
| 1138 | </a> |
| 1139 | {infos[i] ? ( |
| 1140 | <div class="meta"> |
| 1141 | {firstLine(infos[i]!.message)} · <Time at={new Date(infos[i]!.committer.timestamp * 1000).toISOString()} /> |
| 1142 | </div> |
| 1143 | ) : null} |
| 1144 | </div> |
| 1145 | <a class="sha" href={`${base}/commit/${tg.target}`}> |
| 1146 | {shortSha(tg.target)} |
| 1147 | </a> |
| 1148 | <a class="btn sm" href={`${base}/compare/${encPath(tg.name)}...${encPath(repo.default_branch)}`}> |
| 1149 | Compare |
| 1150 | </a> |
| 1151 | </li> |
| 1152 | ))} |
| 1153 | </ul> |
| 1154 | ) : ( |
| 1155 | <div class="empty"> |
| 1156 | No tags yet. Create one with <code>git tag v1.0.0 && git push --tags</code>. |
| 1157 | </div> |
| 1158 | )} |
| 1159 | </div> |
| 1160 | </div>, |
| 1161 | ); |
| 1162 | }); |
| 1163 | |
| 1164 | // Compare |
| 1165 | web.get("/:owner/:repo/compare", async (c) => { |
| 1166 | const l = await loadRepo(c, prm(c, "owner"), prm(c, "repo"), "read"); |
| 1167 | const base = repoUrl(l.repo); |
| 1168 | const b = c.req.query("base"); |
| 1169 | const h = c.req.query("head"); |
| 1170 | if (b && h) return c.redirect(`${base}/compare/${encPath(b)}...${encPath(h)}`, 302); |
| 1171 | const names = await refNames(l.stub); |
| 1172 | const other = names.branches.find((x) => x !== l.repo.default_branch); |
| 1173 | return comparePage(c, l, l.repo.default_branch, h ?? other ?? l.repo.default_branch); |
| 1174 | }); |
| 1175 | |
| 1176 | web.get("/:owner/:repo/compare/*", async (c) => { |
| 1177 | const l = await loadRepo(c, prm(c, "owner"), prm(c, "repo"), "read"); |
| 1178 | const spec = restOfPath(c, 3); |
| 1179 | const idx = spec.indexOf("..."); |
| 1180 | const baseRef = idx >= 0 ? spec.slice(0, idx) : l.repo.default_branch; |
| 1181 | const headRef = idx >= 0 ? spec.slice(idx + 3) : spec; |
| 1182 | if (!headRef) return c.redirect(`${repoUrl(l.repo)}/compare`, 302); |
| 1183 | return comparePage(c, l, baseRef || l.repo.default_branch, headRef); |
| 1184 | }); |
| 1185 | |
| 1186 | post(web, "/:owner/:repo/pulls", async (c, f) => { |
| 1187 | const l = await loadRepo(c, prm(c, "owner"), prm(c, "repo"), "write"); |
| 1188 | if (c.get("principal").type !== "account") throw new HttpError(401, "sign in required"); |
| 1189 | const values: PullFormValues = { title: f.s("title").trim(), body: f.s("body").replace(/\r\n/g, "\n"), intent: f.s("intent").replace(/\r\n/g, "\n").trim(), draft: f.b("draft"), ...(f.b("auto_merge_offered") ? { autoMerge: f.b("auto_merge") } : {}) }; |
| 1190 | const baseRef = f.s("base") || l.repo.default_branch; |
| 1191 | const headRef = f.s("head"); |
| 1192 | try { |
| 1193 | const pr = await l.stub.createPull({ title: values.title, body: values.body, head: headRef, base: baseRef, draft: values.draft, intent: values.intent || undefined, ...(values.autoMerge !== undefined ? { autoMerge: values.autoMerge } : {}) }, l.caller); |
| 1194 | return c.redirect(`${repoUrl(l.repo)}/pull/${pr.number}`, 303); |
| 1195 | } catch (e) { |
| 1196 | const s = statusOf(e); |
| 1197 | if (s.status >= 500) throw e; |
| 1198 | return comparePage(c, l, baseRef, headRef, { values, error: s.message }); |
| 1199 | } |
| 1200 | }); |
| 1201 | } |
| 1202 | |
| 1203 | /** Whether a web commit straight to `branch` would pass protection rules for this caller. */ |
| 1204 | async function canCommitDirect(l: Loaded, branch: string): Promise<boolean> { |
| 1205 | const rules = (await l.stub.listProtections()).find((p) => globToRegExp(p.pattern).test(branch))?.rules; |
| 1206 | if (l.caller.kind === "agent" && (branch === l.repo.default_branch || rules) && !rules?.agentsMayPush) return false; |
| 1207 | if (!rules) return true; |
| 1208 | if (l.caller.role === "admin" && !rules.enforceAdmins) return true; |
| 1209 | return !rules.requirePullRequest; |
| 1210 | } |
| 1211 | |