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

A fork's page says in one line how many commits it is behind its upstream and links the update #13563

Merged opened this

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

Merged

scout/forge:scout/13524-a-fork-s-page-says-in-one-line-how-many → main 7 commits fork 5 threads · 5 unresolved

  • Merged. scout/13524-a-fork-s-page-says-in-one-line-how-many was merged into main as 70e4e7f.

Review

Sign in to review this change.
7 files changed +207 −30
docs/features/README.md +1
@@ -21,6 +21,7 @@ Read with the guide page [What a forge is](../guide-what-a-forge-is.md).
2121 - [Empty lists](empty-words.md)
2222 - [An app with no description says its README](readme-description.md)
2323 - [Arcade carts](arcade-carts.md)
24 - [How far behind a followed fork is](fork-behind.md)
2425 - [Changelog](changelog.md)
2526 - [/docs](docs-link.md)
2627 - [Engine shape](engine-shape.md)
docs/features/fork-behind.md added +15
@@ -0,0 +1,15 @@
1 # How far behind a followed fork is
2
3 Under the head of a followed fork's page one line says `N commits behind
4 <upstream>` or `up to date`, with when it was checked. It is read from the
5 check the follow already stored, never from git on the request.
6
7 - An admin of the repository also gets **Update** (runs the check now) and a
8 `details` link to the upstream settings.
9 - Other readers see the words and no action. A spawned fork whose private
10 parent a reader cannot read shows them no line.
11 - A severed following, an unchecked one or a failed check shows no line; a
12 conflict says what to resolve.
13 - In the terminal, the repository's About card shows the same words in its
14 `behind` row to the same readers, a private parent hidden the same way;
15 an admin's row adds `u updates`. Both doors read one helper, `behindFor`.
src/actions/upstream_follow.ts +26 −1
@@ -35,7 +35,7 @@ import { queueAgentRun } from "../crew/dispatch.ts";
3535 import { pickBuilder } from "../crew/route.ts";
3636 import { getOriginFor } from "../core/origins.ts";
3737 import { pullForBranch, retargetPull } from "../core/pulls.ts";
38 import { canAdmin, canWrite, getRepoById, type Repo } from "../core/repos.ts";
38 import { canAdmin, canWrite, forkParentFor, getRepoById, type Repo } from "../core/repos.ts";
3939 import { storageStale } from "../core/storage.ts";
4040 import {
4141 getFollow,
@@ -929,6 +929,31 @@ export function behindWords(follow: UpstreamFollow): { text: string; conflict: b
929929 };
930930 }
931931
932 /**
933 * The behind line both doors show, page and terminal: the behind or conflict
934 * words, or "up to date" when the last check found the repository level.
935 * Every reader of the repository gets it; `admin` says whether the viewer may
936 * also take the update. Null when following nothing, severed, unchecked, or
937 * failed for another reason, and null to a non-admin when the following came
938 * from a parent they cannot read, so a private parent is never named.
939 */
940 export function behindFor(
941 db: Database,
942 repo: Repo,
943 viewer: User | undefined,
944 ): { checkedAt: string; text: string; conflict: boolean; admin: boolean } | null {
945 const follow = getFollow(db, repo.id);
946 if (follow === undefined || !follow.enabled || follow.checkedAt === null) return null;
947 const admin = viewer !== undefined && canAdmin(db, repo, viewer);
948 const parentHidden = follow.via === "parent" && forkParentFor(db, repo, viewer) === undefined;
949 if (!admin && parentHidden) return null;
950 const words = behindWords(follow);
951 const checkedAt = follow.checkedAt;
952 if (words !== null) return { checkedAt, ...words, admin };
953 const level = follow.error === "" && follow.behind === 0;
954 return level ? { checkedAt, text: "up to date", conflict: false, admin } : null;
955 }
956
932957 /** HH:MM, UTC. */
933958 export const clockWords = (iso: string): string => {
934959 const at = new Date(iso);
src/tui/screens/about.ts +15 −1
@@ -48,6 +48,7 @@ import {
4848 checkedWords,
4949 checkUpstreamNow,
5050 FOLLOW_REFUSALS,
51 behindFor,
5152 behindWords,
5253 conflictWaitingWords,
5354 openConflictIssue,
@@ -150,6 +151,7 @@ export function aboutScreen(
150151 ...paceRows(f, repo),
151152 ...trailRows(f, repo),
152153 ...upstreamRows(f, repo),
154 ...behindRows(f, repo),
153155 ...offerRows(offered),
154156 // The phase and git's failure line are the Danger zone card's, an
155157 // admin's: shown here behind the same gate as `x`.
@@ -735,6 +737,19 @@ export function offerRows(offer: UpstreamOffer | null): [string, string][] {
735737 ];
736738 }
737739
740 /**
741 * The behind row, as the page's behind line has it (`behindFor`): every reader
742 * of the repository, a private parent never named; the `u` hint is an
743 * admin's.
744 */
745 export function behindRows(f: Session, repo: Repo | undefined): [string, string][] {
746 if (repo === undefined || repo.origin !== null) return [];
747 const behind = behindFor(f.db, repo, f.user);
748 if (behind === null) return [];
749 const hint = behind.admin && behind.text !== "up to date";
750 return [["behind", hint ? `${behind.text} · u updates` : behind.text]];
751 }
752
738753 /**
739754 * The upstream row, as the web About line has it: for an admin only, with
740755 * the address, branch and last check while following is on, and "off" when
@@ -758,7 +773,6 @@ export function upstreamRows(
758773 "upstream",
759774 `${upstreamLabel(follow.url)} ${follow.branch}${checked} · ${standing(follow)}`,
760775 ],
761 ...(behind === null ? [] : [["behind", `${behind.text} · u updates`] as [string, string]]),
762776 ...(waiting === undefined ? [] : [["", conflictWaitingWords(waiting)] as [string, string]]),
763777 ...listChecks(f.db, repo.id).map((c): [string, string] => ["", checkLine(c, ago(c.at))]),
764778 ];
src/web/pages/upstream-follow.ts +20 −18
@@ -6,7 +6,7 @@
66 */
77
88 import {
9 behindWords,
9 behindFor,
1010 checkedWords,
1111 checkLine,
1212 checkUpstreamNow,
@@ -90,31 +90,33 @@ export function followingLine(ctx: Ctx, repo: Repo): Html | null {
9090 </p>`;
9191 }
9292
93 /** The admin's Update form and the link to the settings card. */
94 const updateAction = (base: string): Html => html`<form method="post" action="${base}/settings/upstream/check" class="inline">
95 <input type="hidden" name="back" value="${base}" />
96 ${btn("Update", { size: "sm", icon: "sync" })}
97 </form>
98 <a href="${base}/settings#upstream">details</a>`;
99
93100 /**
outdated

Doc comment above says 'Admins only' and 'null when level'; both are now false. Update it. (Principle 8: plain, true words.)

94 * Under the head of a followed repository: how far behind the last check
95 * found it, or that it conflicts. Read from the stored check, never git;
96 * null when level, unchecked, failed for another reason, or following
97 * nothing. Admins only, like the page it links to.
101 * Under the head of a followed repository: `behindFor`'s words, read from the
102 * stored check, never git. Only an admin gets the Update action and the links
103 * to settings or the conflict issue.
98104 */
outdated

