Public: anyone can read this; the crew can change it.

A release's entry on /changelog links the commit range it contains #14171

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

torque/forge:torque/14142-a-release-s-entry-on-changelog-links-the → main 10 commits fork 3 threads · 3 unresolved

  • Merged. torque/14142-a-release-s-entry-on-changelog-links-the was merged into main as 9d1508b.

Review

Sign in to review this change.
15 files changed +337 −15
docs/features/changelog.md +4
@@ -6,6 +6,10 @@ The terminal's palette has `Changelog`, the same read for anyone, a guest includ
66
77 One bounded `git log` read, cached per head oid; Server-Timing names `releases` and `render`.
88
9 ## The commits a release holds
10
11 A pull on the page that a release carried says which: `in 0.3.0 a1b2c3d…e4f5a6b`, the range linking the compare page `/<owner>/<name>/compare/<from>...<to>` that lists the commits from the previous release to its own (the first release shows only its one commit, unlinked). The releases are read from the repository's default branch head, not the running commit, so a preview whose commit is not in the repository shows them too; the page's `ETag` includes that head. In the terminal, `c` on a Changelog release opens the same commits, and Enter on one opens it; the row also names the range. The range is built in `release/range.ts`, and a hash that is not a full hex object id forms no link. Tested in `test/changelog-range.test.ts` and `test/tui-changelog.test.ts`.
12
913 ## How close each open milestone is (#11409)
1014
1115 `/changelog` opens with one line per open milestone of the forge's own repository: its name (linked to its milestone page), `N of M done` and a progress bar. A deferred or closed milestone is left out, and the block is absent when none is open or when the reader may not open the repository (a guest on a private one). The terminal's Changelog screen shows the same lines above the releases (name, `N of M done`, at most five), under the same read check. Both read `nearMilestones` in `web/pages/milestones_near.ts`; the page's `ETag` includes them.
src/http/server.ts +2 −1
@@ -264,7 +264,7 @@ import {
264264 previewSubmit,
265265 } from "../web/pages/edit.ts";
266266 import { configPage, configSubmit } from "../web/pages/config.ts";
267 import { commitPage, commitsPage } from "../web/pages/commits.ts";
267 import { commitPage, commitsPage, comparePage } from "../web/pages/commits.ts";
268268 import { eventsList } from "../web/pages/events.ts";
269269 import {
270270 issueCommentSubmit,
@@ -1713,6 +1713,7 @@ export function buildRouter(): Router<Handler> {
17131713
17141714 router.add("GET", "/:owner/:name/commits", commitsPage);
17151715 router.add("GET", "/:owner/:name/commit/:oid", commitPage);
1716 router.add("GET", "/:owner/:name/compare/:range", comparePage);
17161717 router.add("POST", "/:owner/:name/fork", forkSubmit);
17171718 // Forge it: a fresh forge with this repository as its app, then its claim link.
17181719 router.add("POST", "/:owner/:name/forge", forgeItSubmit);
src/perf/page_budget.ts +2 −1
@@ -33,7 +33,8 @@ export const PAGE_BUDGETS: readonly PageBudget[] = [
3333 { page: "explore", pattern: "/explore", medianMs: 50, statements: 18 },
3434 { page: "map", pattern: "/map", medianMs: 50, statements: 21 },
3535 { page: "an app page", pattern: "/:owner/:name", medianMs: 50, statements: 49 },
36 { page: "changelog", pattern: "/changelog", medianMs: 50, statements: 20 },
36 // 21: the release range reads the forge repository's row once, to name its default branch.
37 { page: "changelog", pattern: "/changelog", medianMs: 50, statements: 21 },
3738 { page: "next up", pattern: "/:owner/:name/next", medianMs: 50, statements: 68 },
3839 // The space (#12770), which the owner opens to watch growth: the page and the
3940 // `space.json` it reads are two requests, so each has its own row.
src/release/changelog.ts +13 −5
@@ -20,6 +20,10 @@ export interface ReleaseEntry {
2020 readonly version: string;
2121 readonly date: string;
2222 readonly pulls: readonly ReleasePull[];
23 /** The release commit's id. */
24 readonly oid: string;
25 /** The release before this one: absent for the first release. */
26 readonly previous?: string;
2327 }
2428
2529 const cache = new Map<string, { oid: string; entries: ReleaseEntry[] }>();
@@ -30,13 +34,17 @@ export async function readChangelog(dir: string, branch: string): Promise<Releas
3034 if (!head.ok) return [];
3135 const cached = cache.get(dir);
3236 if (cached?.oid === head.value) return cached.entries;
33 const log = await commitLog(dir, head.value, { limit: CHANGELOG_LIMIT, grep: "^Release [0-9]+\\.[0-9]+\\.[0-9]+: " });
37 const log = await commitLog(dir, head.value, { limit: CHANGELOG_LIMIT + 1, grep: "^Release [0-9]+\\.[0-9]+\\.[0-9]+: " });
3438 if (!log.ok) return [];
35 const entries: ReleaseEntry[] = [];
36 for (const commit of log.value) {
39 // One more than shown, so the oldest shown still knows its previous release.
40 const found = log.value.flatMap((commit) => {
3741 const release = parseReleaseSubject(commit.subject);
38 if (release !== undefined) entries.push({ version: release.version, date: commit.date, pulls: release.pulls });
39 }
42 return release === undefined ? [] : [{ commit, release }];
43 });
44 const entries: ReleaseEntry[] = found.slice(0, CHANGELOG_LIMIT).map(({ commit, release }, i) => {
45 const before = found[i + 1]?.commit.oid;
46 return { version: release.version, date: commit.date, pulls: release.pulls, oid: commit.oid, ...(before === undefined ? {} : { previous: before }) };
47 });
4048 cache.set(dir, { oid: head.value, entries });
4149 return entries;
4250 }
src/release/landings.ts +4
@@ -44,6 +44,10 @@ export interface Landing {
4444 readonly with?: readonly string[];
4545 /** Whose change this took, where the commit could not say (`credits.ts`). */
4646 readonly credit?: Credit;
47 /**
48 * The release that carried it and the commits that release holds, set by the page that shows it.
49 */
50 readonly shippedIn?: { readonly version: string; readonly from?: string; readonly to: string };
4751 }
4852
4953 export interface Landings {
src/release/range.ts added +35
@@ -0,0 +1,35 @@
1 /**
2 * The commits a release contains, as a link: from the previous release's commit to this one's.
3 * Plain data in, plain data out; a hash that is not hex of a full object id forms no link.
4 */
5
6 import { isSafeOid } from "../git/guard.ts";
7
8 export interface Range {
9 /** The previous release's commit, absent for the first release. */
10 readonly from?: string;
11 readonly to: string;
12 }
13
14 /** The range, or undefined when a hash is not a full lowercase hex object id. */
15 export function rangeOf(to: string, from?: string): Range | undefined {
16 if (!isSafeOid(to)) return undefined;
17 if (from === undefined) return { to };
18 return isSafeOid(from) ? { from, to } : { to };
19 }
20
21 /** The compare page's path under a repository's base: `/compare/<from>...<to>`. */
22 export function comparePath(r: Range & { from: string }): string {
23 return `/compare/${r.from}...${r.to}`;
24 }
25
26 /** "a1b2c3d…e4f5a6b", or the one short hash for a first release. */
27 export function rangeWords(r: Range): string {
28 return r.from === undefined ? r.to.slice(0, 7) : `${r.from.slice(0, 7)}…${r.to.slice(0, 7)}`;
29 }
30
31 /** What the compare page reads from its path segment: `<from>...<to>`, both full hex ids. */
32 export function parseRange(segment: string): (Range & { from: string }) | undefined {
33 const m = /^([0-9a-f]{40}|[0-9a-f]{64})\.\.\.([0-9a-f]{40}|[0-9a-f]{64})$/.exec(segment);
34 return m === null ? undefined : { from: m[1]!, to: m[2]! };
35 }
src/tui/screens/changelog.ts +63 −1
@@ -11,10 +11,14 @@ import { chapterOfPulls, listChapters } from "../../core/chapters.ts";
1111 import { groupByChapter, type ChapterEntry, type Group } from "../../release/chapter_groups.ts";
1212 import { gather, plainTitle } from "../../story/gather.ts";
1313 import { monthLabel } from "../../release/month.ts";
14 import { rangeOf, rangeWords } from "../../release/range.ts";
15 import { commitLog } from "../../git/read.ts";
16 import { repoDir } from "../../git/repos.ts";
1417 import { forgeChangelog, type ReleaseEntry } from "../../release/changelog.ts";
1518 import { readLandings, type Landing } from "../../release/landings.ts";
1619 import { nearMilestones, nearWords, type Near } from "../../web/pages/milestones_near.ts";
1720 import { sourceFor } from "../../view/source.ts";
21 import type { Commit } from "../../view/source.ts";
1822 import type { Ctx, Screen } from "../app/app.ts";
1923 import { binding } from "../app/keys.ts";
2024 import type { Session } from "../session.ts";
@@ -22,6 +26,7 @@ import { fill, len, split } from "../ui/layout.ts";
2226 import { style } from "../term/style.ts";
2327 import { truncate } from "../term/width.ts";
2428 import { emptyState } from "../ui/widgets.ts";
29 import { commitScreen } from "./commits.ts";
2530 import { pullScreen } from "./pull.ts";
2631 import { wavesScreen } from "./waves.ts";
2732 import { Filter, ListState, ago, drawList, metaOf, type ListRow } from "./common.ts";
@@ -31,12 +36,22 @@ export function releaseMatches(filter: Filter, e: ReleaseEntry): boolean {
3136 return filter.matches([e.version, ...e.pulls.map((p) => plainTitle(p.title))].join("\n"));
3237 }
3338
39 /**
40 * The commits the release holds, as the page words them ("a1b2c3d…e4f5a6b"); empty without a full
41 * id.
42 */
43 export function releaseRange(e: ReleaseEntry): string {
44 const r = rangeOf(e.oid, e.previous);
45 return r === undefined ? "" : rangeWords(r);
46 }
47
3448 export function changelogRows(entries: readonly ReleaseEntry[]): ListRow[] {
3549 return entries.map((e) => ({
3650 title: e.version,
3751 meta: metaOf(
3852 ago(e.date),
3953 `${e.pulls.length} ${e.pulls.length === 1 ? "pull" : "pulls"}`,
54 releaseRange(e),
4055 e.pulls.map((p) => `#${p.number} ${plainTitle(p.title)}`.trim()).join("; "),
4156 ),
4257 }));
@@ -116,6 +131,47 @@ export function pullLines(pulls: readonly Pull[], credits: ReadonlyMap<number, s
116131 );
117132 }
118133
134 /** Commits the range screen lists: as many as the compare page. */
135 const RANGE_MAX = 100;
136
137 /**
138 * The commits a release holds, as the compare page lists them: previous release's commit to its own
139 * (the first release shows its one commit). Enter opens a commit.
140 */
141 function releaseCommits(f: Session, ctx: Ctx, src: Extract<ReturnType<typeof sourceFor>, { ok: true }>["value"], dir: string, entry: ReleaseEntry): Screen {
142 const state = new ListState();
143 let commits: Commit[] = [];
144 let loaded = false;
145 const range = rangeOf(entry.oid, entry.previous);
146 return {
147 title: `${entry.version} commits`,
148 keys: [binding(["j", "k"], "move"), binding(["enter"], "open commit"), binding(["esc", "q"], "back")],
149 async load() {
150 if (range !== undefined) {
151 const log = await commitLog(dir, range.from === undefined ? range.to : `${range.from}..${range.to}`, { limit: range.from === undefined ? 1 : RANGE_MAX });
152 if (log.ok) commits = log.value;
153 }
154 loaded = true;
155 ctx.invalidate();
156 },
157 render(area, s) {
158 if (commits.length === 0) {
159 emptyState(s, area, ctx.theme.c, { title: loaded ? "No commits" : "Reading…", body: "This release names no commits." });
160 return;
161 }
162 drawList(s, area, ctx.theme.c, state, commits.map((c) => ({ title: c.subject, meta: metaOf(c.oid.slice(0, 7), ago(c.date)) })));
163 },
164 key(e) {
165 if (e.key === "esc" || e.key === "q") ctx.pop();
166 else if (e.key === "enter") {
167 const commit = commits[state.index];
168 if (commit !== undefined) ctx.push(commitScreen(f, ctx, src, commit));
169 } else state.key(e, commits.length);
170 return true;
171 },
172 };
173 }
174
119175 /**
120176 * One release's pulls; Enter opens a pull as the changelog's Enter once did, and a gathered line
121177 * lists its own pulls.
@@ -171,6 +227,7 @@ export function changelogScreen(f: Session, ctx: Ctx): Screen {
171227 binding(["/"], "find"),
172228 binding(["enter"], "open"),
173229 binding(["w"], "by wave"),
230 binding(["c"], "commits"),
174231 binding(["esc", "q"], "close"),
175232 ],
176233 async load() {
@@ -239,7 +296,12 @@ export function changelogScreen(f: Session, ctx: Ctx): Screen {
239296 filter.query = "";
240297 home();
241298 } else if (e.key === "esc" || e.key === "q") ctx.pop();
242 else if (e.key === "w") {
299 else if (e.key === "c") {
300 // The release's commit range, as the compare page lists it, behind the same read gate.
301 const entry = lines()[state.index]?.entry;
302 const opened = repoRef === undefined || entry === undefined ? undefined : sourceFor(f.app, f.user, repoRef);
303 if (entry !== undefined && repoRef !== undefined && opened?.ok) ctx.push(releaseCommits(f, ctx, opened.value, repoDir(f.app.reposRoot, repoRef.owner, repoRef.name), entry));
304 } else if (e.key === "w") {
243305 // The page's "Read it by wave": waves → a wave's changes → a change's pull, the same gate
244306 // as a pull.
245307 const opened = repoRef === undefined ? undefined : sourceFor(f.app, f.user, repoRef);
src/web/pages/changelog.ts +32 −3
@@ -18,6 +18,8 @@ import { newestLive, secondsWords } from "../../keeper/landed.ts";
1818 import { dayHeading, dayOf, daysJs, shippedToday } from "../../release/days.ts";
1919 import { hasMerged, mergedRows, readLandings, type Landing, type Landings, type MergedRow } from "../../release/landings.ts";
2020 import { askedAnchor, releaseAnchor } from "../../release/anchor.ts";
21 import { forgeChangelog, type ReleaseEntry } from "../../release/changelog.ts";
22 import { comparePath, rangeOf, rangeWords } from "../../release/range.ts";
2123 import { gather, plainTitle, type Gathered } from "../../story/gather.ts";
2224 import { milestoneHref, progress } from "./milestones.ts";
2325 import { nearMilestones, nearWords, type Near } from "./milestones_near.ts";
@@ -47,6 +49,30 @@ function nearBlock(base: string, near: readonly Near[]): Html | null {
4749 )}</ul>`;
4850 }
4951
52 /**
53 * Each landing named by a release gains the release's version and its commit range (`shippedIn`):
54 * the pull's own row then links the commits between the previous release and that one.
55 */
56 export function withReleases(read: Landings, repo: string, entries: readonly ReleaseEntry[]): Landings {
57 if (entries.length === 0) return read;
58 const byPull = new Map<number, ReleaseEntry>();
59 for (const e of entries) for (const p of e.pulls) if (!byPull.has(p.number)) byPull.set(p.number, e);
60 const mark = (l: Landing): Landing => {
61 const e = l.repo.toLowerCase() === repo.toLowerCase() ? byPull.get(l.number) : undefined;
62 const range = e === undefined ? undefined : rangeOf(e.oid, e.previous);
63 return e === undefined || range === undefined ? l : { ...l, shippedIn: { version: e.version, ...(range.from === undefined ? {} : { from: range.from }), to: range.to } };
64 };
outdated

Principles 1, 2, 7: a second 'Releases' list that repeats releases already on the page, under a bare label. Fold the range into the existing entry; and setting-list is a settings class, not the changelog's.

65 return { ...read, live: read.live.map(mark), onItsWay: read.onItsWay.map(mark) };
66 }
67
68 /** "in 0.3.0 a1b2c3d…e4f5a6b": the range links the compare page; a first release has one commit. */
69 function shippedWords(l: Landing): Html | null {
70 const s = l.shippedIn;
71 if (s === undefined) return null;
72 const words = rangeWords(s);
73 return html` · in ${s.version} ${s.from === undefined ? html`<span class="sha" title="${s.to}">${words}</span>` : html`<a class="sha" data-range href="/${l.repo}${comparePath({ from: s.from, to: s.to })}">${words}</a>`}`;
74 }
75
5076 /** Releases on a page: the rest are read on demand with `?before=`. */
5177 export const PAGE = 30;
5278
@@ -59,7 +85,7 @@ function landingRow(l: Landing, own: string | undefined, showRepo: boolean): Htm
5985 id: releaseAnchor(l.repo, l.number),
6086 nav: true,
6187 title: plainTitle(l.title),
62 meta: html`${showRepo || l.repo !== own ? html`${l.repo} · ` : null}#${l.number}${l.bet === undefined ? null : html` · ${badge(l.bet, { variant: "outline" })}`}${l.from === undefined ? null : html` · folded in from ${l.from}`}`,
88 meta: html`${showRepo || l.repo !== own ? html`${l.repo} · ` : null}#${l.number}${l.bet === undefined ? null : html` · ${badge(l.bet, { variant: "outline" })}`}${l.from === undefined ? null : html` · folded in from ${l.from}`}${shippedWords(l)}`,
6389 facts: [...(l.by === undefined ? [] : [{ label: "By", value: l.by }]), ...(l.with === undefined ? [] : [{ label: "With", value: l.with.join(", ") }]), ...(l.credit === undefined ? [] : [{ label: "Credit", value: html`${l.credit.name} · <a href="${l.credit.href}">${l.credit.source}</a>` }])],
6490 trail: time(l.at),
6591 });
@@ -316,7 +342,10 @@ export async function changelogPage(ctx: Ctx): Promise<Response> {
316342 const view = viewOf(ctx);
317343 const landed = await timePhaseAsync(ctx.request, "releases", () => readLandings(ctx.app, { limit: PAGE, before: ctx.url.searchParams.get("before") ?? undefined, keep: view.keep }));
318344 const { choice, bet, bets, others, repo: ownRepo, readable } = view.of(landed.own);
319 const read = withBets(ctx, landed, readable ? ownRepo : undefined);
345 // The releases are read from the repository's default branch head, not the running commit, so
346 // the range shows wherever the repository is.
347 const releases = await forgeChangelog(ctx.app);
348 const read = withReleases(withBets(ctx, landed, readable ? ownRepo : undefined), releases === undefined ? "" : `${releases.repo.ownerName}/${releases.repo.name}`, releases?.entries ?? []);
320349 // The forge's own repository, even before anything has landed in it.
321350 const planned = nearMilestones(ctx.app, landed.own ?? ctx.app.config.forgeRepo, ctx.auth.user);
322351 const near = planned?.near ?? [];
@@ -329,7 +358,7 @@ export async function changelogPage(ctx: Ctx): Promise<Response> {
329358 const toLive = newestLive(ctx.app.db);
330359 const target = askedAnchor(ctx.url.searchParams.get("release"));
331360 const flashed = readFlash(ctx.request) !== undefined;
332 const tag = flashed ? undefined : changelogTag(read.version, everything, [choice, bet, read.commit, read.live.map((l) => `${l.repo}#${l.number}`), readable, toLive ?? null, everything.map((l) => timeAgo(l.at)), new Date().toISOString().slice(0, 10), ctx.auth.user?.id ?? null, ctx.auth.user?.isAdmin === true, ctx.theme ?? null, near, stamp, read.more ?? null, ctx.url.searchParams.get("before") === null ? 0 : 1, target ?? null]);
361 const tag = flashed ? undefined : changelogTag(read.version, everything, [choice, bet, read.commit, read.live.map((l) => `${l.repo}#${l.number}`), readable, toLive ?? null, everything.map((l) => timeAgo(l.at)), new Date().toISOString().slice(0, 10), releases?.entries[0]?.oid ?? null, releases?.entries.length ?? 0, ctx.auth.user?.id ?? null, ctx.auth.user?.isAdmin === true, ctx.theme ?? null, near, stamp, read.more ?? null, ctx.url.searchParams.get("before") === null ? 0 : 1, target ?? null]);
333362 const keep = tag === undefined ? undefined : cacheHeaders(ctx, tag);
334363 if (keep !== undefined && keep.matched) return keep.response;
335364 const chapters = chapterEntries(ctx.app.db, read.live, ctx.auth.user);
src/web/pages/commits.ts +22
@@ -16,6 +16,7 @@ import type { CommitCheck } from "../../checks/commit_check.ts";
1616 import { diffCommit, type Diff } from "../../git/diff.ts";
1717 import { isSafeOid, isSafeRef, isSafeTreePath } from "../../git/guard.ts";
1818 import { commitLog } from "../../git/read.ts";
19 import { parseRange } from "../../release/range.ts";
1920 import { repoDir } from "../../git/repos.ts";
2021 import { notePhase, takeSessionTime, timePhase, timePhaseAsync } from "../../core/route_timing.ts";
2122 import type { Ctx } from "../../http/context.ts";
@@ -298,6 +299,27 @@ export async function commitsPage(ctx: Ctx): Promise<Response> {
298299 return response;
299300 }
300301
302 /** Commits a compare page lists: a range longer than this is cut and says so. */
303 const COMPARE_MAX = 100;
304
305 // GET /:owner/:name/compare/:range — the commits in `<from>...<to>` (full hex ids), newest first.
306 export async function comparePage(ctx: Ctx): Promise<Response> {
307 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
308 const repo = loadRepo(ctx);
309 if (!repo) return notFoundPage(ctx);
310 const range = parseRange(ctx.params.range ?? "");
311 if (range === undefined) return notFoundPage(ctx);
312 const scope = localScope(ctx, repo);
313 const dir = repoDir(ctx.app.reposRoot, repo.ownerName, repo.name);
314 const log = await timePhaseAsync(ctx.request, "log", () => commitLog(dir, `${range.from}..${range.to}`, { limit: COMPARE_MAX + 1 }));
315 if (!log.ok) return notFoundPage(ctx);
316 const commits = log.value.slice(0, COMPARE_MAX);
317 const body = html`${scopeHeader(ctx, scope, "commits")}
318 <p class="small muted">${commits.length === 0 ? "No commits" : `${commits.length}${log.value.length > COMPARE_MAX ? "+" : ""} commit${commits.length === 1 ? "" : "s"}`} from ${sha(range.from, `${scope.base}/commit/${range.from}`)} to ${sha(range.to, `${scope.base}/commit/${range.to}`)}.</p>
319 ${commitRows(scope, commits)}`;
320 return page({ ctx, title: `Compare · ${repo.name}`, crumbs: scope.crumbs, palette: scope.palette, body, styleCss: COMMITS_CSS });
321 }
322
301323 // GET /:owner/:name/commit/:oid — one commit's metadata and its diff.
302324 export async function commitPage(ctx: Ctx): Promise<Response> {
303325 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
test/changelog-range.test.ts added +117
@@ -0,0 +1,117 @@
1 /**
2 * A release's entry on /changelog links the commits it contains: previous release's commit … this
3 * one's.
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
10 import { createApp, type App } from "../src/app.ts";
11 import { getRepo } from "../src/core/repos.ts";
12 import { getUserByName } from "../src/core/users.ts";
13 import type { Landing } from "../src/release/landings.ts";
14 import { createUser } from "../src/core/users.ts";
15 import { serve, type Servers } from "../src/http/server.ts";
16 import { readChangelog } from "../src/release/changelog.ts";
17 import { comparePath, parseRange, rangeOf, rangeWords } from "../src/release/range.ts";
18 import { withReleases } from "../src/web/pages/changelog.ts";
19 import { repoDir } from "../src/git/repos.ts";
20
21 let dir: string;
22 let app: App;
23 let servers: Servers;
24
25 // The check stamps a running commit that is not in this repository; the page reads the forge's own
26 // repository against it, so the test runs unstamped.
27 const stamped = { FORGE_COMMIT: process.env["FORGE_COMMIT"], FORGE_APP_COMMIT: process.env["FORGE_APP_COMMIT"] };
28
29 beforeAll(async () => {
30 delete process.env["FORGE_COMMIT"];
31 delete process.env["FORGE_APP_COMMIT"];
32 dir = await mkdtemp(join(tmpdir(), "forge-changelog-range-"));
33 app = createApp({ dataDir: dir, port: 0, forgeRepo: "alice/forge" });
34 servers = await serve(app);
35 const u = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
36 if (!u.ok) throw new Error(u.error);
37 const repo = await createRepo(app, u.value, { name: "forge", visibility: "public" });
38 if (!repo.ok) throw new Error(JSON.stringify(repo.error));
39 for (const [n, message] of ["Release 0.1.0: One (#1)", "Release 0.2.0: Two (#2)", "Release 0.3.0: Three (#3)"].entries()) {
40 const done = await commitToBranch(app, u.value, repo.value, { message, files: [{ path: `f${n}.txt`, content: `${n}\n` }] });
41 if (!done.ok) throw new Error(JSON.stringify(done.error));
42 }
43 }, 60_000);
44
45 afterAll(async () => {
46 for (const [k, v] of Object.entries(stamped)) if (v !== undefined) process.env[k] = v;
47 servers.stop?.();
48 app.close();
49 await rm(dir, { recursive: true, force: true });
50 });
51
52 test("the release read knows each release's commit and the one before it; the first has none", async () => {
53 const entries = await readChangelog(repoDir(app.reposRoot, "alice", "forge"), "main");
54 expect(entries.map((e) => e.version)).toEqual(["0.3.0", "0.2.0", "0.1.0"]);
55 expect(entries[0]!.previous).toBe(entries[1]!.oid);
56 expect(entries[1]!.previous).toBe(entries[2]!.oid);
57 expect(entries[2]!.previous).toBeUndefined();
58 });
59
60 test("a pull a release carried links the range from the previous release to it; the first release shows only its own commit", async () => {
61 const entries = await readChangelog(repoDir(app.reposRoot, "alice", "forge"), "main");
62 const [c, b, a] = entries.map((e) => e.oid) as [string, string, string];
63 const landing = (number: number) => ({ repo: "alice/forge", number, title: `Pull ${number}`, at: "2026-01-01T00:00:00Z", live: true });
64 const read = withReleases({ version: "dev", commit: null, own: "alice/forge", live: [1, 2, 3].map(landing), onItsWay: [] }, "alice/forge", entries);
65 const [p1, p2, p3] = read.live as [Landing, Landing, Landing];
66 expect(p3.shippedIn).toEqual({ version: "0.3.0", from: b, to: c });
67 expect(p2.shippedIn).toEqual({ version: "0.2.0", from: a, to: b });
68 expect(p1.shippedIn).toEqual({ version: "0.1.0", to: a });
69 // Another repository's pull is not touched.
70 expect(withReleases({ ...read, live: [{ ...landing(3), repo: "bob/x" }] }, "alice/forge", entries).live[0]!.shippedIn).toBeUndefined();
71 });
72
73 test("the page shows the range on the pull's own row, read from the default branch head", async () => {
74 const entries = await readChangelog(repoDir(app.reposRoot, "alice", "forge"), "main");
75 const [c, b] = entries.map((e) => e.oid) as [string, string];
76 const { shippedRegion } = await import("../src/web/pages/changelog.ts");
77 const at = new Date().toISOString();
78 const read = withReleases({ version: "dev", commit: null, own: "alice/forge", live: [{ repo: "alice/forge", number: 3, title: "Three", at, live: true }], onItsWay: [] }, "alice/forge", entries);
79 const text = String(shippedRegion(read, "alice/forge"));
80 expect(text).toContain(`href="/alice/forge${comparePath({ from: b, to: c })}"`);
81 expect(text).toContain(`${b.slice(0, 7)}…${c.slice(0, 7)}`);
82 expect(text).toContain("in 0.3.0");
83 });
84
85 test("the compare page the link opens lists the commits in the range", async () => {
86 const [c, b] = (await readChangelog(repoDir(app.reposRoot, "alice", "forge"), "main")).map((e) => e.oid) as [string, string];
87 const res = await fetch(`${servers.url}/alice/forge/compare/${b}...${c}`);
88 expect(res.status).toBe(200);
89 const text = await res.text();
90 expect(text).toContain("Release 0.3.0: Three (#3)");
91 expect(text).not.toContain("Release 0.2.0: Two (#2)");
92 expect((await fetch(`${servers.url}/alice/forge/compare/main...${c}`)).status).toBe(404);
93 });
94
95 test("a hash that is not hex forms no link and is escaped", () => {
96 const good = "a".repeat(40);
97 expect(rangeOf("<script>")).toBeUndefined();
98 expect(rangeOf(good, "zz")).toEqual({ to: good });
99 expect(rangeWords({ from: "1".repeat(40), to: good })).toBe("1111111…aaaaaaa");
100 expect(parseRange(`${good}...${"b".repeat(40)}`)).toEqual({ from: good, to: "b".repeat(40) });
101 expect(parseRange(`${good}...<x>`)).toBeUndefined();
102 const read = withReleases({ version: "dev", commit: null, own: "a/b", live: [{ repo: "a/b", number: 1, title: "t", at: "2026-01-01T00:00:00Z", live: true }], onItsWay: [] }, "a/b", [{ version: "1.0.0", date: "2026-01-01T00:00:00Z", pulls: [{ number: 1, title: "t" }], oid: "<img src=x>", previous: good }]);
103 expect(read.live[0]!.shippedIn).toBeUndefined();
104 });
105
106 test("the page's tag moves with the default branch head", async () => {
107 const first = await fetch(`${servers.url}/changelog`);
108 expect(first.headers.get("etag")).not.toBeNull();
109 const u = (await createUser(app.db, { origin: "seed", trusted: true, username: "tagger", email: "[email protected]", password: "a-good-passphrase" }));
110 expect(u.ok).toBe(true);
111 const repo = getRepo(app.db, "alice", "forge")!;
112 const owner = getUserByName(app.db, "alice")!;
113 const done = await commitToBranch(app, owner, repo, { message: "Release 0.4.0: Four (#4)", files: [{ path: "f9.txt", content: "9\n" }] });
114 expect(done.ok).toBe(true);
115 const second = await fetch(`${servers.url}/changelog`);
116 expect(second.headers.get("etag")).not.toBe(first.headers.get("etag"));
117 });
test/no-polling.test.ts +1
@@ -304,6 +304,7 @@ const NOT_WALKED: Record<string, string> = {
304304 "/:owner/:name/builds/:label/cart.png": "needs a pinned build with a cart",
305305 "/:owner/:name/builds/:label/shots": "needs a pinned build with pictures",
306306 "/:owner/:name/chapters/:chapter": "needs a drafted chapter, which the seed does not make",
307 "/:owner/:name/compare/:range": "needs two commits the seed does not name (test/changelog-range.test.ts covers it)",
307308 "/:owner/:name/data/:file": "a CSV download of one table of an app database, not a page; the seed has no app data",
308309 "/:owner/:name/builds/:label/shots/:file": "needs a pinned build with pictures",
309310 "/:owner/:name/commit/:oid": "the seed does not keep the commit id; the commit page is a plain diff with the shell script only",
test/open-routes-floor.test.ts +1 −1
@@ -41,7 +41,7 @@ const FILL: Readonly<Record<string, string>> = {
4141 ref: "main", branch: "main", oid: "0".repeat(40), sha: "0".repeat(40), commit: "0".repeat(40),
4242 // Not seeded: each still has to answer its not-found with the floor.
4343 team: "core", env: "prod", file: "README.md", label: "v1", chapter: "1", kind: "desktop", machine: "web",
44 op: "x", step: "1", group: "a", version: "1", slug: "board", receipt: "r", token: "t", code: "c", spec: "16", stage: "build",
44 range: `${"0".repeat(40)}...${"1".repeat(40)}`, op: "x", step: "1", group: "a", version: "1", slug: "board", receipt: "r", token: "t", code: "c", spec: "16", stage: "build",
4545 };
4646
4747 /** Open GET routes that cannot be filled in from a seeded public repository, each with why. */
test/pages-budget.test.ts +9
@@ -17,6 +17,8 @@
1717 * so no reading answers here while the pages are asked, and a page that waits
1818 * for one is over `AFTER_IDLE_MS` by construction, on any machine.
1919 */
20 import { commitLog } from "../src/git/read.ts";
21 import { repoDir } from "../src/git/repos.ts";
2022 import { afterAll, beforeAll, expect, setSystemTime, test } from "bun:test";
2123 import { mkdtempSync, rmSync } from "node:fs";
2224 import { tmpdir } from "node:os";
@@ -154,6 +156,13 @@ beforeAll(async () => {
154156 ],
155157 });
156158 if (!files.ok) throw new Error(JSON.stringify(files.error));
159 // A release range for `/:owner/:name/compare/:range`: the repository's first commit to its
160 // newest.
161 const second = await commitToBranch(app, alice, forge, { message: "Release 0.1.0: A release (#1)", files: [{ path: "release.txt", content: "1\n" }] });
162 if (!second.ok) throw new Error(JSON.stringify(second.error));
163 const history = await commitLog(repoDir(app.reposRoot, "alice", "forge"), "main", { limit: 10 });
164 if (!history.ok || history.value.length < 2) throw new Error("the fixture repository has no range");
165 FIXTURE["/:owner/:name/compare/:range"] = `/alice/forge/compare/${history.value.at(-1)!.oid}...${history.value[0]!.oid}`;
157166 app.db.run("UPDATE repo SET is_template = 1 WHERE id = ?1", [forge.id]);
158167 pin(app.db, alice.id, forge.id);
159168 pin(app.db, alice.id, getRepo(app.db, "bob", "notes")!.id);
test/security-floor-routes.test.ts +1
@@ -83,6 +83,7 @@ const UNSEEDED: Record<string, string> = {
8383 "/:owner/:name/archive/:file": "a tarball download of a ref, not a page; the file name is one the seed cannot guess",
8484 "/:owner/:name/bets/:id": BET,
8585 "/:owner/:name/chapters/:chapter": "needs a chapter, which the seed does not draft (test/chapters.test.ts covers it)",
86 "/:owner/:name/compare/:range": "needs two commits of the seeded repository, which the seed does not name (test/changelog-range.test.ts covers it)",
8687 "/:owner/:name/data/:file": "a CSV download of one table of an app database, not a page; the seed has no app data (test/data-csv-export.test.ts covers it)",
8788 "/:owner/:name/builds/:label/cart": CART,
8889 "/:owner/:name/builds/:label/cart.png": CART,
test/tui-changelog.test.ts +31 −3
@@ -13,7 +13,7 @@ import { createUser } from "../src/core/users.ts";
1313 import { createForgeApp, forgeCommands, Session } from "../src/tui/forge.ts";
1414 import type { Ctx } from "../src/tui/app/app.ts";
1515 import { groupByChapter } from "../src/release/chapter_groups.ts";
16 import { chapterLines, changelogLines, changelogScreen, creditWords, pullLines } from "../src/tui/screens/changelog.ts";
16 import { chapterLines, changelogLines, changelogRows, changelogScreen, creditWords, pullLines } from "../src/tui/screens/changelog.ts";
1717 import { headlessTerminal } from "../src/tui/term/terminal.ts";
1818 import { quietLogs } from "./helpers/globals.ts";
1919 import { settleApp } from "./helpers/tui.ts";
@@ -90,6 +90,25 @@ test("a guest is offered the changelog and sees the releases newest first", asyn
9090 expect(text.indexOf("November 2026")).toBeLessThan(text.indexOf("0.2.0"));
9191 });
9292
93 test("c on a release opens the commits it holds: the previous release's commit to its own, and Enter opens one", async () => {
94 const terminal = headlessTerminal(120, 30);
95 const { app: tui, session } = createForgeApp(app, guest, { terminal, exitHooks: false });
96 tui.start();
97 tui.ctx.push(changelogScreen(session, tui.ctx));
98 await settleApp(tui);
99 terminal.feed("c");
100 await settleApp(tui);
101 const listed = tui.screen.toText();
102 terminal.feed("\r");
103 await settleApp(tui);
104 const opened = tui.screen.toText();
105 tui.stop?.();
106 expect(listed).toContain("Changelog › 0.2.0 commits");
107 expect(listed).toContain("Release 0.2.0: Newer thing (#2)");
108 expect(listed).not.toContain("Release 0.1.0: Older (#1)");
109 expect(opened).not.toBe(listed);
110 });
111
93112 test("a private forge repository leaves the terminal's screen empty", async () => {
94113 app.db.run("UPDATE repo SET visibility = 'private' WHERE name = 'forge'");
95114 const terminal = headlessTerminal(120, 30);
@@ -144,11 +163,11 @@ test("the terminal tells pulls in chapters, open first, then between chapters; w
144163 expect(lines.filter((l) => l.pull !== undefined).map((l) => l.pull)).toEqual([4, 3, 1, 2]);
145164 // Narrowed, a heading with no pull left goes.
146165 expect(chapterLines(groups, (l) => l.number === 1, true).map((l) => l.row.title)).toEqual(["Chapter v1", " #1 Pull 1"]);
147 expect(changelogLines([{ version: "0.4.0", date: "2026-10-30T00:00:00Z", pulls: [] }]).map((l) => l.row.title)).toEqual(["October 2026", "0.4.0"]);
166 expect(changelogLines([{ version: "0.4.0", date: "2026-10-30T00:00:00Z", pulls: [], oid: "a".repeat(40) }]).map((l) => l.row.title)).toEqual(["October 2026", "0.4.0"]);
148167 });
149168
150169 test("releases sit under a month heading line, newest first, one per month; a heading is no release", () => {
151 const e = (version: string, date: string) => ({ version, date, pulls: [] });
170 const e = (version: string, date: string) => ({ version, date, pulls: [], oid: "a".repeat(40) });
152171 const lines = changelogLines([e("0.6.0", "2026-11-10T00:00:00Z"), e("0.5.0", "2026-11-02T00:00:00Z"), e("0.4.0", "2026-10-30T00:00:00Z"), e("0.1.0", "2025-12-31T00:00:00Z")]);
153172 expect(lines.map((l) => l.row.title)).toEqual(["November 2026", "0.6.0", "0.5.0", "October 2026", "0.4.0", "December 2025", "0.1.0"]);
154173 expect(lines[0]!.row.meta).toContain("2 releases");
@@ -156,3 +175,12 @@ test("releases sit under a month heading line, newest first, one per month; a he
156175 expect(lines.filter((l) => l.entry === undefined).length).toBe(3);
157176 expect(changelogLines([])).toEqual([]);
158177 });
178
179 test("a release row in the terminal names the commit range it holds, as the page does", () => {
180 const a = "a".repeat(40);
181 const b = "b".repeat(40);
182 const rows = changelogRows([{ version: "0.2.0", date: "2026-11-01T00:00:00Z", pulls: [], oid: b, previous: a }, { version: "0.1.0", date: "2026-10-01T00:00:00Z", pulls: [], oid: a }]);
183 expect(rows[0]!.meta).toContain("aaaaaaa…bbbbbbb");
184 expect(rows[1]!.meta).toContain("aaaaaaa");
185 expect(rows[1]!.meta).not.toContain("…");
186 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs