A release is a tag of git: v1.2.7 on a commit of main, cut by one call, and a Releases page
Jonas Templestein, 2026-11-27 13:10 UTC · c8cf2c596b09654cb68b74374a1bdd7ab6360593 · parent 295cda8
7 files changed
- M README.md
- M app.ts
- M pages.ts
- M public/page.css
- A releases.ts
- M tests/local-mind.mjs
- A tests/releases.test.mjs
M README.md
@@ -13,6 +13,7 @@ /repos/<name>/commits the newest commits /repos/<name>/commit/<oid> one commit: what it changed /repos/<name>/branches the branches, each with its pull or a compare link +/repos/<name>/releases the releases: each a tag of git, with its notes /repos/<name>/compare/<branch> a branch against main, and "Open a pull" /repos/<name>/pulls the pulls /repos/<name>/pull/<number> one pull: its conversation and what it changes @@ -81,11 +82,26 @@ A repo's pulls are events on the repo's own context: `pulls.ts` says which. An agent opens a pull or comments by appending the same events, and merges with `itx.config.pullMerge(repo, number)`. +## Releases + +A release is an annotated tag of git on a commit of main, named `v1.2.7`. Take a version, and not +every commit: + +```sh +git ls-remote --tags https://git.<domain>/repos/<name> +git clone --branch v1.2.7 https://git.<domain>/repos/<name> +``` + +An agent cuts one with `itx.config.releaseCut(repo)`: the next version raises the patch, the notes +are main's commits since the release before, and nothing is cut when main has nothing new. +`releases.ts` says the rest. A tag is never moved. + ## The files - `app.ts`: who may do what, and the git remote - `pages.ts`: each page, as plain HTML - `pulls.ts`: what a pull is, and the merge +- `releases.ts`: what a release is, and the cut - `public/`: what the browser runs. There is no build. - `public/branch-commit.js`: the commit on a new branch that a member's page makes of an edit
M app.ts
@@ -8,6 +8,7 @@ // GET /repos/<name>/commits its newest commits // GET /repos/<name>/commit/<oid> one commit: what it changed // GET /repos/<name>/branches its branches, each with its pull or a compare link +// GET /repos/<name>/releases its releases: each a tag of git, with its notes // GET /repos/<name>/compare/<branch> a branch against main, and the box that opens a pull // GET /repos/<name>/pulls its pulls // GET /repos/<name>/pull/<number> one pull: its conversation and what it changes @@ -17,7 +18,8 @@ // POST /repos/<name>/git-receive-pack push // // The files: this one (who may do what, and the remote), pages.ts (each page's HTML), pulls.ts -// (what a pull is), and public/ (what the browser runs). +// (what a pull is), releases.ts (what a release is, and how one is cut), and public/ (what the +// browser runs). // // WHO MAY READ. A repo that worker.ts lists as public is for anyone: its pages, its pulls, and a // clone with no credential. Any other repo's pages, and git on it, are for a member of the mind. @@ -81,6 +83,7 @@ PAGE_PATH, pullPage, pullsPage, + releasesPage, reposPage, } from "./pages.ts"; import files from "./public/"; @@ -184,6 +187,7 @@ if (match[2] === "commits") return await commitsPage(view, handle); if (match[2] === "commit") return await commitPage(view, handle, itx, rest); if (match[2] === "branches") return await branchesPage(view, handle, itx); + if (match[2] === "releases") return await releasesPage(view, itx); if (match[2] === "pulls") return await pullsPage(view, handle, itx); if (match[2] === "pull") return await pullPage(view, handle, itx, rest); if (match[2] === "compare") return await comparePage(view, handle, itx, rest);
M pages.ts
@@ -4,7 +4,8 @@ // public/page.js then draws in their places what wants a script: the file tree, a file or a diff // with its colours, markdown, and for a member the boxes that write (a comment, a pull, a merge). // -// WHAT A PULL IS, and where its events are, is pulls.ts. A page here only reads. +// WHAT A PULL IS, and where its events are, is pulls.ts; what a release is, releases.ts. A page +// here only reads. // // THE DIFFERENCE BETWEEN TWO COMMITS COSTS TWO READS OF A WHOLE TREE: a repo answers with files, // never with changes. Two commits never change, so the app keeps what it worked out in the @@ -22,6 +23,7 @@ import { z } from "zod"; import { plainDiff } from "./plain-diff.ts"; import { type LinePlace, type Pull, pullsIn, type Standing, standingOf } from "./pulls.ts"; +import { type Release, releasesIn } from "./releases.ts"; type Host = Pick<IterateConfigEntrypoint, "getItx" | "auth">; export type Itx = ReturnType<Host["getItx"]>; @@ -34,7 +36,7 @@ /** A repo's pages: its name, then what of it. */ export const PAGE_PATH = - /^\/repos\/([A-Za-z0-9._-]+)(?:\/(tree|edit|commits|commit|branches|pulls|pull|compare)(?:\/(.*))?)?$/; + /^\/repos\/([A-Za-z0-9._-]+)(?:\/(tree|edit|commits|commit|branches|releases|pulls|pull|compare)(?:\/(.*))?)?$/; /** How many commits the list shows, and how far back a short oid is looked for. */ const COMMITS_SHOWN = 100; @@ -344,6 +346,35 @@ // ── PULLS ── +/** The repo's releases, newest first: each one's tag, the commit it stands on, who cut it and + * when, and its notes. A release is a tag of git (releases.ts), so the page says how git gets + * one. */ +export async function releasesPage(view: View, itx: Itx) { + const { repo, url } = view; + const releases = await releasesIn(itx, repo); + const row = (release: Release) => { + const commit = `<a href="${esc(repo)}/commit/${release.commitOid}"><code>${release.commitOid.slice(0, 7)}</code></a>`; + const cut = release.at + ? `, cut${release.by ? ` by ${esc(release.by)}` : ""}, ${utcStamp(Date.parse(release.at))}` + : ", a tag with no release notes"; + const notes = release.notes ? `<pre class="notes">${esc(release.notes)}</pre>` : ""; + return `<li id="${esc(release.tag)}"><b>${esc(release.tag)}</b> <span class="by">at ${commit}${cut}</span>${notes}</li>`; + }; + const newest = releases[0]; + const main = [ + `<h1>Releases</h1>`, + newest + ? `<ul class="releases">${releases.map(row).join("")}</ul>` + : note("No release yet."), + `<p class="note">A release is a tag of git on a commit of main. To see the tags: <code>git ls-remote --tags ${esc(url.origin + repo)}</code>${ + newest + ? `. To get one: <code>git clone --branch ${esc(newest.tag)} ${esc(url.origin + repo)}</code>` + : "" + }</p>`, + ].join(""); + return page(view, 200, "releases", `Releases · ${nameOf(repo)}`, main, {}); +} + /** The repo's pulls: the open ones, then the ones that are merged or closed. */ export async function pullsPage(view: View, handle: Repo, itx: Itx) { const { repo } = view; @@ -652,7 +683,7 @@ export function page( view: { url: URL; repo: string | null; isPublic: boolean; me: string | null }, status: number, - tab: "code" | "commits" | "branches" | "pulls" | null, + tab: "code" | "commits" | "branches" | "releases" | "pulls" | null, title: string, main: string, data: Record<string, unknown>, @@ -667,6 +698,7 @@ `</p><nav><a href="${esc(repo)}"${current("code")}>Code</a>`, `<a href="${esc(repo)}/commits"${current("commits")}>Commits</a>`, `<a href="${esc(repo)}/branches"${current("branches")}>Branches</a>`, + `<a href="${esc(repo)}/releases"${current("releases")}>Releases</a>`, `<a href="${esc(repo)}/pulls"${current("pulls")}>Pulls</a></nav>`, `<code class="clone">git clone ${esc(url.origin + repo)}</code>`, ].join("")
M public/page.css
@@ -75,6 +75,9 @@ h2 { margin: 1.5rem 0 0.5rem; font-size: 0.9375rem; font-weight: 600; } main > h2, main > details { margin-left: 1rem; margin-right: 1rem; } .pulls li, .branches li { padding: 0.25rem 0; } +.releases { list-style: none; padding: 0; } +.releases li { padding: 0.5rem 0; } +.releases .notes { margin: 0.25rem 0 0; white-space: pre-wrap; font-size: 0.8125rem; color: var(--muted-foreground); } .done { margin-top: 1.25rem; } .done summary { cursor: pointer; color: var(--muted-foreground); } .pull { margin: 1rem 1rem 3rem; }
A releases.ts
@@ -0,0 +1,408 @@ +// releases.ts — WHAT A RELEASE IS: a tag of git on a commit of `main`, named `v<major>.<minor>.<patch>` +// (`v1.2.7`). A tag tells whoever uses the repo that a new version is there, so they take a +// version and not every commit: +// +// git ls-remote --tags https://git.<domain>/repos/<name> +// git clone --branch v1.2.7 https://git.<domain>/repos/<name> +// +// THE TAG IS THE RELEASE. It is an annotated tag in the repo's own remote: its message holds the +// notes, and git shows them (`git show v1.2.7`). A tag is made once and never moved: the push +// names no old commit, and the remote refuses a name that it has. +// +// WHO CUT IT, AND WHEN, is one event on the repo's own context (/repos/<name>), beside its pulls: +// +// release/cut { tag, version, commitOid, previous, notes } +// +// `previous` is the tag before it, or null for the first. Who and when are the event's own +// (`source.principal`, `createdAt`), which the platform stamps. A tag that git pushed by hand has +// no such event: the page shows it with its commit alone. +// +// TO CUT A RELEASE IS THE ONE CALL (`cutRelease`, which the mind's API offers as +// `itx.config.releaseCut`). With no version named, the next one raises the patch: v1.2.7 becomes +// v1.2.8, and a repo's first release is v0.1.0. When main is at the newest release already, +// nothing is cut. The notes, when none are given, are the first line of each commit of main since +// the release before: main is a straight line, each commit one pull (pulls.ts). +// +// WHY THIS FILE SPEAKS GIT'S WIRE. The mind's repo API reads branches and writes main, and knows +// no tag. So the tags are read, and a tag is pushed, as git does it: smart HTTP to the repo's +// Cloudflare Artifacts remote, with a token that is minted for the one request (app.ts, "THE +// REMOTE"). A tag's push carries one object, the tag itself. +import type { IterateConfigEntrypoint } from "iterate/sdk"; +import type { StreamEvent } from "iterate/stream/processor"; +import { z } from "zod"; + +type Itx = ReturnType<IterateConfigEntrypoint["getItx"]>; + +/** Where a repo's remote is, and the credential for it (`Basic …`), or null where none is asked. */ +export type Remote = { address: string; authorization: string | null }; + +/** A tag of the remote. `oid` is what the ref names: the tag's own object for an annotated tag, + * the commit for a plain one. `commitOid` is the commit either way. */ +export type Tag = { name: string; oid: string; commitOid: string }; + +export type Version = [major: number, minor: number, patch: number]; + +export type Release = { + tag: string; + /** `1.2.7` for the tag `v1.2.7`; null for a tag that is no version. */ + version: string | null; + commitOid: string; + /** From the `release/cut` event; each null for a tag that has none. */ + by: string | null; + at: string | null; + previous: string | null; + notes: string | null; +}; + +const Cut = z.object({ + tag: z.string().min(1), + version: z.string().min(1), + commitOid: z.string().regex(/^[0-9a-f]{40}$/), + previous: z.string().nullable(), + notes: z.string(), +}); + +const TAGS = "refs/tags/"; +const ZERO_OID = "0".repeat(40); +/** How far back main is read for the notes. */ +const HISTORY_READ = 300; +/** The most that is read of one answer of the remote: a list of refs, or a push's report. */ +const ANSWER_BYTES = 4 * 1024 * 1024; +const WRITE_TOKEN_SECONDS = 300; +const READ_TOKEN_SECONDS = 300; + +// ── VERSIONS ── + +/** `v1.2.7` or `1.2.7` as numbers; null for any other text. */ +export function versionOf(text: string): Version | null { + const match = /^v?(0|[1-9]\d{0,8})\.(0|[1-9]\d{0,8})\.(0|[1-9]\d{0,8})$/.exec(text); + return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null; +} + +export const compareVersions = (a: Version, b: Version) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2]; + +export const tagOf = (version: Version) => `v${version.join(".")}`; + +/** The version after `latest`: the patch raised, or the minor or the major with what is under it + * at zero. A repo's first is 0.1.0. */ +export function nextVersion(latest: Version | null, bump: "patch" | "minor" | "major" = "patch"): Version { + if (!latest) return [0, 1, 0]; + if (bump === "major") return [latest[0] + 1, 0, 0]; + if (bump === "minor") return [latest[0], latest[1] + 1, 0]; + return [latest[0], latest[1], latest[2] + 1]; +} + +/** The tags that are versions, newest version first. */ +function versionsIn(tags: Tag[]) { + return tags + .flatMap((tag) => { + const version = versionOf(tag.name); + return version && tag.name.startsWith("v") ? [{ ...tag, version }] : []; + }) + .sort((a, b) => compareVersions(b.version, a.version)); +} + +// ── THE RELEASES OF A REPO ── + +/** The repo's releases, newest first: its version tags by version, then any other tag by name. + * Each has what its `release/cut` event says, when it has one. */ +export async function releasesIn(itx: Itx, repo: string): Promise<Release[]> { + const [tags, cuts] = await Promise.all([ + readTags(await remoteOf(itx, repo, "read")), + cutsIn(itx, repo), + ]); + return releasesOf(tags, cuts); +} + +export function releasesOf(tags: Tag[], cuts: Map<string, Omit<Release, "tag" | "version" | "commitOid"> & { commitOid: string }>): Release[] { + const versions = versionsIn(tags); + const others = tags + .filter((tag) => !versions.some(({ name }) => name === tag.name)) + .sort((a, b) => (a.name < b.name ? 1 : -1)); + return [...versions, ...others].map((tag) => { + const cut = cuts.get(tag.name); + // an event that names another commit than the tag has is not this tag's + const said = cut && cut.commitOid === tag.commitOid ? cut : null; + const version = versionOf(tag.name); + return { + tag: tag.name, + version: version && tag.name.startsWith("v") ? version.join(".") : null, + commitOid: tag.commitOid, + by: said?.by ?? null, + at: said?.at ?? null, + previous: said?.previous ?? null, + notes: said?.notes ?? null, + }; + }); +} + +/** What the repo's `release/cut` events say, by tag: the first event of a tag is the tag's. Only + * those few fields are kept of the log. */ +async function cutsIn(itx: Itx, repo: string) { + const cuts = new Map<string, { commitOid: string; by: string | null; at: string; previous: string | null; notes: string }>(); + let after = 0; + for (;;) { + const page = await itx.cd(repo).readEvents(after, 1000); + for (const event of page.events as StreamEvent[]) { + if (event.type !== "release/cut") continue; + const cut = Cut.safeParse(event.payload || {}); + if (!cut.success || cuts.has(cut.data.tag)) continue; + const person = event.source.principal || event.source.onBehalfOf?.principal; + cuts.set(cut.data.tag, { + commitOid: cut.data.commitOid, + by: person?.email?.split("@")[0] || person?.name || null, + at: event.createdAt, + previous: cut.data.previous, + notes: cut.data.notes, + }); + } + if (page.atHead) return cuts; + after = page.scannedThroughOffset; + } +} + +// ── CUT A RELEASE ── + +export type CutInput = { + /** The version to cut, `1.3.0` or `v1.3.0`: newer than every release of the repo. */ + version?: string; + /** With no `version`: which part the next one raises. `patch` when not said. */ + bump?: "patch" | "minor" | "major"; + /** What the release brings, as text. With none, the commits of main since the release before. */ + notes?: string; + /** Who git names as the one who tagged. With none, `releases@<the mind's own domain>`. */ + tagger?: { name: string; email: string }; +}; + +export type CutOutcome = + | { cut: true; tag: string; version: string; commitOid: string; previous: string | null; notes: string } + | { cut: false; why: string; tag: string | null; commitOid: string | null }; + +/** CUT A RELEASE OF A REPO: an annotated tag on main's newest commit, then the `release/cut` + * event that says so. It answers `{ cut: false, why }` and changes nothing when main is at the + * newest release already, or has no commit. It throws, in words for the one who asked, when the + * version is no version or is not newer than the newest release, or the remote refuses the tag. */ +export async function cutRelease(itx: Itx, repo: string, input: CutInput = {}): Promise<CutOutcome> { + const handle = itx.repos.get(repo); + const [history, tags] = await Promise.all([ + handle.log({ limit: HISTORY_READ }), + readTags(await remoteOf(itx, repo, "read")), + ]); + const tip = history[0]; + if (!tip) return { cut: false, why: `${repo} has no commit on main`, tag: null, commitOid: null }; + const latest = versionsIn(tags)[0] || null; + if (latest && latest.commitOid === tip.oid) + return { + cut: false, + why: `main is at ${latest.name} already: nothing is new`, + tag: latest.name, + commitOid: tip.oid, + }; + + let version: Version; + if (input.version === undefined) version = nextVersion(latest?.version || null, input.bump); + else { + const named = versionOf(input.version); + if (!named) throw new Error(`"${input.version}" is no version: write it as 1.2.7`); + if (latest && compareVersions(named, latest.version) <= 0) + throw new Error(`${tagOf(named)} is not newer than ${latest.name}, the newest release`); + version = named; + } + const tag = tagOf(version); + if (tags.some(({ name }) => name === tag)) throw new Error(`the tag ${tag} is there already`); + + const notes = (input.notes?.trim() || notesOf(history, latest)).slice(0, 20_000); + const tagger = input.tagger || { name: "releases", email: `releases@${new URL(await itx.url()).hostname}` }; + const name = repo.slice("/repos/".length); + const object = tagObject({ + tag, + commitOid: tip.oid, + tagger, + seconds: Math.floor(Date.now() / 1000), + message: `${name} ${tag}\n\n${notes}`, + }); + await pushTag(await remoteOf(itx, repo, "write"), tag, object); + + const payload = { tag, version: version.join("."), commitOid: tip.oid, previous: latest?.name || null, notes }; + // one tag is cut once: a second try of this call lands no second event + await itx.cd(repo).append({ type: "release/cut", idempotencyKey: `release/cut:${tag}`, payload }); + return { cut: true, ...payload }; +} + +/** The notes of a release with none given: the first line of each commit of main since the + * release before, newest first. */ +function notesOf(history: { oid: string; message: string }[], latest: { name: string; commitOid: string } | null) { + if (!latest) return `The first release: main at ${history[0]!.oid.slice(0, 7)}.`; + const reached = history.findIndex(({ oid }) => oid === latest.commitOid); + const since = reached < 0 ? history : history.slice(0, reached); + const lines = since.map(({ oid, message }) => `- ${message.trim().split("\n")[0] || "(no message)"} (${oid.slice(0, 7)})`); + if (reached < 0) lines.push(`- and the commits before these, back to ${latest.name}`); + return `Since ${latest.name}:\n\n${lines.join("\n")}`; +} + +// ── GIT'S WIRE: the tags of a remote, and the push of one tag ── + +/** The repo's remote with a token for one request, as git sends it. */ +async function remoteOf(itx: Itx, repo: string, scope: "read" | "write"): Promise<Remote> { + const artifacts = await itx.cfArtifacts.get(repo); + const [address, token] = await Promise.all([ + artifacts.remote(), + artifacts.createToken(scope, scope === "write" ? WRITE_TOKEN_SECONDS : READ_TOKEN_SECONDS), + ]); + return { address, authorization: `Basic ${btoa(`x:${token.plaintext}`)}` }; +} + +const encoder = new TextEncoder(); +const decoder = new TextDecoder(); + +function concat(parts: Uint8Array[]): Uint8Array<ArrayBuffer> { + const whole = new Uint8Array(parts.reduce((length, part) => length + part.length, 0)); + let at = 0; + for (const part of parts) { + whole.set(part, at); + at += part.length; + } + return whole; +} + +/** One line of git's wire: four hex digits of its whole length, then the bytes. */ +function pktLine(line: string | Uint8Array): Uint8Array { + const bytes = typeof line === "string" ? encoder.encode(line) : line; + return concat([encoder.encode((bytes.length + 4).toString(16).padStart(4, "0")), bytes]); +} +const FLUSH = encoder.encode("0000"); +const DELIM = encoder.encode("0001"); + +/** The lines of an answer, each without its length and its last newline. A flush or a + * delimiter is no line. An answer that is cut short ends the lines. */ +function pktLines(body: Uint8Array): string[] { + const lines: string[] = []; + let at = 0; + while (at + 4 <= body.length) { + const length = Number.parseInt(decoder.decode(body.subarray(at, at + 4)), 16); + if (Number.isNaN(length)) break; + if (length < 4) { + at += 4; + continue; + } + if (at + length > body.length) break; + lines.push(decoder.decode(body.subarray(at + 4, at + length)).replace(/\n$/, "")); + at += length; + } + return lines; +} + +async function post(remote: Remote, service: "git-upload-pack" | "git-receive-pack", body: Uint8Array<ArrayBuffer>) { + const headers = new Headers({ + "content-type": `application/x-${service}-request`, + accept: `application/x-${service}-result`, + "git-protocol": "version=2", + "user-agent": "git/2.45.0 (iterate-git-app)", + }); + if (remote.authorization) headers.set("authorization", remote.authorization); + const answer = await fetch(`${remote.address}/${service}`, { method: "POST", headers, body, redirect: "manual" }); + const bytes = new Uint8Array(await answer.arrayBuffer()); + // never the remote's own words past a few: an answer of the remote is no text of this app + if (!answer.ok) throw new Error(`the repo's remote answered ${answer.status} to ${service}`); + if (bytes.length > ANSWER_BYTES) throw new Error(`the repo's remote answered too much to ${service}`); + return bytes; +} + +/** Every tag of the remote, with the commit it stands on. */ +export async function readTags(remote: Remote): Promise<Tag[]> { + const request = concat([ + pktLine("command=ls-refs\n"), + DELIM, + pktLine("peel\n"), + pktLine(`ref-prefix ${TAGS}\n`), + FLUSH, + ]); + const tags: Tag[] = []; + for (const line of pktLines(await post(remote, "git-upload-pack", request))) { + const [oid, ref, ...attributes] = line.split(" "); + if (!oid || !/^[0-9a-f]{40}$/.test(oid) || !ref?.startsWith(TAGS)) continue; + const peeled = attributes.find((attribute) => attribute.startsWith("peeled:"))?.slice("peeled:".length); + tags.push({ name: ref.slice(TAGS.length), oid, commitOid: peeled || oid }); + } + return tags; +} + +/** An annotated tag as git holds one: its text, and the oid that the text has. */ +export type TagObject = { payload: Uint8Array; oid: Promise<string> }; + +/** `tag` on `commitOid`, tagged by `tagger` at `seconds` (of the epoch, written as UTC), with + * `message`. */ +export function tagObject(input: { + tag: string; + commitOid: string; + tagger: { name: string; email: string }; + seconds: number; + message: string; +}): TagObject { + // git takes no `<`, `>` or newline in a name or an address + const clean = (text: string) => text.replace(/[<>\n\r\0]/g, "").trim(); + const payload = encoder.encode( + [ + `object ${input.commitOid}`, + "type commit", + `tag ${input.tag}`, + `tagger ${clean(input.tagger.name) || "releases"} <${clean(input.tagger.email)}> ${input.seconds} +0000`, + "", + `${input.message.replace(/\0/g, "").trimEnd()}\n`, + ].join("\n"), + ); + const oid = crypto.subtle + .digest("SHA-1", concat([encoder.encode(`tag ${payload.length}\0`), payload])) + .then(hex); + return { payload, oid }; +} + +const hex = (bytes: ArrayBuffer) => + [...new Uint8Array(bytes)].map((byte) => byte.toString(16).padStart(2, "0")).join(""); + +async function deflate(bytes: Uint8Array<ArrayBuffer>): Promise<Uint8Array> { + const stream = new Blob([bytes]).stream().pipeThrough(new CompressionStream("deflate")); + return new Uint8Array(await new Response(stream).arrayBuffer()); +} + +/** A pack of the one tag object: git's header, the object's type (4, a tag) and length, its text + * deflated, and the SHA-1 of all of it. */ +async function packOf(object: TagObject): Promise<Uint8Array> { + const header = new Uint8Array(12); + header.set(encoder.encode("PACK"), 0); + new DataView(header.buffer).setUint32(4, 2); + new DataView(header.buffer).setUint32(8, 1); + const lengthBytes: number[] = []; + let size = object.payload.length; + let byte = (4 << 4) | (size & 0x0f); + size >>= 4; + while (size > 0) { + lengthBytes.push(byte | 0x80); + byte = size & 0x7f; + size >>= 7; + } + lengthBytes.push(byte); + const body = concat([header, Uint8Array.from(lengthBytes), await deflate(concat([object.payload]))]); + return concat([body, new Uint8Array(await crypto.subtle.digest("SHA-1", body))]); +} + +/** Push one new tag. The push names no old commit, so the remote refuses a tag that is there. It + * throws unless the remote says that it took the pack and made the ref. */ +export async function pushTag(remote: Remote, tag: string, object: TagObject): Promise<void> { + if (!isTagName(tag)) throw new Error(`"${tag}" is no name for a tag`); + const ref = `${TAGS}${tag}`; + const request = concat([ + pktLine(`${ZERO_OID} ${await object.oid} ${ref}\0report-status agent=iterate-git-app/1\n`), + FLUSH, + await packOf(object), + ]); + const report = pktLines(await post(remote, "git-receive-pack", request)); + const refused = report.find((line) => line.startsWith(`ng ${ref} `)); + if (refused) throw new Error(`the remote refused the tag ${tag}: ${refused.slice(`ng ${ref} `.length, 300)}`); + if (!report.includes("unpack ok") || !report.includes(`ok ${ref}`)) + throw new Error(`the remote did not say that it made the tag ${tag}`); +} + +/** A tag's name as this app's pages hold one: letters, digits, `.`, `_` and `-`. */ +export const isTagName = (name: string) => + /^[A-Za-z0-9_][A-Za-z0-9._-]{0,99}$/.test(name) && !name.endsWith(".") && !name.endsWith(".lock") && !name.includes("..");
M tests/local-mind.mjs
@@ -11,13 +11,15 @@ const MAIN = "refs/heads/main"; /** `folders`: where each repo is, by its path in the mind (`/repos/<name>`). `member`: the - * visitor's address when they are a member, null when they are not. + * visitor's address when they are a member, null when they are not. `remote`: where git's own + * smart HTTP serves the folders (git-http.mjs `gitServer`), which is what Cloudflare Artifacts is + * to the mind: only what reads or writes a tag asks for it (../releases.ts). * * What it gives back: `getItx()`, the mind's own itx, as the app's code holds it; `as(address)`, * the itx of a member's page, whose events are stamped with that member; `kv`, the mind's kv as * the app left it; `events`, each context's log by path; and `asked`, each call the app made of * a repo or of the list, in order (`files /repos/kernel`). */ -export function localMind({ folders, member }) { +export function localMind({ folders, member, remote }) { const kv = {}; const asked = []; const events = {}; @@ -164,6 +166,16 @@ /** An itx whose events are stamped as `principal` wrote them: a member's page, or with none * the mind's own code. */ const itxOf = (principal) => ({ + url: async () => "https://example.com", + cfArtifacts: { + get: async (repo) => ({ + remote: async () => { + if (!remote) throw new Error("this local mind was given no remote"); + return `${remote}${repo}`; + }, + createToken: async (scope) => ({ plaintext: `art_${scope}` }), + }), + }, kv: { get: async (key) => kv[key] || null, put: async (key, value) => {
A tests/releases.test.mjs
@@ -0,0 +1,171 @@ +// tests/releases.test.mjs — a release, from main's newest commit to a tag of git (../releases.ts), +// and the page that shows the releases (../pages.ts). Each test makes a repo with git itself; +// git-http.mjs serves it as git's own smart HTTP, which is what Cloudflare Artifacts is to the +// app, and git itself then says what the tag is. +// Run it from the repo's root with `node --test "tests/*.test.mjs"`. +import "@repos/stdlib/testing/mind-loader.mjs"; +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { compareVersions, cutRelease, nextVersion, releasesIn, versionOf } from "../releases.ts"; +import { repoWith } from "./fixtures.mjs"; +import { gitServer } from "./git-http.mjs"; +import { localMind } from "./local-mind.mjs"; + +const { gitApp } = await import("../app.ts"); +const look = { icon: () => new Response("<svg/>") }; +const repo = "/repos/kernel"; + +/** A repo, git's own server over it, and the mind that reaches it. */ +async function served(history, member = null) { + const kernel = repoWith(history); + const server = await gitServer({ [repo]: kernel.folder }); + const mind = localMind({ folders: { [repo]: kernel.folder }, member, remote: server.origin }); + return { kernel, server, mind, async [Symbol.asyncDispose]() { await server.close(); kernel[Symbol.dispose](); } }; +} + +test("a version is three numbers; the next one raises the patch, and a repo's first is 0.1.0", () => { + assert.deepEqual(versionOf("v1.2.7"), [1, 2, 7]); + assert.deepEqual(versionOf("1.2.7"), [1, 2, 7]); + for (const text of ["v1.2", "1.2.7-rc1", "v01.2.3", "latest", "v1.2.7\n", ""]) assert.equal(versionOf(text), null); + assert.deepEqual(nextVersion(null), [0, 1, 0]); + assert.deepEqual(nextVersion([1, 2, 7]), [1, 2, 8]); + assert.deepEqual(nextVersion([1, 2, 7], "minor"), [1, 3, 0]); + assert.deepEqual(nextVersion([1, 2, 7], "major"), [2, 0, 0]); + assert.ok(compareVersions([1, 10, 0], [1, 9, 9]) > 0); +}); + +test("the first cut is v0.1.0: an annotated tag on main's newest commit, as git itself reads it, and one event on the repo's context", async () => { + await using site = await served([ + { message: "Start", files: { "README.md": "# kernel\n" } }, + { message: "Add the SDK", files: { "sdk.ts": "export {};\n" } }, + ]); + const { kernel, mind } = site; + const tip = kernel.commits[1]; + + const outcome = await cutRelease(mind.as("ada@example.com"), repo); + + assert.deepEqual(outcome, { + cut: true, + tag: "v0.1.0", + version: "0.1.0", + commitOid: tip, + previous: null, + notes: `The first release: main at ${tip.slice(0, 7)}.`, + }); + // git's own word on what was pushed + assert.equal(kernel.git("cat-file", "-t", "v0.1.0"), "tag"); + assert.equal(kernel.git("rev-parse", "v0.1.0^{commit}"), tip); + assert.equal( + kernel.git("for-each-ref", "--format=%(taggername) %(taggeremail)|%(contents:subject)|%(contents:body)", "refs/tags/v0.1.0"), + `releases <releases@example.com>|kernel v0.1.0|The first release: main at ${tip.slice(0, 7)}.`, + ); + kernel.git("fsck", "--strict"); + // main is where it was + assert.equal(kernel.git("rev-parse", "main"), tip); + const [event] = mind.events[repo]; + assert.equal(event.type, "release/cut"); + assert.deepEqual(event.payload, { tag: "v0.1.0", version: "0.1.0", commitOid: tip, previous: null, notes: outcome.notes }); + assert.equal(event.source.principal.email, "ada@example.com"); +}); + +test("nothing is cut while main is at the newest release; a new commit makes the next patch, whose notes are main's commits since", async () => { + await using site = await served([{ message: "Start", files: { "README.md": "# kernel\n" } }]); + const { kernel, mind } = site; + const itx = mind.getItx(); + await cutRelease(itx, repo); + + assert.deepEqual(await cutRelease(itx, repo), { + cut: false, + why: "main is at v0.1.0 already: nothing is new", + tag: "v0.1.0", + commitOid: kernel.commits[0], + }); + assert.equal(mind.events[repo].length, 1); + + const sdk = kernel.more({ message: "Add the SDK (#1)\n\nIt was missing.", files: { "sdk.ts": "export {};\n" } }); + const fix = kernel.more({ message: "Fix the SDK (#2)", files: { "sdk.ts": "export const one = 1;\n" } }); + const second = await cutRelease(itx, repo); + + assert.equal(second.tag, "v0.1.1"); + assert.equal(second.previous, "v0.1.0"); + assert.equal(second.commitOid, fix); + assert.equal( + second.notes, + `Since v0.1.0:\n\n- Fix the SDK (#2) (${fix.slice(0, 7)})\n- Add the SDK (#1) (${sdk.slice(0, 7)})`, + ); + assert.equal(kernel.git("rev-parse", "v0.1.1^{commit}"), fix); + assert.equal(kernel.git("rev-parse", "v0.1.0^{commit}"), kernel.commits[0]); +}); + +test("a version can be named, with notes of its own; one that is not newer, or is no version, is refused and nothing is tagged", async () => { + await using site = await served([{ message: "Start", files: { "README.md": "# kernel\n" } }]); + const { kernel, mind } = site; + const itx = mind.getItx(); + await cutRelease(itx, repo, { version: "1.2.7", notes: "The one with the SDK." }); + assert.equal(kernel.git("for-each-ref", "--format=%(contents:body)", "refs/tags/v1.2.7"), "The one with the SDK."); + + kernel.more({ message: "More", files: { "more.txt": "more\n" } }); + await assert.rejects(cutRelease(itx, repo, { version: "1.2.7" }), /v1\.2\.7 is not newer than v1\.2\.7, the newest release/); + await assert.rejects(cutRelease(itx, repo, { version: "1.2.0" }), /not newer/); + await assert.rejects(cutRelease(itx, repo, { version: "soon" }), /"soon" is no version/); + assert.equal(kernel.git("tag", "--list"), "v1.2.7"); + + const minor = await cutRelease(itx, repo, { bump: "minor", tagger: { name: "Ada <Author>", email: "ada@example.com" } }); + assert.equal(minor.tag, "v1.3.0"); + assert.equal(kernel.git("for-each-ref", "--format=%(taggername) %(taggeremail)", "refs/tags/v1.3.0"), "Ada Author <ada@example.com>"); + kernel.git("fsck", "--strict"); +}); + +test("a tag is never moved: the remote refuses a second push of a name that it has", async () => { + await using site = await served([{ message: "Start", files: { "README.md": "# kernel\n" } }]); + const { kernel, server, mind } = site; + const { pushTag, tagObject } = await import("../releases.ts"); + await cutRelease(mind.getItx(), repo); + const other = kernel.more({ message: "More", files: { "more.txt": "more\n" } }); + const object = tagObject({ tag: "v0.1.0", commitOid: other, tagger: { name: "x", email: "x@example.com" }, seconds: 1, message: "again" }); + + await assert.rejects(pushTag({ address: `${server.origin}${repo}`, authorization: null }, "v0.1.0", object), /refused the tag v0\.1\.0|did not say/); + assert.equal(kernel.git("rev-parse", "v0.1.0^{commit}"), kernel.commits[0]); +}); + +test("the releases page lists the releases newest first, each with its commit, who cut it and its notes; a tag that git pushed is there with its commit alone; anyone reads a public repo's", async () => { + await using site = await served([{ message: "Start", files: { "README.md": "# kernel\n" } }]); + const { kernel, mind } = site; + await cutRelease(mind.as("ada@example.com"), repo); + const fix = kernel.more({ message: "Fix <it>", files: { "fix.txt": "fixed\n" } }); + await cutRelease(mind.getItx(), repo); + kernel.git("tag", "by-hand", kernel.commits[0]); + + assert.deepEqual( + (await releasesIn(mind.getItx(), repo)).map(({ tag, version, commitOid, by, previous }) => ({ tag, version, commitOid, by, previous })), + [ + { tag: "v0.1.1", version: "0.1.1", commitOid: fix, by: null, previous: "v0.1.0" }, + { tag: "v0.1.0", version: "0.1.0", commitOid: kernel.commits[0], by: "ada", previous: null }, + { tag: "by-hand", version: null, commitOid: kernel.commits[0], by: null, previous: null }, + ], + ); + + const git = gitApp({ public: [repo], ...look }); + const answer = await git.fetch(new Request("https://git.example.com/repos/kernel/releases"), mind); + const html = await answer.text(); + assert.equal(answer.status, 200); + assert.ok(html.includes(`<a href="/repos/kernel/releases" aria-current="page">Releases</a>`)); + const rows = html.slice(html.indexOf(`<ul class="releases">`), html.indexOf("</ul>", html.indexOf(`<ul class="releases">`))); + assert.deepEqual([...rows.matchAll(/<li id="([^"]+)"><b>([^<]+)<\/b>/g)].map((row) => row[2]), ["v0.1.1", "v0.1.0", "by-hand"]); + assert.ok(rows.includes(`<li id="v0.1.0"><b>v0.1.0</b> <span class="by">at <a href="/repos/kernel/commit/${kernel.commits[0]}"><code>${kernel.commits[0].slice(0, 7)}</code></a>, cut by ada, `)); + // the notes are text, never markup + assert.ok(rows.includes(`<pre class="notes">Since v0.1.0:\n\n- Fix <it> (${fix.slice(0, 7)})</pre>`)); + assert.ok(rows.includes(`<li id="by-hand"><b>by-hand</b> <span class="by">at <a href="/repos/kernel/commit/${kernel.commits[0]}"><code>${kernel.commits[0].slice(0, 7)}</code></a>, a tag with no release notes</span></li>`)); + assert.ok(html.includes("git clone --branch v0.1.1 https://git.example.com/repos/kernel")); + + // a repo that is not public answers the mind's sign-in to anyone who is no member + const closed = gitApp({ public: [], ...look }); + assert.equal((await closed.fetch(new Request("https://git.example.com/repos/kernel/releases"), mind)).status, 401); +}); + +test("a repo with no release says so", async () => { + await using site = await served([{ message: "Start", files: { "README.md": "# kernel\n" } }]); + const git = gitApp({ public: [repo], ...look }); + const html = await (await git.fetch(new Request("https://git.example.com/repos/kernel/releases"), site.mind)).text(); + assert.ok(html.includes(`<p class="note">No release yet.</p>`)); +});