Mixed || and && without parentheses, and a very long line. Parenthesise the error test and wrap it.

99105 export function behindLine(ctx: Ctx, repo: Repo): Html | null {
outdated

This private-parent hiding is the data-leak guard for non-admins and has no test. Add one in test/fork-behind.test.ts for a spawned fork with a private parent viewed by a stranger.

100 const follow = followShown(ctx.app, repo, ctx.auth.user);
101 const words = follow === undefined ? null : behindWords(follow);
102 if (follow === undefined || words === null || follow.checkedAt === null) return null;
106 const behind = behindFor(ctx.app.db, repo, ctx.auth.user);
107 if (behind === null) return null;
108 const { checkedAt, text, conflict, admin } = behind;
103109 const base = repoBase(repo);
104 const waiting = words.conflict ? openConflictIssue(ctx.app.db, repo.id) : undefined;
110 const waiting = conflict ? openConflictIssue(ctx.app.db, repo.id) : undefined;
105111 return html`<div class="small muted" data-behind-upstream>
106112 ${icon("sync")}
107 ${words.conflict
113 ${conflict && admin
108114 ? waiting === undefined
109 ? html`<a href="${base}/settings#upstream">${words.text}</a>`
115 ? html`<a href="${base}/settings#upstream">${text}</a>`
110116 : html`<a href="${base}/issues/${waiting.number}">${conflictWaitingWords(waiting)}</a>`
outdated

The 'level' rule (checkedAt set, no error, behind 0) lives here and again in about.ts. One function returning the words, used by both doors, so they cannot drift.

111 : html`${words.text} ·`}
112 checked ${timeAgo(follow.checkedAt)}
113 <form method="post" action="${base}/settings/upstream/check" class="inline">
114 <input type="hidden" name="back" value="${base}" />
115 ${btn("Update", { size: "sm", icon: "sync" })}
116 </form>
117 <a href="${base}/settings#upstream">details</a>
117 : html`${text} ·`}
118 checked ${timeAgo(checkedAt)}
119 ${when(admin, () => updateAction(base))}
118120 </div>`;
119121 }
120122
test/fork-behind.test.ts added +118
@@ -0,0 +1,118 @@
1 /**
2 * A followed fork's page says "N commits behind <upstream>" or "up to date" from the stored check,
3 * and links the update only to who may take it.
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, forkRepo } from "../src/actions/repos.ts";
10 import { createApp, type App } from "../src/app.ts";
11 import { noteCheck, putFollow } from "../src/core/upstream_follow.ts";
12 import { createUser } from "../src/core/users.ts";
13 import { serve, type Servers } from "../src/http/server.ts";
14 import { getRepo } from "../src/core/repos.ts";
15 import type { User } from "../src/core/users.ts";
16 import { behindRows } from "../src/tui/screens/about.ts";
17 import type { Session } from "../src/tui/session.ts";
18 import { quietLogs } from "./helpers/globals.ts";
19
20 quietLogs();
21 let dir: string;
22 let app: App;
23 let servers: Servers;
24 let cookie: string;
25 let amy: User;
26 let bob: User;
27
28 const mkRepo = async (user: NonNullable<Parameters<typeof createRepo>[1]>, name: string, behind: number, enabled = true) => {
29 const made = await createRepo(app, user, { name, visibility: "public" });
30 if (!made.ok) throw new Error(String(made.error));
31 await commitToBranch(app, user, made.value, { message: "first", files: [{ path: "a.txt", content: "a\n" }] });
32 putFollow(app.db, { repoId: made.value.id, url: "https://github.com/trevato/forge.git", branch: "main", enabled, byId: user.id, originId: "" });
33 noteCheck(app.db, made.value.id, { at: new Date().toISOString(), behind, error: "" });
34 };
35 const repoId = (name: string): string =>
36 (app.db.query("SELECT id FROM repo WHERE name = ?").get(name) as { id: string }).id;
37 const page = async (name: string, headers: Record<string, string> = {}) =>
38 (await (await fetch(`${servers.url}/amy/${name}`, { headers })).text()).match(/<div[^>]*data-behind-upstream[\s\S]*?<\/div>/)?.[0] ?? "";
39
40 beforeAll(async () => {
41 dir = await mkdtemp(join(tmpdir(), "forge-fork-behind-"));
42 app = createApp({ dataDir: dir, port: 0, host: "forge.test" });
43 servers = await serve(app);
44 const u = await createUser(app.db, { origin: "seed", trusted: true, username: "amy", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
45 if (!u.ok) throw new Error(u.error);
46 amy = u.value;
47 const b = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" });
48 if (!b.ok) throw new Error(b.error);
49 bob = b.value;
50 await mkRepo(u.value, "behind", 1);
51 await mkRepo(u.value, "level", 0);
52 await mkRepo(u.value, "severed", 4, false);
53 await mkRepo(u.value, "conflicted", 2);
54 noteCheck(app.db, repoId("conflicted"), { at: new Date().toISOString(), behind: 2, error: "conflict", files: 3 });
55 // A public fork whose parent is private: the following came from the parent.
56 const parent = await createRepo(app, u.value, { name: "secret", visibility: "public" });
57 if (!parent.ok) throw new Error(String(parent.error));
58 await commitToBranch(app, u.value, parent.value, { message: "first", files: [{ path: "a.txt", content: "a\n" }] });
59 const fork = await forkRepo(app, u.value, parent.value, "spawned", { visibility: "public" });
60 if (!fork.ok) throw new Error(String(fork.error));
61 putFollow(app.db, { repoId: fork.value.id, url: "https://github.com/trevato/forge.git", branch: "main", enabled: true, byId: u.value.id, originId: "", via: "parent" });
62 noteCheck(app.db, fork.value.id, { at: new Date().toISOString(), behind: 5, error: "" });
63 app.db.query("UPDATE repo SET visibility = 'private' WHERE id = ?").run(parent.value.id);
64 const r = await fetch(`${servers.url}/signin`, { method: "POST", body: new URLSearchParams({ username: "amy", password: "a-good-passphrase" }), redirect: "manual" });
65 cookie = (r.headers.get("set-cookie") ?? "").split(";")[0]!;
66 });
67 afterAll(async () => {
68 await servers.stop();
69 await rm(dir, { recursive: true, force: true });
70 });
71
72 test("behind: singular count and the update action for the admin", async () => {
73 const line = await page("behind", { cookie });
74 expect(line).toContain("1 commit behind trevato/forge");
75 expect(line).toContain('action="/amy/behind/settings/upstream/check"');
76 });
77
78 test("level: says up to date", async () => {
79 expect(await page("level", { cookie })).toContain("up to date");
80 });
81
82 test("a reader who may not update sees the words and no action", async () => {
83 const line = await page("behind");
84 expect(line).toContain("1 commit behind trevato/forge");
85 expect(line).not.toContain("<form");
86 });
87
88 test("severed: no line", async () => {
89 expect(await page("severed", { cookie })).toBe("");
90 });
91
92 test("a spawned fork of a private parent shows a stranger no line, and its owner the line", async () => {
93 expect(await page("spawned")).toBe("");
94 expect(await page("spawned", { cookie })).toContain("5 commits behind trevato/forge");
95 });
96
97 test("a conflict shows a reader its words without the settings or issue link", async () => {
98 const line = await page("conflicted");
99 expect(line).toContain("conflicts with trevato/forge: resolve");
100 expect(line).not.toContain("<a ");
101 expect(line).not.toContain("<form");
102 expect(await page("conflicted", { cookie })).toContain("/amy/conflicted/settings#upstream");
103 });
104
105 const terminalRows = (name: string, user: User | undefined) =>
106 behindRows({ db: app.db, user } as unknown as Session, getRepo(app.db, "amy", name)!);
107
108 test("the terminal shows a reader who is not an admin the behind words without the u hint", () => {
109 expect(terminalRows("behind", bob)).toEqual([["behind", "1 commit behind trevato/forge"]]);
110 expect(terminalRows("behind", undefined)).toEqual([["behind", "1 commit behind trevato/forge"]]);
111 expect(terminalRows("behind", amy)).toEqual([["behind", "1 commit behind trevato/forge · u updates"]]);
112 expect(terminalRows("conflicted", bob)).toEqual([["behind", "conflicts with trevato/forge: resolve"]]);
113 });
114
115 test("the terminal shows a stranger no behind row for a spawned fork of a private parent", () => {
116 expect(terminalRows("spawned", bob)).toEqual([]);
117 expect(terminalRows("spawned", amy)).toEqual([["behind", "5 commits behind trevato/forge · u updates"]]);
118 });
test/repo-behind-line.test.ts +12 −10
@@ -12,7 +12,7 @@ import { createUser, type User } from "../src/core/users.ts";
1212 import { serve, type Servers } from "../src/http/server.ts";
1313 import { getRepo } from "../src/core/repos.ts";
1414 import type { Session } from "../src/tui/session.ts";
15 import { upstreamRows } from "../src/tui/screens/about.ts";
15 import { behindRows, upstreamRows } from "../src/tui/screens/about.ts";
1616 import { quietLogs } from "./helpers/globals.ts";
1717
1818 quietLogs();
@@ -97,8 +97,10 @@ test("behind: the count, the upstream, the age, linking to the settings", async
9797 expect(line).toMatch(/<button[^>]*type="submit"[\s\S]*Update/);
9898 });
9999
100 test("level: no line", async () => {
101 expect((await home("level")).html).not.toContain("data-behind-upstream");
100 test("level: says up to date", async () => {
101 const html = (await home("level")).html;
102 expect(html).toContain("data-behind-upstream");
103 expect(html.match(/<div[^>]*data-behind-upstream[\s\S]*?<\/div>/)![0]).toContain("up to date");
102104 });
103105
104106 test("conflicted: says what to do", async () => {
@@ -107,13 +109,13 @@ test("conflicted: says what to do", async () => {
107109 expect(html).not.toContain("commits behind");
108110 });
109111
110 test("not a fork: no line, and a stranger sees none", async () => {
112 test("not a fork: no line; a stranger sees the line but no action", async () => {
111113 expect((await home("plain")).html).not.toContain("data-behind-upstream");
112114 const r = await fetch(`${servers.url}/amy/behind`);
113 expect(await r.text()).not.toContain("data-behind-upstream");
115 expect(await r.text()).toContain("12 commits behind");
114116 });
115117
116 test("a signed-in non-admin who can read the repository sees no line and no button", async () => {
118 test("a signed-in non-admin who can read the repository sees the line and no button", async () => {
117119 const made = await createUser(app.db, {
118120 origin: "seed",
119121 trusted: true,
@@ -129,7 +131,7 @@ test("a signed-in non-admin who can read the repository sees no line and no butt
129131 });
130132 const bob = (r.headers.get("set-cookie") ?? "").split(";")[0]!;
131133 const { html } = await home("behind", bob);
132 expect(html).not.toContain("data-behind-upstream");
134 expect(html).toContain("12 commits behind trevato/forge");
133135 expect(html).not.toContain("settings/upstream/check");
134136 });
135137
@@ -145,18 +147,18 @@ test("Update runs the check and comes back to the home; a foreign back goes to s
145147 expect((await post("https://evil.example/")).headers.get("location")).toBe("/amy/behind/settings#upstream");
146148 });
147149
148 test("the terminal's About rows carry the same behind words, only while behind or conflicting", () => {
150 test("the terminal's About rows carry the same behind words, and up to date when level", () => {
149151 const rows = (name: string) => {
150152 const repo = getRepo(app.db, "amy", name)!;
151153 // The Update test above ran a real check; put the stored one back.
152154 const stored = { behind: { behind: 12, error: "" }, conflicted: { behind: 3, error: "conflict" }, level: { behind: 0, error: "" } }[name]!;
153155 noteCheck(app.db, repo.id, { at: new Date().toISOString(), ...stored });
154156 const session = { db: app.db, user } as unknown as Session;
155 return upstreamRows(session, repo).filter(([k]) => k === "behind");
157 return behindRows(session, repo);
156158 };
157159 expect(rows("behind")).toEqual([["behind", "12 commits behind trevato/forge · u updates"]]);
158160 expect(rows("conflicted")).toEqual([["behind", "conflicts with trevato/forge: resolve · u updates"]]);
159 expect(rows("level")).toEqual([]);
161 expect(rows("level")).toEqual([["behind", "up to date"]]);
160162 });
161163
162164 test("the terminal's About rows name the open conflict issue, by the facts", () => {

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs