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

A repository's forks page draws the tree: each fork's own forks beneath it, two levels deep #6292

Parked opened this
Closed without merging

scout/forge:scout/6250-a-repository-s-forks-page-draws-the-tree → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
3 files changed +162 −2
src/core/repos.ts +62
@@ -626,6 +626,68 @@ export function visibleForks(
626626 return listForks(db, repoId).filter((fork) => canRead(db, fork, viewer));
627627 }
628628
629 /** A fork the viewer may see, its visible forks beneath it, and how many lie deeper. */
630 export interface ForkNode {
631 readonly repo: Repo;
632 readonly forks: readonly ForkNode[];
633 /** Visible forks below the listed levels (counted on the second level). */
634 readonly deeper: number;
635 }
636
637 /** The deepest generation the tree counts past what it lists: one query a level. */
638 const FORK_TREE_REACH = 8;
639
640 const forksOfMany = (db: Database, ids: readonly string[]): Repo[] =>
641 ids.length === 0
642 ? []
643 : db
644 .query<RepoRow, string[]>(
645 `${SELECT} WHERE repo.fork_parent_id IN (${ids.map(() => "?").join(",")}) ORDER BY repo.id`,
646 )
647 .all(...ids)
648 .map(toRepo);
649
650 /**
651 * The visible forks of a repository, each with its own visible forks
652 * (two levels listed) and a count of what lies below those. One query per
653 * level; a fork the viewer cannot read hides itself and everything under it.
654 */
655 export function forkTree(
656 db: Database,
657 repoId: string,
658 viewer: User | undefined,
659 ): ForkNode[] {
660 const seen = (rs: Repo[]) => rs.filter((r) => canRead(db, r, viewer));
661 const first = seen(listForks(db, repoId));
662 const second = seen(forksOfMany(db, first.map((r) => r.id)));
663 const deeper = new Map<string, number>();
664 const rootOf = new Map(second.map((r) => [r.id, r.id]));
665 let level = second;
666 for (let d = 3; d <= FORK_TREE_REACH && level.length > 0; d++) {
667 level = seen(forksOfMany(db, level.map((r) => r.id)));
668 for (const r of level) {
669 const root = rootOf.get(r.forkParentId ?? "") as string;
670 rootOf.set(r.id, root);
671 deeper.set(root, (deeper.get(root) ?? 0) + 1);
672 }
673 }
674 const kids = new Map<string, Repo[]>();
675 for (const r of second) {
676 const k = kids.get(r.forkParentId ?? "") ?? [];
677 k.push(r);
678 kids.set(r.forkParentId ?? "", k);
679 }
680 return first.map((r) => ({
681 repo: r,
682 forks: (kids.get(r.id) ?? []).map((c) => ({
683 repo: c,
684 forks: [],
685 deeper: deeper.get(c.id) ?? 0,
686 })),
687 deeper: 0,
688 }));
689 }
690
629691 export function getRepo(
630692 db: Database,
631693 ownerName: string,
src/web/pages/repo.ts +25 −2
@@ -38,6 +38,8 @@ import { pinRepo, syncRepoNow, unpinRepo } from "../../actions/origins.ts";
3838 import {
3939 canAdmin,
4040 forkParentFor,
41 forkTree,
42 type ForkNode,
4143 visibleForks,
4244 } from "../../core/repos.ts";
4345 import { isSafeRef, isSafeTreePath } from "../../git/guard.ts";
@@ -131,6 +133,9 @@ export async function forksPage(ctx: Ctx): Promise<Response> {
131133 );
132134 notePhase(ctx.request, "forks", performance.now() - t);
133135 t = performance.now();
136 const tree = forkTree(ctx.app.db, repo.id, ctx.auth.user);
137 notePhase(ctx.request, "fork-tree", performance.now() - t);
138 t = performance.now();
134139 // The whole family, from the oldest ancestor this viewer may see: who
135140 // follows whom, and where each stands against the one it follows.
136141 const lineage = await lineageOf(ctx.app, repo, (r) =>
@@ -151,7 +156,7 @@ export async function forksPage(ctx: Ctx): Promise<Response> {
151156 title: "No forks yet",
152157 note: "A fork is a copy under another name that can propose changes back here, and follows this one until it has work of its own.",
153158 })
154 : html`${forkRanking(ranked)}
159 : html`${forkRanking(ranked, new Map(tree.map((n) => [n.repo.id, n])))}
155160 <h3 class="mt">The family, by who follows whom</h3>
156161 ${lineageCard(lineage, repo.id)}`}`;
157162 const res = page({
@@ -167,9 +172,27 @@ export async function forksPage(ctx: Ctx): Promise<Response> {
167172 * The forks with work to offer, best first, each linking to the compare
168173 * view that proposes it upstream; then those with nothing new, counted.
169174 */
170 function forkRanking(ranked: ForkRanking): Html {
175 function forkRanking(
176 ranked: ForkRanking,
177 tree: ReadonlyMap<string, ForkNode>,
178 ): Html {
179 const below = (n: ForkNode): Html =>
180 row({
181 lead: icon("fork"),
182 title: html`<a href="/${n.repo.ownerName}/${n.repo.name}"
183 >${n.repo.ownerName}/${n.repo.name}</a
184 >`,
185 ...(n.deeper === 0
186 ? {}
187 : {
188 meta: html`<a href="/${n.repo.ownerName}/${n.repo.name}/forks"
189 >and ${n.deeper} more fork${n.deeper === 1 ? "" : "s"} below</a
190 >`,
191 }),
192 });
171193 const line = (f: RankedFork, offer: boolean): Html =>
172194 row({
195 children: (tree.get(f.fork.id)?.forks ?? []).map(below),
173196 lead: icon("fork"),
174197 title: html`<a href="/${f.fork.ownerName}/${f.fork.name}"
175198 >${f.fork.ownerName}/${f.fork.name}</a
test/fork-tree.test.ts added +75
@@ -0,0 +1,75 @@
1 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2 import { mkdtemp, rm } from "node:fs/promises";
3 import { tmpdir } from "node:os";
4 import { join } from "node:path";
5 import { createRepo, forkRepo } from "../src/actions/repos.ts";
6 import { forkTree, getRepo } from "../src/core/repos.ts";
7 import { createApp, type App } from "../src/app.ts";
8 import { createUser, type User } from "../src/core/users.ts";
9 import { serve, type Servers } from "../src/http/server.ts";
10 import { promote } from "./helpers/members.ts";
11
12 const must = <T>(r: { ok: true; value: T } | { ok: false; error: unknown }): T => {
13 if (!r.ok) throw new Error(JSON.stringify(r.error));
14 return r.value;
15 };
16
17 describe("the forks page draws the tree", () => {
18 let dataDir: string;
19 let app: App;
20 let servers: Servers;
21 const users: Record<string, User> = {};
22
23 beforeAll(async () => {
24 dataDir = await mkdtemp(join(tmpdir(), "forge-fork-tree-"));
25 app = createApp({ dataDir, port: 0 });
26 servers = await serve(app);
27 for (const name of ["alice", "bob", "carol", "dan", "erin", "fay"]) {
28 users[name] = must(
29 await createUser(app.db, {
30 origin: "seed",
31 trusted: true,
32 username: name,
33 email: `${name}@f.dev`,
34 password: "a-good-passphrase",
35 adminIfFirst: name === "alice",
36 }),
37 );
38 promote(app.db, users[name]!);
39 }
40 const upstream = must(await createRepo(app, users["alice"]!, { name: "app", visibility: "public" }));
41 const bob = must(await forkRepo(app, users["bob"]!, upstream));
42 must(await forkRepo(app, users["carol"]!, upstream));
43 const dan = must(await forkRepo(app, users["dan"]!, bob));
44 must(await forkRepo(app, users["erin"]!, dan));
45 must(await forkRepo(app, users["fay"]!, dan, "secret", { visibility: "private" }));
46 }, 60_000);
47
48 afterAll(async () => {
49 servers.stop();
50 app.close();
51 await rm(dataDir, { recursive: true, force: true });
52 });
53
54 test("a fork of a fork is nested under its parent; deeper forks are a count", async () => {
55 const text = await (await fetch(`${servers.url}/alice/app/forks`, { headers: { cookie: "forge_mode=dev" } })).text();
56 const at = (s: string) => text.indexOf(s);
57 for (const who of ["bob", "carol", "dan"]) expect(at(`href="/${who}/app"`)).toBeGreaterThan(-1);
58 const ul = at('<ul class="row-children">');
59 expect(ul).toBeGreaterThan(-1);
60 expect(at('href="/dan/app"')).toBeGreaterThan(ul);
61 expect(text).toContain('href="/dan/app/forks"');
62 expect(text).toContain("and 1 more fork below");
63 });
64
65 test("a private fork is never named or counted to someone who cannot read it", async () => {
66 const text = await (await fetch(`${servers.url}/alice/app/forks`, { headers: { cookie: "forge_mode=dev" } })).text();
67 expect(text).not.toContain("fay/secret");
68 expect(text).not.toContain("and 2 more");
69 const alice = getRepo(app.db, "alice", "app")!;
70 const dan = forkTree(app.db, alice.id, undefined).find((n) => n.repo.ownerName === "bob")!.forks[0]!;
71 expect(dan.deeper).toBe(1);
72 const seenByFay = forkTree(app.db, alice.id, users["fay"]!).find((n) => n.repo.ownerName === "bob")!.forks[0]!;
73 expect(seenByFay.deeper).toBe(2);
74 });
75 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs