aboutsummaryrefslogtreecommitdiffstats
authorDivy Srivastava <me@littledivy.com>2026-08-20 04:42:35 +0530
committerDivy Srivastava <me@littledivy.com>2026-08-20 04:42:35 +0530
commita5311cc4b9d97954e9beef06bc487eab376accf4 (patch)
treeaeab3c577c417c61adf84c3713968c825e303cbe
parent0fa57ce9fe4fc8314ab6d6a93ae1e42ec9acec78 (diff)
downloaddgit-a5311cc4b9.tar.gz zip
v0.0.5v0.0.5
Diffstat
README.md+8-31
docs/api.md+44-3
examples/platform.ts (deleted)+0-73
package.json+1-1
src/mod.ts+133-21
src/registry.ts+14-2
src/repo.ts+75-26
src/ui/html.ts+11-1
tsconfig.json+2-4
9 files changed, 288 insertions(+), 162 deletions(-)
diff --git a/README.md b/README.md
@@ -118,38 +118,15 @@
bind the Durable Object classes as [wrangler.jsonc](wrangler.jsonc) does
and re-export them from your entry module.
-`authorize` gates every repository-scoped request — `read` (pages,
-clones, the content API), `write` (push), or `admin` (config, gc,
-delete) — ahead of the page cache and the R2 clone path. `false` sends
-the Basic challenge; a `Response` is sent verbatim. It replaces the
-stock `GIT_TOKEN` policy entirely, so the private flag protects nothing
-unless the hook consults it. `onPush` fires off the response path with
-the ref updates a push applied. [docs/api.md](docs/api.md) has the full
-contract; [examples/platform.ts](examples/platform.ts) is a multi-tenant
-host built from both.
+`authorize` gates every repository-scoped request and replaces the
+stock `GIT_TOKEN` policy entirely (the private flag is yours to
+consult); `onPush` fires with the ref updates a push applied. Every
+repository also serves a JSON content API, gated like its pages, and
+the same surface as typed RPC on the cell. `ui: false` runs it headless
+behind your own frontend, `cors` opens the API cross-origin, and
+`namespaces: true` routes GitHub-style `owner/name` repositories. See
+docs at [docs/api.md](docs/api.md).
-Reading a repository from code needs no git client. Every repository
-serves a JSON API, gated like its pages:
-
-```
-/myrepo/api/refs refs and HEAD, tags peeled
-/myrepo/api/log?h=main&path=src&n=50 commit log, filtered and paged
-/myrepo/api/commit?id=v1 one commit (branch, tag, or oid)
-/myrepo/api/tree?h=main&path=src tree listing with blob sizes
-/myrepo/api/blob?h=main&path=a.ts raw blob bytes (oid in x-oid)
-```
-
-and the same surface is typed RPC on the cell, for Workers holding the
-`REPO` binding — which bypasses `authorize`, so gate such routes
-yourself:
-
-```ts
-const repo = env.REPO.getByName("myrepo");
-const { head, refs } = await repo.listRefs();
-const log = await repo.listLog("main", { path: "src", n: 20 });
-const blob = await repo.readBlob("main", "src/a.ts");
-```
-
## Operate
```sh
diff --git a/docs/api.md b/docs/api.md
@@ -82,6 +82,20 @@
truncated (8 KB budget) — a consumer that must not miss updates
reconciles against `/api/refs`.
+### ui, cors, namespaces
+
+```ts
+ui?: boolean; // false = headless: protocol, admin, and API only; every page 404s
+cors?: string; // access-control-allow-origin for the API; preflights answered
+namespaces?: boolean; // true = every repository is <owner>/<name>
+```
+
+Headless runs dgit as a pure git server behind your own frontend — git
+needs only `/info/refs`, `/git-upload-pack`, and `/git-receive-pack`,
+and the JSON API stays for your UI's data. With `namespaces` the
+two-segment name is the repository name everywhere: hooks, the
+registry, the API, RPC (`env.REPO.getByName("owner/name")`).
+
### secretsEqual(a, b)
Timing-safe string comparison for hooks. `credentials.pass === secret`
@@ -106,6 +120,15 @@
served only when reachable from a current ref. Omitted means HEAD; tags
peel to commits.
+### GET /api/repos?owner=\<ns\>
+
+Site-level (not repository-scoped): public repositories, newest
+activity first, capped at 1000. `owner` filters one namespace.
+
+```json
+{ "repos": [ { "name": "alice/blog", "description": "", "owner": "", "section": "", "idle": 1787198887000 } ] }
+```
+
### GET /\<repo\>/api/refs
```json
@@ -163,6 +186,24 @@
The raw bytes, not JSON. Content type from the extension with nosniff;
the blob's oid in the `x-oid` header.
+### GET /\<repo\>/api/diff?id=\<ref-or-oid\>&id2=\<ref-or-oid\>
+
+Changes id2..id; `id2` defaults to the first parent of `id`, `old` is
+null for a root commit. `binary` and `toolarge` files carry no hunks.
+
+```json
+{
+ "old": "0b520f…", "new": "c3f12e…", "truncated": false,
+ "files": [{
+ "path": "a.ts",
+ "old": null, "new": { "oid": "ad1d38…", "mode": "100644" },
+ "kind": "text", "add": 1, "del": 0,
+ "hunks": [{ "aStart": 0, "aLen": 0, "bStart": 1, "bLen": 1,
+ "ops": [{ "tag": "add", "line": "const x = 1;" }] }]
+ }]
+}
+```
+
## RPC
The same surface as typed methods on the cell, for same-account Workers
@@ -175,6 +216,7 @@
await repo.listLog("main", { path: "src", n: 20 }); // LogResult
await repo.listTree("main", "src"); // TreeResult | null
await repo.readBlob("main", "src/a.ts"); // BlobResult | null — { oid, mode, data }
+await repo.readDiff("main"); // DiffResult | null
```
Resolution, bounds, and reachability match the JSON API; pass
@@ -185,9 +227,8 @@
RPC runs no auth — a binding is trusted infrastructure. A route built
on it gates itself: validate the name before `getByName` (an unchecked
name materializes a billable cell per probe), check the registry, and
-hold private reads to real credentials.
-[examples/platform.ts](../examples/platform.ts) shows the pattern; the
-registry is addressed the same way:
+hold private reads to real credentials. The registry is addressed the
+same way:
```ts
await env.REGISTRY.getByName("registry").get(repo); // RepoInfo | null
diff --git a/examples/platform.ts b/examples/platform.ts
@@ -1,73 +0,0 @@
-// A minimal platform on durable-git: public reads of public repos,
-// per-repository deploy keys in KV, a CI webhook on push, and a route that
-// reads repository content over RPC. Bind the Durable Objects as dgit's own
-// wrangler.jsonc does and re-export the classes.
-import { createDurableGit, secretsEqual, type Env as DgitEnv, type PushEvent } from "durable-git";
-
-export { RepoCell, Registry } from "durable-git";
-
-interface Env extends DgitEnv {
- /** key: repository name, value: its push token */
- DEPLOY_KEYS: KVNamespace;
- CI_WEBHOOK: string;
-}
-
-/** a repository's deploy key also grants private reads and admin ops */
-async function holdsDeployKey(env: Env, repo: string, pass: string | undefined): Promise<boolean> {
- const key = await env.DEPLOY_KEYS.get(repo);
- return key !== null && (await secretsEqual(pass ?? "", key));
-}
-
-const git = createDurableGit<Env>({
- // consulting ctx.private is on the hook: it replaces the default policy
- async authorize({ repo, op, private: priv, credentials, env }) {
- if (op === "read" && !priv) return true;
- return holdsDeployKey(env, repo, credentials?.pass);
- },
- async onPush(event: PushEvent, env: Env) {
- await fetch(env.CI_WEBHOOK, {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify(event),
- });
- },
-});
-
-const REPO_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
-
-export default {
- async fetch(req: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
- const url = new URL(req.url);
- // serve any repository's README at /_readme/<repo> over RPC. RPC bypasses
- // authorize, so the route gates itself: validate the name (an unchecked
- // getByName materializes a cell per probe), then hold private repos to
- // the same key as a push.
- if (url.pathname.startsWith("/_readme/")) {
- const repo = url.pathname.slice("/_readme/".length);
- if (!REPO_NAME.test(repo)) return new Response("bad repository name\n", { status: 400 });
- const info = await env.REGISTRY.getByName("registry").get(repo);
- if (!info) return new Response("not found\n", { status: 404 });
- if (info.priv && !(await holdsDeployKey(env, repo, parseBasicPass(req)))) {
- return new Response("auth required\n", {
- status: 401,
- headers: { "www-authenticate": 'Basic realm="platform"' },
- });
- }
- const blob = await env.REPO.getByName(repo).readBlob(undefined, "README.md");
- if (!blob) return new Response("no README\n", { status: 404 });
- return new Response(blob.data, { headers: { "content-type": "text/markdown; charset=utf-8" } });
- }
- return git.fetch(req, env, ctx);
- },
-} satisfies ExportedHandler<Env>;
-
-function parseBasicPass(req: Request): string | undefined {
- const header = req.headers.get("authorization") ?? "";
- if (!header.startsWith("Basic ")) return undefined;
- try {
- const decoded = atob(header.slice(6));
- return decoded.slice(decoded.indexOf(":") + 1);
- } catch {
- return undefined;
- }
-}
diff --git a/package.json b/package.json
@@ -1,6 +1,6 @@
{
"name": "durable-git",
- "version": "0.0.4",
+ "version": "0.0.5",
"description": "Durable git: a git server as a Cloudflare Durable Object. Smart HTTP, a cgit-style web interface, pluggable auth, push events, and a typed content API.",
"type": "module",
"main": "src/mod.ts",
diff --git a/src/mod.ts b/src/mod.ts
@@ -9,7 +9,7 @@
*/
import type { Env } from "./env";
import type { RepoInfo } from "./registry";
-import { esc, age, layout, htmlResponse, errorPage } from "./ui/html";
+import { esc, repoUrl, age, layout, htmlResponse, errorPage } from "./ui/html";
import { CSS } from "./ui/style";
import { parseUploadRequest, streamingCloneResponse } from "./git/protocol";
import { isOid } from "./git/util";
@@ -20,7 +20,7 @@
export { Registry } from "./registry";
export type { Env } from "./env";
export type { RepoInfo, RepoConfig } from "./registry";
-export type { RefsResult, CommitJson, TreeResult, TreeEntryJson, BlobResult, LogResult } from "./repo";
+export type { RefsResult, CommitJson, TreeResult, TreeEntryJson, BlobResult, LogResult, DiffResult, DiffFileJson } from "./repo";
export type { Person } from "./git/objects";
/** an upload-pack negotiation body is wants/haves/caps only — a few hundred KB */
@@ -27,7 +27,7 @@
const MAX_UPLOAD_PACK_BYTES = 16 * 1024 * 1024;
const REPO_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
-const RESERVED = new Set(["cgit.css", "favicon.ico", "robots.txt", "info", "git-upload-pack", "git-receive-pack"]);
+const RESERVED = new Set(["api", "cgit.css", "favicon.ico", "robots.txt", "info", "git-upload-pack", "git-receive-pack"]);
const CACHE_TTL = 60;
/** What a request is asking to do, from the repository's point of view. */
@@ -78,6 +78,24 @@
* (via waitUntil), so a slow or throwing hook never fails the push.
*/
onPush?: (event: PushEvent, env: E) => void | Promise<void>;
+ /**
+ * false runs dgit headless: the git protocol, admin endpoints, and the JSON
+ * API stay; every page (index and repo UI) 404s, so a wrapping Worker can
+ * own the whole frontend. Default true.
+ */
+ ui?: boolean;
+ /**
+ * access-control-allow-origin for the JSON API (e.g. "*"), so a
+ * cross-origin UI can call it from the browser; preflights are answered.
+ */
+ cors?: string;
+ /**
+ * true routes every repository as <owner>/<name> (GitHub-style, exactly two
+ * segments); the combined name is the repository name everywhere — hooks,
+ * the registry, the API, RPC (env.REPO.getByName("owner/name")). Default
+ * false: flat single-segment names.
+ */
+ namespaces?: boolean;
}
function tokens(env: Env): string[] {
@@ -220,7 +238,7 @@
let rows = "";
for (const r of repos) {
rows +=
- `<tr><td><a href='/${encodeURIComponent(r.name)}/'>${esc(r.name)}</a></td>` +
+ `<tr><td><a href='/${repoUrl(r.name)}/'>${esc(r.name)}</a></td>` +
`<td>${esc(r.desc || "[no description]")}</td>` +
`<td>${esc(r.owner || env.SITE_OWNER || "")}</td>` +
`<td>${age(Math.floor(r.idle / 1000))}</td></tr>`;
@@ -323,6 +341,23 @@
return streamingCloneResponse(obj.body, objects, req.caps.has("no-progress"));
}
+function withCors(res: Response, origin: string | undefined): Response {
+ if (origin) res.headers.set("access-control-allow-origin", origin);
+ return res;
+}
+
+function corsPreflight(origin: string): Response {
+ return new Response(null, {
+ status: 204,
+ headers: {
+ "access-control-allow-origin": origin,
+ "access-control-allow-methods": "GET",
+ "access-control-allow-headers": "authorization",
+ "access-control-max-age": "86400",
+ },
+ });
+}
+
function parseRefUpdates(res: Response): RefUpdate[] {
const header = res.headers.get("x-ref-updates");
if (!header) return [];
@@ -340,13 +375,86 @@
fetch(req: Request, env: E, ctx: ExecutionContext): Promise<Response>;
}
+/**
+ * Parse a repository route: /<name>[.git][/sub] flat, /<owner>/<name>[.git][/sub]
+ * namespaced. null for anything that is not a well-formed repository path
+ * (bad or reserved names, undecodable escapes).
+ */
+function repoPath(
+ pattern: URLPattern,
+ namespaced: boolean,
+ path: string
+): { repo: string; sub: string } | null {
+ const m = pattern.exec({ pathname: path });
+ if (!m) return null;
+ const g = m.pathname.groups;
+ const segs: string[] = [];
+ for (const raw of namespaced ? [g.owner, g.name] : [g.name]) {
+ if (!raw) return null;
+ let seg: string;
+ try {
+ seg = decodeURIComponent(raw);
+ } catch {
+ return null;
+ }
+ if (!REPO_NAME.test(seg)) return null;
+ segs.push(seg);
+ }
+ if (RESERVED.has(segs[0])) return null;
+ return { repo: segs.join("/"), sub: g["0"] ? `/${g["0"]}` : "/" };
+}
+
+/** What a repository sub-path is asking for, and the authorize op it implies. */
+function classify(sub: string, method: string, url: URL): {
+ op: AuthOp;
+ isReceive: boolean;
+ isProtocol: boolean;
+ isApi: boolean;
+ isAdmin: boolean;
+} {
+ const isReceive =
+ sub === "/git-receive-pack" ||
+ (sub === "/info/refs" && url.searchParams.get("service") === "git-receive-pack");
+ const isProtocol = isReceive || sub === "/git-upload-pack" || sub === "/info/refs";
+ const isApi = sub.startsWith("/api/");
+ const isAdmin =
+ ((sub === "/config" || sub === "/description") && method === "PUT") ||
+ (sub === "/gc" && method === "POST") ||
+ ((sub === "/" || sub === "") && method === "DELETE");
+ return { op: isReceive ? "write" : isAdmin ? "admin" : "read", isReceive, isProtocol, isApi, isAdmin };
+}
+
export function createDurableGit<E extends Env = Env>(options: DurableGitOptions<E> = {}): DurableGitHandler<E> {
const authorize = options.authorize ?? tokenAuthorize;
+ const ui = options.ui !== false;
+ const namespaced = !!options.namespaces;
+ const repoRoute = new URLPattern({
+ pathname: namespaced ? "/:owner/:name{.git}?{/*}?" : "/:name{.git}?{/*}?",
+ });
return {
async fetch(req: Request, env: E, ctx: ExecutionContext): Promise<Response> {
const url = new URL(req.url);
const path = url.pathname;
+ // site-level JSON ("api" is a reserved repository name)
+ if (path.startsWith("/api/")) {
+ if (options.cors && req.method === "OPTIONS") return corsPreflight(options.cors);
+ const json = (data: unknown, status = 200) =>
+ withCors(Response.json(data, { status, headers: { "x-content-type-options": "nosniff" } }), options.cors);
+ if (path === "/api/repos" && req.method === "GET") {
+ const ns = url.searchParams.get("owner") ?? undefined;
+ const repos = await env.REGISTRY.getByName("registry").list(1000, ns);
+ return json({
+ repos: repos.map((r) => ({ name: r.name, description: r.desc, owner: r.owner, section: r.section, idle: r.idle })),
+ });
+ }
+ return json({ error: "not found" }, 404);
+ }
+
+ if (!ui && (path === "/" || path === "" || path === "/cgit.css" || path === "/robots.txt" || path === "/favicon.ico")) {
+ return new Response("not found\n", { status: 404 });
+ }
+
if (path === "/" || path === "") {
// the index is the front door under load: cache it briefly at the edge
const cache = pageCache();
@@ -375,25 +483,25 @@
return new Response("not found\n", { status: 404 });
}
- const m = path.match(/^\/([^/]+?)(\.git)?(\/.*)?$/);
- if (!m) return errorPage(siteBase(env), "bad request", 400);
- const repo = decodeURIComponent(m[1]);
- const sub = m[3] ?? "/";
- if (!REPO_NAME.test(repo) || RESERVED.has(repo)) {
- return errorPage(siteBase(env), `no such repository: ${repo}`, 404);
+ const parsed = repoPath(repoRoute, namespaced, path);
+ if (!parsed) {
+ return ui
+ ? errorPage(siteBase(env), `no such repository: ${path}`, 404)
+ : new Response("not found\n", { status: 404 });
}
+ const { repo, sub } = parsed;
+ const { op, isReceive, isProtocol, isApi, isAdmin } = classify(sub, req.method, url);
const registry = env.REGISTRY.getByName("registry");
- const isReceive =
- sub === "/git-receive-pack" ||
- (sub === "/info/refs" && url.searchParams.get("service") === "git-receive-pack");
- const isProtocol = isReceive || sub === "/git-upload-pack" || sub === "/info/refs";
- const isApi = sub.startsWith("/api/");
- const isAdmin =
- ((sub === "/config" || sub === "/description") && req.method === "PUT") ||
- (sub === "/gc" && req.method === "POST") ||
- ((sub === "/" || sub === "") && req.method === "DELETE");
+ // headless: pages 404 before touching the registry or the cell; a CORS
+ // preflight (credential-less by spec) is answered before the auth gate
+ if (!ui && !isProtocol && !isApi && !isAdmin) {
+ return new Response("not found\n", { status: 404 });
+ }
+ if (options.cors && isApi && req.method === "OPTIONS") {
+ return corsPreflight(options.cors);
+ }
// mutations read the registry fresh; page views tolerate a short memo
const info: RepoInfo | null = await repoInfo(env, repo, isReceive || isAdmin);
@@ -400,7 +508,6 @@
// every repo-scoped request passes through authorize; the default hook
// waves reads of public repositories straight through
- const op: AuthOp = isReceive ? "write" : isAdmin ? "admin" : "read";
const decision = await authorize({
repo,
op,
@@ -478,7 +585,12 @@
fwd.headers.set("x-repo", repo);
fwd.headers.set("x-host", url.host);
fwd.headers.set("x-proto", url.protocol.replace(":", ""));
- const res = await stub.fetch(fwd);
+ let res = await stub.fetch(fwd);
+ // set before the cache put, so cached copies carry the header too
+ if (options.cors && isApi) {
+ res = new Response(res.body, res);
+ res.headers.set("access-control-allow-origin", options.cors);
+ }
// bookkeeping after successful mutations. idle is the newest committer date
// (x-commit-time), computed by the DO which alone can read the object graph
diff --git a/src/registry.ts b/src/registry.ts
@@ -81,8 +81,20 @@
return rows[0] ?? null;
}
- /** Public index page feed: excludes private repos, bounded so a large table can't dump wholesale over RPC. */
- list(limit = 1000): RepoInfo[] {
+ /** Public index page feed: excludes private repos, bounded so a large table
+ * can't dump wholesale over RPC. `ns` filters to one namespace ("ns/..."),
+ * as a range scan: '0' is the code point after '/'. */
+ list(limit = 1000, ns?: string): RepoInfo[] {
+ if (ns) {
+ return this.ctx.storage.sql
+ .exec<RepoInfo>(
+ "SELECT name, desc, owner, section, priv, idle, ver FROM repos WHERE priv = 0 AND name >= ? AND name < ? ORDER BY idle DESC LIMIT ?",
+ `${ns}/`,
+ `${ns}0`,
+ limit
+ )
+ .toArray();
+ }
return this.ctx.storage.sql
.exec<RepoInfo>(
"SELECT name, desc, owner, section, priv, idle, ver FROM repos WHERE priv = 0 ORDER BY idle DESC LIMIT ?",
diff --git a/src/repo.ts b/src/repo.ts
@@ -32,7 +32,7 @@
import { diffLines, toHunks, isBinary, Hunk, DiffOp } from "./git/diff";
import { blame, BlameHistoryEntry } from "./git/blame";
import { tarGz, zip, SnapshotFile } from "./git/snapshot";
-import { esc, age, fmtDate, fmtDate2822, layout, htmlResponse, errorPage, LayoutOpts } from "./ui/html";
+import { esc, repoUrl, repoBase, age, fmtDate, fmtDate2822, layout, htmlResponse, errorPage, LayoutOpts } from "./ui/html";
import { renderMarkdown } from "./ui/markdown";
import { highlightLines } from "./ui/highlight";
@@ -128,6 +128,24 @@
data: Uint8Array;
}
+export interface DiffFileJson {
+ path: string;
+ old: { oid: string; mode: string } | null;
+ new: { oid: string; mode: string } | null;
+ kind: "text" | "binary" | "toolarge";
+ add: number;
+ del: number;
+ hunks: Hunk[];
+}
+
+export interface DiffResult {
+ /** null for a root commit */
+ old: string | null;
+ new: string;
+ files: DiffFileJson[];
+ truncated: boolean;
+}
+
interface FileDiff {
path: string;
o: { oid: string; mode: string } | null;
@@ -482,6 +500,32 @@
return { oid: found.oid, entries };
}
+ /** Changes id2..id (default id2 = first parent of id, like the diff page). */
+ async readDiff(id?: string, id2?: string): Promise<DiffResult | null> {
+ this.rpcBind();
+ const rr = await this.resolveRef(id);
+ if (!rr) return null;
+ const head = await this.peelToCommit(rr.oid);
+ if (!head) return null;
+ let oldOid: string | null = null;
+ if (id2) {
+ const rr2 = await this.resolveRef(id2);
+ const c2 = rr2 ? await this.peelToCommit(rr2.oid) : null;
+ if (!c2) return null;
+ oldOid = c2.oid;
+ } else {
+ oldOid = head.commit.parents[0] ?? null;
+ }
+ const oldCommit = oldOid ? await this.loadCommit(oldOid) : null;
+ const { files, truncated } = await this.computeDiff(oldCommit?.tree ?? null, head.commit.tree);
+ return {
+ old: oldOid,
+ new: head.oid,
+ truncated,
+ files: files.map((f) => ({ path: f.path, old: f.o, new: f.n, kind: f.kind, add: f.add, del: f.del, hunks: f.hunks })),
+ };
+ }
+
async readBlob(ref: string | undefined, path: string): Promise<BlobResult | null> {
this.rpcBind();
const rr = await this.resolveRef(ref);
@@ -519,6 +563,10 @@
const t = await this.listTree(h, q.get("path") ?? "");
return t ? json(t) : notFound("tree not found");
}
+ if (path === "/api/diff") {
+ const d = await this.readDiff(q.get("id") ?? h, q.get("id2") ?? undefined);
+ return d ? json(d) : notFound("commit not found");
+ }
if (path === "/api/blob") {
const blob = await this.readBlob(h, q.get("path") ?? "");
if (!blob) return notFound("blob not found");
@@ -791,7 +839,7 @@
ref: ref ?? headBranch,
hasAbout: (await this.findReadme()) !== null,
branches,
- formAction: formAction ?? `/${encodeURIComponent(repo)}/`,
+ formAction: formAction ?? `/${repoUrl(repo)}/`,
};
}
@@ -1023,7 +1071,7 @@
/** Map oid -> decorations (branch/tag pointing at it). */
private async decorations(repo: string): Promise<Map<string, string>> {
const map = new Map<string, string>();
- const r = `/${encodeURIComponent(repo)}`;
+ const r = `/${repoUrl(repo)}`;
for (const ref of this.store.refs()) {
let html = "";
let target = ref.target;
@@ -1199,7 +1247,7 @@
private async aboutPage(repo: string, h: string | undefined): Promise<Response> {
- const base = await this.base(repo, "about", h, `/${encodeURIComponent(repo)}/about/`);
+ const base = await this.base(repo, "about", h, `/${repoUrl(repo)}/about/`);
const readme = await this.findReadme();
if (!readme) return errorPage(base, "no readme found");
const obj = await this.store.get(readme.oid);
@@ -1217,7 +1265,7 @@
const base = await this.base(repo, "summary");
const branches = this.store.refs().filter((r) => r.name.startsWith("refs/heads/"));
const tags = this.store.refs().filter((r) => r.name.startsWith("refs/tags/"));
- const r = `/${encodeURIComponent(repo)}`;
+ const r = `/${repoUrl(repo)}`;
if (!branches.length && !tags.length) {
return htmlResponse(
@@ -1257,8 +1305,8 @@
}
const c = await this.peelToCommit(target);
if (c && !when) when = c.commit.committer.time;
- const snap = `<a href='${r}/snapshot/${encodeURIComponent(repo)}-${encodeURIComponent(name)}.tar.gz'>tar.gz</a> ` +
- `<a href='${r}/snapshot/${encodeURIComponent(repo)}-${encodeURIComponent(name)}.zip'>zip</a>`;
+ const snap = `<a href='${r}/snapshot/${encodeURIComponent(repoBase(repo))}-${encodeURIComponent(name)}.tar.gz'>tar.gz</a> ` +
+ `<a href='${r}/snapshot/${encodeURIComponent(repoBase(repo))}-${encodeURIComponent(name)}.zip'>zip</a>`;
return `<tr><td><a href='${r}/tag/?h=${encodeURIComponent(name)}'>${esc(name)}</a></td>` +
`<td><a href='${r}/commit/?id=${target}'>${esc(c?.commit.subject ?? "")}</a></td>` +
`<td>${esc(c?.commit.author.name ?? "")}</td><td>${age(when)}</td><td class='snapshots'>${snap}</td></tr>`;
@@ -1293,7 +1341,7 @@
}
private async logPage(repo: string, h: string | undefined, ofs: number, filter: LogFilter): Promise<Response> {
- const r = `/${encodeURIComponent(repo)}`;
+ const r = `/${repoUrl(repo)}`;
const base = await this.base(repo, "log", h, `${r}/log/`);
let tip = h;
if (filter.qt === "range" && filter.q) {
@@ -1351,7 +1399,7 @@
}
private async refsPage(repo: string): Promise<Response> {
- const r = `/${encodeURIComponent(repo)}`;
+ const r = `/${repoUrl(repo)}`;
const base = await this.base(repo, "refs", undefined, `${r}/refs/`);
const refs = this.store.refs();
const branches = refs.filter((x) => x.name.startsWith("refs/heads/"));
@@ -1360,8 +1408,8 @@
.map(async (b) => {
const name = b.name.slice(11);
const c = await this.peelToCommit(b.target);
- const snap = `<a href='${r}/snapshot/${encodeURIComponent(repo)}-${encodeURIComponent(name)}.tar.gz'>tar.gz</a> ` +
- `<a href='${r}/snapshot/${encodeURIComponent(repo)}-${encodeURIComponent(name)}.zip'>zip</a>`;
+ const snap = `<a href='${r}/snapshot/${encodeURIComponent(repoBase(repo))}-${encodeURIComponent(name)}.tar.gz'>tar.gz</a> ` +
+ `<a href='${r}/snapshot/${encodeURIComponent(repoBase(repo))}-${encodeURIComponent(name)}.zip'>zip</a>`;
return `<tr><td><a href='${r}/log/?h=${encodeURIComponent(name)}'>${esc(name)}</a></td>` +
`<td class='sha1'><a href='${r}/commit/?id=${b.target}'>${b.target.slice(0, 10)}</a></td>` +
`<td>${esc(c?.commit.author.name ?? "")}</td><td>${c ? age(c.commit.committer.time) : ""}</td><td class='snapshots'>${snap}</td></tr>`;
@@ -1384,8 +1432,8 @@
when = c.committer.time;
who = c.author.name;
}
- const snap = `<a href='${r}/snapshot/${encodeURIComponent(repo)}-${encodeURIComponent(name)}.tar.gz'>tar.gz</a> ` +
- `<a href='${r}/snapshot/${encodeURIComponent(repo)}-${encodeURIComponent(name)}.zip'>zip</a>`;
+ const snap = `<a href='${r}/snapshot/${encodeURIComponent(repoBase(repo))}-${encodeURIComponent(name)}.tar.gz'>tar.gz</a> ` +
+ `<a href='${r}/snapshot/${encodeURIComponent(repoBase(repo))}-${encodeURIComponent(name)}.zip'>zip</a>`;
return `<tr><td><a href='${r}/tag/?h=${encodeURIComponent(name)}'>${esc(name)}</a></td>` +
`<td class='sha1'><a href='${r}/commit/?id=${target}'>${target.slice(0, 10)}</a></td>` +
`<td>${esc(who)}</td><td>${age(when)}</td><td class='snapshots'>${snap}</td></tr>`;
@@ -1404,17 +1452,17 @@
private pathBar(repo: string, h: string | undefined, path: string[]): string {
const q = h ? `?h=${encodeURIComponent(h)}` : "";
- let html = `path: <a href='/${encodeURIComponent(repo)}/tree/${q}'>root</a>`;
+ let html = `path: <a href='/${repoUrl(repo)}/tree/${q}'>root</a>`;
let acc = "";
for (const seg of path) {
acc += "/" + encodeURIComponent(seg);
- html += `/<a href='/${encodeURIComponent(repo)}/tree${acc}${q}'>${esc(seg)}</a>`;
+ html += `/<a href='/${repoUrl(repo)}/tree${acc}${q}'>${esc(seg)}</a>`;
}
return html;
}
private async treePage(repo: string, h: string | undefined, path: string[]): Promise<Response> {
- const r = `/${encodeURIComponent(repo)}`;
+ const r = `/${repoUrl(repo)}`;
const base = await this.base(repo, "tree", h, `${r}/tree/${path.map(encodeURIComponent).join("/")}`);
const rr = await this.resolveRef(h);
if (!rr) return errorPage(base, h ? `bad ref: ${h}` : "empty repository");
@@ -1463,7 +1511,7 @@
): Promise<Response> {
const obj = await this.store.get(entry.oid);
if (!obj) return errorPage(base, "missing blob");
- const r = `/${encodeURIComponent(repo)}`;
+ const r = `/${repoUrl(repo)}`;
const q = h ? `?h=${encodeURIComponent(h)}` : "";
const href = path.map(encodeURIComponent).join("/");
const plainHref = `${r}/plain/${href}${q}`;
@@ -1484,7 +1532,7 @@
}
private async blamePage(repo: string, h: string | undefined, path: string[]): Promise<Response> {
- const r = `/${encodeURIComponent(repo)}`;
+ const r = `/${repoUrl(repo)}`;
const base = await this.base(repo, "tree", h, `${r}/blame/${path.map(encodeURIComponent).join("/")}`);
const withPath = { ...base, pathBar: this.pathBar(repo, h, path) };
const rr = await this.resolveRef(h);
@@ -1545,7 +1593,7 @@
}
private async commitPage(repo: string, id: string | undefined, h: string | undefined): Promise<Response> {
- const r = `/${encodeURIComponent(repo)}`;
+ const r = `/${repoUrl(repo)}`;
const base = await this.base(repo, "commit", h, `${r}/commit/`);
const oid = await this.resolveCommitId(id, h);
if (!oid) return errorPage(base, "commit not found");
@@ -1563,7 +1611,7 @@
<tr><th>commit</th><td colspan='2' class='sha1'>${oid} (<a href='${r}/patch/?id=${oid}'>patch</a>)</td></tr>
<tr><th>tree</th><td colspan='2' class='sha1'><a href='${r}/tree/?h=${oid}'>${commit.tree}</a></td></tr>
${commit.parents.map((p) => `<tr><th>parent</th><td colspan='2' class='sha1'><a href='?id=${p}'>${p}</a> (<a href='${r}/diff/?id=${oid}&id2=${p}'>diff</a>)</td></tr>`).join("")}
-<tr><th>download</th><td colspan='2' class='sha1'><a href='${r}/snapshot/${encodeURIComponent(repo)}-${oid.slice(0, 10)}.tar.gz'>${esc(repo)}-${oid.slice(0, 10)}.tar.gz</a> <a href='${r}/snapshot/${encodeURIComponent(repo)}-${oid.slice(0, 10)}.zip'>zip</a></td></tr>
+<tr><th>download</th><td colspan='2' class='sha1'><a href='${r}/snapshot/${encodeURIComponent(repoBase(repo))}-${oid.slice(0, 10)}.tar.gz'>${esc(repoBase(repo))}-${oid.slice(0, 10)}.tar.gz</a> <a href='${r}/snapshot/${encodeURIComponent(repoBase(repo))}-${oid.slice(0, 10)}.zip'>zip</a></td></tr>
</table>
<div class='commit-subject'>${esc(commit.subject)}${deco.get(oid) ?? ""}</div>
<div class='commit-msg'>${esc(commit.message.split("\n").slice(1).join("\n").trim())}</div>
@@ -1582,7 +1630,7 @@
/** diff/rawdiff: changes id2..id (default id2 = first parent of id). */
private async diffPage(repo: string, id: string | undefined, id2: string | undefined, h: string | undefined, raw: boolean): Promise<Response> {
- const base = await this.base(repo, "diff", h, `/${encodeURIComponent(repo)}/diff/`);
+ const base = await this.base(repo, "diff", h, `/${repoUrl(repo)}/diff/`);
const newOid = await this.resolveCommitId(id, h);
if (!newOid) return raw ? new Response("not found\n", { status: 404 }) : errorPage(base, "commit not found");
const commit = (await this.loadCommit(newOid))!;
@@ -1636,7 +1684,7 @@
}
private async tagPage(repo: string, name: string | undefined): Promise<Response> {
- const r = `/${encodeURIComponent(repo)}`;
+ const r = `/${repoUrl(repo)}`;
const base = await this.base(repo, "refs", undefined, `${r}/refs/`);
if (!name) return errorPage(base, "no tag given");
const target = this.store.getRef(`refs/tags/${name}`) ?? (await this.resolveServable(name));
@@ -1651,7 +1699,7 @@
<tr><th>tag name</th><td>${esc(tag.tag || name)}</td></tr>
${tag.tagger ? `<tr><th>tag date</th><td>${fmtDate(tag.tagger.time, tag.tagger.tz)}</td></tr><tr><th>tagged by</th><td>${esc(tag.tagger.name)} &lt;${esc(tag.tagger.email)}&gt;</td></tr>` : ""}
<tr><th>tagged object</th><td class='sha1'><a href='${r}/commit/?id=${tag.object}'>${tag.object}</a> (${esc(tag.type)})</td></tr>
-<tr><th>download</th><td class='sha1'><a href='${r}/snapshot/${encodeURIComponent(repo)}-${encodeURIComponent(name)}.tar.gz'>${esc(repo)}-${esc(name)}.tar.gz</a> <a href='${r}/snapshot/${encodeURIComponent(repo)}-${encodeURIComponent(name)}.zip'>zip</a></td></tr>
+<tr><th>download</th><td class='sha1'><a href='${r}/snapshot/${encodeURIComponent(repoBase(repo))}-${encodeURIComponent(name)}.tar.gz'>${esc(repoBase(repo))}-${esc(name)}.tar.gz</a> <a href='${r}/snapshot/${encodeURIComponent(repoBase(repo))}-${encodeURIComponent(name)}.zip'>zip</a></td></tr>
</table>
<div class='commit-msg'>${esc(tag.message.trim())}</div>`;
} else {
@@ -1681,7 +1729,8 @@
}
// cgit-style: reponame-ref.tar.gz; also accept a bare ref and a v-prefix
const candidates = [stem];
- if (stem.startsWith(`${repo}-`)) candidates.push(stem.slice(repo.length + 1));
+ const base = repoBase(repo); // snapshot filenames carry the last name segment
+ if (stem.startsWith(`${base}-`)) candidates.push(stem.slice(base.length + 1));
for (const c of [...candidates]) candidates.push(`v${c}`);
let commit: { oid: string; commit: Commit } | null = null;
for (const cand of candidates) {
@@ -1727,7 +1776,7 @@
const rr = await this.resolveRef(h);
if (!rr) return new Response("empty repository\n", { status: 404 });
const { entries } = await this.walkLog(rr.oid, 0, 20);
- const abs = `${proto}://${host}/${encodeURIComponent(repo)}`;
+ const abs = `${proto}://${host}/${repoUrl(repo)}`;
const iso = (t: number) => new Date(t * 1000).toISOString().replace(/\.\d+Z$/, "Z");
const updated = entries[0] ? iso(entries[0].commit.committer.time) : iso(0);
const items = entries
@@ -1806,7 +1855,7 @@
}
private async statsPage(repo: string, h: string | undefined, period: string): Promise<Response> {
- const r = `/${encodeURIComponent(repo)}`;
+ const r = `/${repoUrl(repo)}`;
const base = await this.base(repo, "stats", h, `${r}/stats/`);
const rr = await this.resolveRef(h);
if (!rr) return errorPage(base, "empty repository");
diff --git a/src/ui/html.ts b/src/ui/html.ts
@@ -6,6 +6,16 @@
return s.replace(/[&<>"'`]/g, (c) => ESCAPES[c]);
}
+/** repo name as a URL path — a namespaced name's slash stays a separator */
+export function repoUrl(repo: string): string {
+ return repo.split("/").map(encodeURIComponent).join("/");
+}
+
+/** repo name as a filename stem: the last segment of a namespaced name */
+export function repoBase(repo: string): string {
+ return repo.slice(repo.lastIndexOf("/") + 1);
+}
+
/** cgit-style relative age with its color class, e.g. "3 days" / age-days. */
export function age(unixSecs: number): string {
if (!unixSecs) return "";
@@ -67,7 +77,7 @@
}
export function layout(o: LayoutOpts): string {
- const r = o.repo ? `/${encodeURIComponent(o.repo)}` : "";
+ const r = o.repo ? `/${repoUrl(o.repo)}` : "";
const q = o.ref ? `?h=${encodeURIComponent(o.ref)}` : "";
const tabs: [string, string][] = o.repo
? [
diff --git a/tsconfig.json b/tsconfig.json
@@ -9,9 +9,7 @@
"noEmit": true,
"skipLibCheck": true,
"isolatedModules": true,
- "forceConsistentCasingInFileNames": true,
- // lets examples/ import the package by its published name
- "paths": { "durable-git": ["./src/mod.ts"] }
+ "forceConsistentCasingInFileNames": true
},
- "include": ["src/**/*.ts", "examples/**/*.ts"]
+ "include": ["src/**/*.ts"]
}