Public: anyone can read this; the crew can change it.
A fork's owner offers one commit upward from the fork's page, and the offer appears on the upstream as a pull #13698
Check · Review · Land · Live done — Landed and live in production.
mason/forge:mason/13671-a-fork-s-owner-offers-one-commit-upward → main 11 commits fork 1 thread · 1 unresolved
9 files
changed +611
−6
docs/features/README.md +1
| @@ -408,6 +408,7 @@ Read with the guide page [Agents: MCP, git, or the terminal](../guide-agents.md) | ||
| 408 | 408 | - [](conversation-fence.md) |
| 409 | 409 | - [](muse-test.md) |
| 410 | 410 | - [](offer.md) |
| 411 | - [](offer-commit-upstream.md) | |
| 411 | 412 | - [](report-form.md) |
| 412 | 413 | - [](report-receipt.md) |
| 413 | 414 | - [](team-effective-share.md) |
docs/features/offer-commit-upstream.md added +34
| @@ -0,0 +1,34 @@ | ||
| 1 | # Offer one commit upstream | |
| 2 | ||
| 3 | A fork's writer can send a single commit of the fork to its parent as a pull. | |
| 4 | ||
| 5 | ## On the web | |
| 6 | ||
| 7 | Open a commit on your fork (`/<you>/<fork>/commit/<oid>`) and press **Offer upstream**. The | |
| 8 | button shows only to someone who can write to a fork. The forge cuts the branch `offer/<first 12 | |
| 9 | hex of the commit>` in the fork at that commit, opens a pull on the parent from it, and sends you | |
| 10 | to the pull. The pull's title is the commit's subject; its body names the fork and the commit and | |
| 11 | says what the fork's check made of it: passed, failed, still running, superseded, or none ran. | |
| 12 | ||
| 13 | The form works without JavaScript. The address must carry the full commit id: anything else | |
| 14 | answers 404 before git is asked. | |
| 15 | ||
| 16 | ## In the terminal | |
| 17 | ||
| 18 | Open the commit in the history screen (`enter` on a log row) of a fork and press `o`. The toast | |
| 19 | names the pull (`owner/name#N`) or says why not. The pull opens through the same action as the | |
| 20 | page, so anyone watching the parent's pulls on the web sees it appear. | |
| 21 | ||
| 22 | ## Refusals, in words | |
| 23 | ||
| 24 | `OFFER_COMMIT_WORDS` in `src/actions/offer_commit.ts` says each: not signed in, cannot write to | |
| 25 | the fork, not a fork, upstream archived, no such commit in the fork, already offered in an open | |
| 26 | pull, and the upstream did not take the offer. | |
| 27 | ||
| 28 | An upstream that does not accept outside pulls is not yet a refusal of its own; only an archived | |
| 29 | one is. | |
| 30 | ||
| 31 | ## Branches | |
| 32 | ||
| 33 | If the pull fails to open, the branch this offer cut is deleted. After a pull is closed the | |
| 34 | `offer/` branch stays in the fork, and the same commit can be offered again on it. |
src/actions/offer_commit.ts added +114
| @@ -0,0 +1,114 @@ | ||
| 1 | /** | |
| 2 | * One commit of a fork, offered to its parent (#13671): the branch is cut at | |
| 3 | * that commit in the fork and a pull is opened on the parent from it. The | |
| 4 | * pull's body names the fork and carries the fork's check verdict for the | |
| 5 | * commit as it stood when offered. Gated like any pull from a fork — the | |
| 6 | * actor writes to the fork and reads the parent — with the refusals said in | |
| 7 | * words (`OFFER_COMMIT_WORDS`) for the page and the terminal alike. | |
| 8 | */ | |
| 9 | ||
| 10 | import type { App } from "../app.ts"; | |
| 11 | import type { CommitCheck } from "../checks/commit_check.ts"; | |
| 12 | import { openPullFromHead, type Pull } from "../core/pulls.ts"; | |
| 13 | import { canRead, getRepoById, type Repo } from "../core/repos.ts"; | |
| 14 | import type { User } from "../core/users.ts"; | |
| 15 | import { isSafeOid } from "../git/guard.ts"; | |
| 16 | import { resolveOid } from "../git/merge.ts"; | |
| 17 | import { repoDir } from "../git/repos.ts"; | |
| 18 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 19 | import { requireWriter } from "./access.ts"; | |
| 20 | import { createBranch, deleteBranch } from "./branches.ts"; | |
| 21 | import { openPull } from "./pulls.ts"; | |
| 22 | import { checkOfCommit } from "./runs.ts"; | |
| 23 | ||
| 24 | export type OfferCommitRefusal = | |
| 25 | | "not_found" | |
| 26 | | "unauthorized" | |
| 27 | | "forbidden" | |
| 28 | | "not_a_fork" | |
| 29 | | "upstream_archived" | |
| 30 | | "no_such_commit" | |
| 31 | | "already_offered" | |
| 32 | | "not_opened"; | |
| 33 | ||
| 34 | /** Why each refusal, in words that say what to do. */ | |
| 35 | export const OFFER_COMMIT_WORDS: Readonly<Record<OfferCommitRefusal, string>> = { | |
| 36 | not_found: "That commit or its upstream cannot be found.", | |
| 37 | unauthorized: "Sign in to offer a commit upstream.", | |
| 38 | forbidden: "Only someone who can write to this fork may offer its commits upstream.", | |
| 39 | not_a_fork: "This repository is not a fork, so it has no upstream to offer to.", | |
| 40 | upstream_archived: "The upstream is archived and accepts no offers until it is unarchived.", | |
| 41 | no_such_commit: "That commit is not in this fork.", | |
| 42 | already_offered: "That commit is already offered upstream in an open pull.", | |
| 43 | not_opened: "The upstream did not take the offer. Try again from the pull form.", | |
| 44 | }; | |
| 45 | ||
| 46 | /** The fork's verdict on the commit, as one plain sentence for a pull body. */ | |
| 47 | export function verdictWords(check: CommitCheck | null): string { | |
| 48 | switch (check?.state) { | |
| 49 | case "ok": | |
| 50 | return "The fork's check passed on this commit."; | |
| 51 | case "failed": | |
| 52 | return "The fork's check failed on this commit."; | |
| 53 | case "pending": | |
| 54 | return "The fork's check on this commit is still running."; | |
| 55 | case "superseded": | |
| 56 | return "The fork's check on this commit was superseded and none will follow."; | |
| 57 | default: | |
| 58 | return "No check ran on this commit in the fork."; | |
| 59 | } | |
| 60 | } | |
| 61 | ||
| 62 | export interface CommitOffered { | |
| 63 | readonly pull: Pull; | |
| 64 | readonly parent: Repo; | |
| 65 | } | |
| 66 | ||
| 67 | /** The branch an offered commit travels on: named for the commit, cut in the fork. */ | |
| 68 | export const offerBranch = (oid: string): string => `offer/${oid.slice(0, 12)}`; | |
| 69 | ||
| 70 | export async function offerCommit( | |
| 71 | app: App, | |
| 72 | actor: User | undefined, | |
| 73 | fork: Repo, | |
| 74 | rev: string, | |
| 75 | subject: string, | |
| 76 | ): Promise<Result<CommitOffered, OfferCommitRefusal>> { | |
| 77 | const writer = requireWriter(app, actor, fork); | |
| 78 | if (!writer.ok) return writer; | |
| 79 | const parent = fork.forkParentId === null ? undefined : getRepoById(app.db, fork.forkParentId); | |
| 80 | if (parent === undefined) return err("not_a_fork"); | |
| 81 | if (!canRead(app.db, parent, writer.value)) return err("not_found"); | |
| 82 | if (parent.archivedAt !== null) return err("upstream_archived"); | |
| 83 | if (!isSafeOid(rev)) return err("no_such_commit"); | |
| 84 | const dir = repoDir(app.reposRoot, fork.ownerName, fork.name); | |
| 85 | const oid = await resolveOid(dir, rev); | |
| 86 | if (oid === undefined) return err("no_such_commit"); | |
| 87 | ||
| 88 | const branch = offerBranch(oid); | |
| 89 | if (openPullFromHead(app.db, parent.id, fork.id, branch) !== undefined) | |
| 90 | return err("already_offered"); | |
| 91 | const cut = await createBranch(app, writer.value, fork, { name: branch, from: oid }); | |
| 92 | if (!cut.ok && cut.error !== "exists") return err("not_opened"); | |
| 93 | ||
| 94 | const checked = await checkOfCommit(app, writer.value, fork, oid); | |
| 95 | const body = | |
| 96 | `Offered from ${fork.ownerName}/${fork.name}, a fork of this repository: ` + | |
| 97 | `commit ${oid.slice(0, 7)}.\n\n${verdictWords(checked.ok ? checked.value : null)}`; | |
| 98 | const pullTitle = | |
| 99 | subject.trim() === "" ? `Commit ${oid.slice(0, 7)} from ${fork.ownerName}/${fork.name}` : subject.trim(); | |
| 100 | const opened = await openPull(app, writer.value, parent, { | |
| 101 | title: pullTitle, | |
| 102 | body, | |
| 103 | baseBranch: parent.defaultBranch, | |
| 104 | headBranch: branch, | |
| 105 | headRepo: fork, | |
| 106 | }); | |
| 107 | if (!opened.ok) { | |
| 108 | // The branch exists only to carry this offer: a branch this call cut goes with the failure, | |
| 109 | // so the fork is not left with a ref nothing points at. One that was already there stays. | |
| 110 | if (cut.ok) await deleteBranch(app, writer.value, fork, branch); | |
| 111 | return err("not_opened"); | |
| 112 | } | |
| 113 | return ok({ pull: opened.value, parent }); | |
| 114 | } |
src/http/server.ts +2
| @@ -242,6 +242,7 @@ import { | ||
| 242 | 242 | branchDelete, |
| 243 | 243 | branchesPage, |
| 244 | 244 | } from "../web/pages/branches.ts"; |
| 245 | import { offerCommitPost } from "../web/pages/offer-upstream.ts"; | |
| 245 | 246 | import { iterationsPage, noteSubmit } from "../web/pages/iterations.ts"; |
| 246 | 247 | import { mainSubmit, registerSubmit, retireSubmit, valuesSubmit, variantBoardPage } from "../web/pages/app_variants.ts"; |
| 247 | 248 | import { buildsPage, deletePinSubmit, newBuildPage, pinBuildSubmit, previewBuildSubmit } from "../web/pages/builds.ts"; |
| @@ -1662,6 +1663,7 @@ export function buildRouter(): Router<Handler> { | ||
| 1662 | 1663 | router.add("GET", "/:owner/:name/waves", wavesPage); |
| 1663 | 1664 | router.add("GET", "/:owner/:name/waves/:version", wavePage); |
| 1664 | 1665 | router.add("POST", "/:owner/:name/branches", branchCreate); |
| 1666 | router.add("POST", "/:owner/:name/commit/:oid/offer", offerCommitPost); | |
| 1665 | 1667 | router.add("POST", "/:owner/:name/branches/:branch/delete", branchDelete); |
| 1666 | 1668 | |
| 1667 | 1669 | // Editing a file: the page, the one write, and the delete's own confirm. |
src/tui/screens/commits.ts +21 −2
| @@ -6,6 +6,7 @@ | ||
| 6 | 6 | * about having reached the end. |
| 7 | 7 | */ |
| 8 | 8 | |
| 9 | import { OFFER_COMMIT_WORDS, offerCommit } from "../../actions/offer_commit.ts"; | |
| 9 | 10 | import { checkOfCommit, verdictsOfCommits } from "../../actions/runs.ts"; |
| 10 | 11 | import type { CommitCheck } from "../../checks/commit_check.ts"; |
| 11 | 12 | import type { FileDiff } from "../../git/diff.ts"; |
| @@ -190,7 +191,10 @@ export function commitScreen( | ||
| 190 | 191 | let check: CommitCheck | null = null; |
| 191 | 192 | return { |
| 192 | 193 | title: commit.oid.slice(0, 8), |
| 193 | keys: view.keys, | |
| 194 | get keys() { | |
| 195 | const here = localRepo(src); | |
| 196 | return here?.forkParentId == null ? view.keys : [...view.keys, binding(["o"], "offer upstream")]; | |
| 197 | }, | |
| 194 | 198 | async load() { |
| 195 | 199 | const result = await src.commit(commit.oid); |
| 196 | 200 | view.setFiles(result.ok ? result.value.diff.files : []); |
| @@ -260,7 +264,22 @@ export function commitScreen( | ||
| 260 | 264 | ); |
| 261 | 265 | view.render(s, body!, c); |
| 262 | 266 | }, |
| 263 | key: (e) => view.key(e, ctx), | |
| 267 | key(e) { | |
| 268 | const here = localRepo(src); | |
| 269 | if (e.key === "o" && !e.ctrl && !e.alt && here?.forkParentId != null) { | |
| 270 | runAsync(ctx, async () => { | |
| 271 | const offered = await offerCommit(f.app, f.user, here, commit.oid, commit.subject); | |
| 272 | if (!offered.ok) ctx.toast(OFFER_COMMIT_WORDS[offered.error], "danger"); | |
| 273 | else | |
| 274 | ctx.toast( | |
| 275 | `Offered upstream as ${offered.value.parent.ownerName}/${offered.value.parent.name}#${offered.value.pull.number}.`, | |
| 276 | "success", | |
| 277 | ); | |
| 278 | }); | |
| 279 | return true; | |
| 280 | } | |
| 281 | return view.key(e, ctx); | |
| 282 | }, | |
| 264 | 283 | }; |
| 265 | 284 | } |
| 266 | 285 |
src/web/pages/commits.ts +5 −2
| @@ -25,6 +25,7 @@ import { hunkSyntax } from "../diff-syntax.ts"; | ||
| 25 | 25 | import { renderDiff, type SyntaxMap } from "../diff-view.ts"; |
| 26 | 26 | import { html, when, type Html } from "../html.ts"; |
| 27 | 27 | import { page } from "../layout.ts"; |
| 28 | import { offerCommitButton } from "./offer-upstream.ts"; | |
| 28 | 29 | import { liveClientJs, liveMount } from "../live.ts"; |
| 29 | 30 | import { localScope, type RepoScope } from "../scope.ts"; |
| 30 | 31 | import { |
| @@ -147,6 +148,7 @@ export function renderCommit( | ||
| 147 | 148 | diff: Diff, |
| 148 | 149 | syntax: SyntaxMap, |
| 149 | 150 | check: CommitCheck | null = null, |
| 151 | offer: Html | null = null, | |
| 150 | 152 | ): Html { |
| 151 | 153 | const verdict: Html = |
| 152 | 154 | check !== null && check.state !== "none" |
| @@ -173,7 +175,8 @@ export function renderCommit( | ||
| 173 | 175 | )} |
| 174 | 176 | <span class="spacer"></span> |
| 175 | 177 | <a href="${scope.base}/tree/${commit.oid}">Browse files</a> |
| 176 | </p>`; | |
| 178 | </p> | |
| 179 | ${offer}`; | |
| 177 | 180 | return html`<div data-commits>${head}</div> |
| 178 | 181 | <div class="mt"> |
| 179 | 182 | ${renderDiff(diff, { |
| @@ -324,7 +327,7 @@ export async function commitPage(ctx: Ctx): Promise<Response> { | ||
| 324 | 327 | const checked = await checking; |
| 325 | 328 | const rendering = performance.now(); |
| 326 | 329 | const body = html`${scopeHeader(ctx, scope, "commits", { compact: true })} |
| 327 | ${renderCommit(scope, commit, diff, syntax, checked.ok ? checked.value : null)}`; | |
| 330 | ${renderCommit(scope, commit, diff, syntax, checked.ok ? checked.value : null, offerCommitButton(ctx, repo, commit.oid))}`; | |
| 328 | 331 | const response = page({ |
| 329 | 332 | ctx, |
| 330 | 333 | title: `${commit.subject} · ${repo.name}`, |
src/web/pages/offer-upstream.ts +49 −2
| @@ -6,10 +6,17 @@ | ||
| 6 | 6 | * `upstreamOffer`'s, shared with the terminal; no git here. |
| 7 | 7 | */ |
| 8 | 8 | |
| 9 | import { OFFER_COMMIT_WORDS, offerCommit } from "../../actions/offer_commit.ts"; | |
| 9 | 10 | import type { UpstreamOffer } from "../../actions/offer_upstream.ts"; |
| 10 | import type { Repo } from "../../core/repos.ts"; | |
| 11 | import { repoBase } from "../chrome.ts"; | |
| 11 | import { canWrite, type Repo } from "../../core/repos.ts"; | |
| 12 | import { isSafeOid } from "../../git/guard.ts"; | |
| 13 | import { commitLog } from "../../git/read.ts"; | |
| 14 | import { repoDir } from "../../git/repos.ts"; | |
| 15 | import type { Ctx } from "../../http/context.ts"; | |
| 16 | import { loadRepo, notFoundPage, repoBase, signInFirst } from "../chrome.ts"; | |
| 17 | import { readForm } from "../form.ts"; | |
| 12 | 18 | import { html, type Html } from "../html.ts"; |
| 19 | import { flashTo } from "../layout.ts"; | |
| 13 | 20 | import { btn } from "../ui.ts"; |
| 14 | 21 | |
| 15 | 22 | export function offerUpstream( |
| @@ -31,3 +38,43 @@ export function offerUpstream( | ||
| 31 | 38 | })} |
| 32 | 39 | </div>`; |
| 33 | 40 | } |
| 41 | ||
| 42 | /** | |
| 43 | * The button on one commit of a fork: shown to someone who writes to the fork | |
| 44 | * (the upstream's own answer, refusals included, comes on the post). | |
| 45 | */ | |
| 46 | export function offerCommitButton( | |
| 47 | ctx: Ctx, | |
| 48 | repo: Repo, | |
| 49 | oid: string, | |
| 50 | ): Html | null { | |
| 51 | if (repo.forkParentId === null || ctx.auth.user === undefined) return null; | |
| 52 | if (!canWrite(ctx.app.db, repo, ctx.auth.user)) return null; | |
| 53 | return html`<form method="post" action="${repoBase(repo)}/commit/${oid}/offer" class="mt"> | |
| 54 | ${btn("Offer upstream", { size: "sm", icon: "merge" })} | |
| 55 | </form>`; | |
| 56 | } | |
| 57 | ||
| 58 | // POST /:owner/:name/commit/:oid/offer | |
| 59 | export async function offerCommitPost(ctx: Ctx): Promise<Response> { | |
| 60 | const repo = loadRepo(ctx); | |
| 61 | if (!repo) return notFoundPage(ctx); | |
| 62 | if (!ctx.auth.user) return signInFirst(ctx); | |
| 63 | const form = await readForm(ctx, "rw"); | |
| 64 | if (form instanceof Response) return form; | |
| 65 | const rev = ctx.params.oid ?? ""; | |
| 66 | // Before any git call: only a full object id names a commit here, so a segment shaped like an | |
| 67 | // option or a ref never reaches git. | |
| 68 | if (!isSafeOid(rev)) return notFoundPage(ctx); | |
| 69 | const back = `${repoBase(repo)}/commit/${rev}`; | |
| 70 | const dir = repoDir(ctx.app.reposRoot, repo.ownerName, repo.name); | |
| 71 | const log = await commitLog(dir, rev, { limit: 1 }); | |
| 72 | const commit = log.ok ? log.value[0] : undefined; | |
| 73 | if (commit === undefined) return notFoundPage(ctx); | |
| 74 | const offered = await offerCommit(ctx.app, ctx.auth.user, repo, commit.oid, commit.subject); | |
| 75 | if (!offered.ok) | |
| 76 | return flashTo(ctx, back, { tone: "danger", message: OFFER_COMMIT_WORDS[offered.error] }); | |
| 77 | return flashTo(ctx, `${repoBase(offered.value.parent)}/pulls/${offered.value.pull.number}`, { | |
| 78 | message: `Offered upstream as #${offered.value.pull.number}.`, | |
| 79 | }); | |
| 80 | } |
test/offer-commit-tui.test.ts added +124
| @@ -0,0 +1,124 @@ | ||
| 1 | /** | |
| 2 | * The terminal's one-commit view offers a fork's commit upstream with `o`, through the same | |
| 3 | * action as the page: the pull opens on the parent (and is announced on the bus, so a viewer of | |
| 4 | * the web page sees it live), and a refusal is the page's words. | |
| 5 | */ | |
| 6 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 7 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 8 | import { tmpdir } from "node:os"; | |
| 9 | import { join } from "node:path"; | |
| 10 | import { OFFER_COMMIT_WORDS } from "../src/actions/offer_commit.ts"; | |
| 11 | import { setRole } from "../src/actions/roles.ts"; | |
| 12 | import { commitToBranch, createRepo, forkRepo } from "../src/actions/repos.ts"; | |
| 13 | import { createApp, type App } from "../src/app.ts"; | |
| 14 | import { getRepo, type Repo } from "../src/core/repos.ts"; | |
| 15 | import { createUser, type User } from "../src/core/users.ts"; | |
| 16 | import type { Ctx } from "../src/tui/app/app.ts"; | |
| 17 | import { commitScreen } from "../src/tui/screens/commits.ts"; | |
| 18 | import { local } from "../src/tui/screens/where.ts"; | |
| 19 | import { Session } from "../src/tui/session.ts"; | |
| 20 | import { theme } from "../src/tui/ui/theme.ts"; | |
| 21 | import { quietLogs } from "./helpers/globals.ts"; | |
| 22 | ||
| 23 | quietLogs(); | |
| 24 | ||
| 25 | let dataDir: string; | |
| 26 | let app: App; | |
| 27 | let owner: User; | |
| 28 | let forker: User; | |
| 29 | let fork: Repo; | |
| 30 | let oid = ""; | |
| 31 | const toasts: string[] = []; | |
| 32 | ||
| 33 | const ctx = { | |
| 34 | theme: theme("dark"), | |
| 35 | push: () => {}, | |
| 36 | pop: () => {}, | |
| 37 | replace: () => {}, | |
| 38 | invalidate: () => {}, | |
| 39 | toast: (text: string) => void toasts.push(text), | |
| 40 | hit: () => {}, | |
| 41 | track: <T>(p: Promise<T>) => p, | |
| 42 | } as unknown as Ctx; | |
| 43 | ||
| 44 | const mk = async (username: string, first: boolean): Promise<User> => { | |
| 45 | const made = await createUser(app.db, { | |
| 46 | origin: "seed", | |
| 47 | trusted: true, | |
| 48 | username, | |
| 49 | email: `${username}@forge.local`, | |
| 50 | password: "a-good-passphrase", | |
| 51 | adminIfFirst: first, | |
| 52 | }); | |
| 53 | if (!made.ok) throw new Error(made.error); | |
| 54 | return made.value; | |
| 55 | }; | |
| 56 | ||
| 57 | beforeAll(async () => { | |
| 58 | dataDir = await mkdtemp(join(tmpdir(), "forge-offer-tui-")); | |
| 59 | app = createApp({ dataDir, port: 0, host: "forge.test" }); | |
| 60 | const admin = await mk("hank", true); | |
| 61 | owner = await mk("olive", false); | |
| 62 | forker = await mk("ravi", false); | |
| 63 | for (const u of [owner, forker]) setRole(app, admin, u.username, "member"); | |
| 64 | const r = await createRepo(app, owner, { name: "yard", visibility: "public" }); | |
| 65 | if (!r.ok) throw new Error(String(r.error)); | |
| 66 | await commitToBranch(app, owner, r.value, { message: "first", files: [{ path: "a.txt", content: "a\n" }] }); | |
| 67 | const f = await forkRepo(app, forker, r.value); | |
| 68 | if (!f.ok) throw new Error(String(f.error)); | |
| 69 | fork = getRepo(app.db, "ravi", "yard")!; | |
| 70 | const c = await commitToBranch(app, forker, fork, { message: "mine", files: [{ path: "m.txt", content: "m\n" }] }); | |
| 71 | if (!c.ok) throw new Error(String(c.error)); | |
| 72 | oid = c.value.commitOid; | |
| 73 | }, 60_000); | |
| 74 | ||
| 75 | afterAll(async () => { | |
| 76 | app.close(); | |
| 77 | await rm(dataDir, { recursive: true, force: true }); | |
| 78 | }); | |
| 79 | ||
| 80 | const open = async (user: User, repo: Repo) => { | |
| 81 | const f = new Session(app, { sshUsername: "t", remoteAddress: "127.0.0.1", user }); | |
| 82 | const src = local(f, repo); | |
| 83 | const found = await src.commit(oid); | |
| 84 | if (!found.ok) throw new Error("commit not found"); | |
| 85 | return commitScreen(f, ctx, src, found.value.commit); | |
| 86 | }; | |
| 87 | const toastCount = async (n: number, ok = () => toasts.length >= n): Promise<void> => { | |
| 88 | for (let i = 0; i < 500 && !ok(); i++) { | |
| 89 | await Bun.sleep(20); // real-timer: the offer opens its pull in a background task with no hook to await | |
| 90 | } | |
| 91 | if (!ok()) throw new Error(`no toast number ${n} within 10 s`); | |
| 92 | }; | |
| 93 | const press = (screen: Awaited<ReturnType<typeof open>>) => | |
| 94 | screen.key!({ type: "key", key: "o", ctrl: false, alt: false, shift: false }); | |
| 95 | ||
| 96 | test("o on a fork's commit opens the pull upstream, announced on the bus, and a second o says it is offered", async () => { | |
| 97 | const seen: string[] = []; | |
| 98 | app.bus.subscribe((event) => void seen.push(event.kind), "local"); | |
| 99 | const screen = await open(forker, fork); | |
| 100 | expect(screen.keys.map((k) => JSON.stringify(k)).join()).toContain("offer upstream"); | |
| 101 | expect(press(screen)).toBe(true); | |
| 102 | await toastCount(1); | |
| 103 | expect(toasts[0]).toContain("Offered upstream as olive/yard#"); | |
| 104 | expect(seen).toContain("pull.opened"); | |
| 105 | press(screen); | |
| 106 | await toastCount(2); | |
| 107 | expect(toasts[1]).toBe(OFFER_COMMIT_WORDS.already_offered); | |
| 108 | }); | |
| 109 | ||
| 110 | test("a repository that is not a fork has no such key", async () => { | |
| 111 | const parent = getRepo(app.db, "olive", "yard")!; | |
| 112 | const c = await commitToBranch(app, owner, parent, { message: "own", files: [{ path: "o.txt", content: "o\n" }] }); | |
| 113 | if (!c.ok) throw new Error(String(c.error)); | |
| 114 | const f = new Session(app, { sshUsername: "t", remoteAddress: "127.0.0.1", user: owner }); | |
| 115 | const src = local(f, parent); | |
| 116 | const found = await src.commit(c.value.commitOid); | |
| 117 | if (!found.ok) throw new Error("commit not found"); | |
| 118 | const screen = commitScreen(f, ctx, src, found.value.commit); | |
| 119 | expect(screen.keys.map((k) => JSON.stringify(k)).join()).not.toContain("offer upstream"); | |
| 120 | const before = toasts.length; | |
| 121 | press(screen); | |
| 122 | await Bun.sleep(50); // real-timer: proving nothing happens has no event to wait for | |
| 123 | expect(toasts.length).toBe(before); | |
| 124 | }); |
test/offer-commit.test.ts added +261
| @@ -0,0 +1,261 @@ | ||
| 1 | /** | |
| 2 | * One commit of a fork offered upstream from its page: a pull on the parent | |
| 3 | * that names the fork and carries its check verdict; refused in words when the | |
| 4 | * upstream is archived, the commit is already offered or the viewer cannot write. | |
| 5 | */ | |
| 6 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 7 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 8 | import { tmpdir } from "node:os"; | |
| 9 | import { join } from "node:path"; | |
| 10 | import type { CommitCheck } from "../src/checks/commit_check.ts"; | |
| 11 | import { OFFER_COMMIT_WORDS, offerBranch, offerCommit, verdictWords } from "../src/actions/offer_commit.ts"; | |
| 12 | import { setRole } from "../src/actions/roles.ts"; | |
| 13 | import { commitToBranch, createRepo, forkRepo } from "../src/actions/repos.ts"; | |
| 14 | import { createApp, type App } from "../src/app.ts"; | |
| 15 | import { getIssueById } from "../src/core/issues.ts"; | |
| 16 | import { createRun, finishRun } from "../src/core/runs.ts"; | |
| 17 | import { resolveOid } from "../src/git/merge.ts"; | |
| 18 | import { repoDir } from "../src/git/repos.ts"; | |
| 19 | import { getRepo, type Repo } from "../src/core/repos.ts"; | |
| 20 | import { createUser, type User } from "../src/core/users.ts"; | |
| 21 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 22 | import { quietLogs } from "./helpers/globals.ts"; | |
| 23 | ||
| 24 | quietLogs(); | |
| 25 | ||
| 26 | let dataDir: string; | |
| 27 | let app: App; | |
| 28 | let servers: Servers; | |
| 29 | let users: User[] = []; | |
| 30 | let oids: string[] = []; | |
| 31 | ||
| 32 | async function mk(username: string, first: boolean): Promise<User> { | |
| 33 | const made = await createUser(app.db, { | |
| 34 | origin: "seed", | |
| 35 | trusted: true, | |
| 36 | username, | |
| 37 | email: `${username}@forge.local`, | |
| 38 | password: "a-good-passphrase", | |
| 39 | adminIfFirst: first, | |
| 40 | }); | |
| 41 | if (!made.ok) throw new Error(made.error); | |
| 42 | return made.value; | |
| 43 | } | |
| 44 | ||
| 45 | const signIn = async (username: string): Promise<string> => { | |
| 46 | const r = await fetch(`${servers.url}/signin`, { | |
| 47 | method: "POST", | |
| 48 | body: new URLSearchParams({ username, password: "a-good-passphrase" }), | |
| 49 | redirect: "manual", | |
| 50 | }); | |
| 51 | return (r.headers.get("set-cookie") ?? "").split(";")[0]!; | |
| 52 | }; | |
| 53 | ||
| 54 | const post = async (path: string, cookie: string): Promise<Response> => | |
| 55 | fetch(`${servers.url}${path}`, { | |
| 56 | method: "POST", | |
| 57 | headers: { cookie, origin: servers.url }, | |
| 58 | redirect: "manual", | |
| 59 | }); | |
| 60 | ||
| 61 | const forkOf = (): Repo => getRepo(app.db, "ravi", "yard")!; | |
| 62 | ||
| 63 | beforeAll(async () => { | |
| 64 | dataDir = await mkdtemp(join(tmpdir(), "forge-offer-commit-")); | |
| 65 | app = createApp({ dataDir, port: 0, host: "forge.test" }); | |
| 66 | servers = await serve(app); | |
| 67 | users = [await mk("hank", true), await mk("olive", false), await mk("ravi", false)]; | |
| 68 | for (const name of ["olive", "ravi"]) setRole(app, users[0]!, name, "member"); | |
| 69 | const r = await createRepo(app, users[1]!, { name: "yard", visibility: "public" }); | |
| 70 | if (!r.ok) throw new Error(String(r.error)); | |
| 71 | await commitToBranch(app, users[1]!, r.value, { message: "first", files: [{ path: "a.txt", content: "a\n" }] }); | |
| 72 | const f = await forkRepo(app, users[2]!, r.value); | |
| 73 | if (!f.ok) throw new Error(String(f.error)); | |
| 74 | for (const n of ["one", "two", "three"]) { | |
| 75 | const c = await commitToBranch(app, users[2]!, forkOf(), { | |
| 76 | message: `mine ${n}`, | |
| 77 | files: [{ path: `${n}.txt`, content: "x\n" }], | |
| 78 | }); | |
| 79 | if (!c.ok) throw new Error(String(c.error)); | |
| 80 | oids.push(c.value.commitOid); | |
| 81 | } | |
| 82 | }); | |
| 83 | ||
| 84 | afterAll(async () => { | |
| 85 | await servers.stop(); | |
| 86 | await rm(dataDir, { recursive: true, force: true }); | |
| 87 | }); | |
| 88 | ||
| 89 | test("a fork's writer sees the button on a commit; a stranger and the parent's owner do not", async () => { | |
| 90 | const path = `/ravi/yard/commit/${oids[0]}`; | |
| 91 | const mine = await (await fetch(`${servers.url}${path}`, { headers: { cookie: await signIn("ravi") } })).text(); | |
| 92 | expect(mine).toContain("Offer upstream"); | |
| 93 | expect(mine).toContain(`action="/ravi/yard/commit/${oids[0]}/offer"`); | |
| 94 | const theirs = await (await fetch(`${servers.url}${path}`, { headers: { cookie: await signIn("olive") } })).text(); | |
| 95 | expect(theirs).not.toContain("Offer upstream"); | |
| 96 | const anon = await (await fetch(`${servers.url}${path}`)).text(); | |
| 97 | expect(anon).not.toContain("Offer upstream"); | |
| 98 | }); | |
| 99 | ||
| 100 | test("offering a commit opens a pull on the parent naming the fork and its check verdict", async () => { | |
| 101 | const res = await post(`/ravi/yard/commit/${oids[0]}/offer`, await signIn("ravi")); | |
| 102 | expect(res.status).toBe(303); | |
| 103 | const to = res.headers.get("location") ?? ""; | |
| 104 | expect(to).toMatch(/^\/olive\/yard\/pulls\/\d+/); | |
| 105 | const number = Number(/pulls\/(\d+)/.exec(to)![1]); | |
| 106 | const parent = getRepo(app.db, "olive", "yard")!; | |
| 107 | const issue = app.db | |
| 108 | .query<{ id: string }, [string, number]>("SELECT id FROM issue WHERE repo_id = ? AND number = ?") | |
| 109 | .get(parent.id, number)!; | |
| 110 | const pull = getIssueById(app.db, issue.id)!; | |
| 111 | expect(pull.title).toBe("mine one"); | |
| 112 | expect(pull.body).toContain("ravi/yard"); | |
| 113 | expect(pull.body).toContain(oids[0]!.slice(0, 7)); | |
| 114 | expect(pull.body).toContain("No check ran on this commit in the fork."); | |
| 115 | }); | |
| 116 | ||
| 117 | test("the same commit is refused a second time, in words", async () => { | |
| 118 | const again = await offerCommit(app, users[2]!, forkOf(), oids[0]!, "mine one"); | |
| 119 | expect(again.ok).toBe(false); | |
| 120 | if (!again.ok) { | |
| 121 | expect(again.error).toBe("already_offered"); | |
| 122 | expect(OFFER_COMMIT_WORDS[again.error]).toContain("already offered"); | |
| 123 | } | |
| 124 | }); | |
| 125 | ||
| 126 | test("someone who cannot write to the fork is refused", async () => { | |
| 127 | const refused = await offerCommit(app, users[1]!, forkOf(), oids[1]!, "x"); | |
| 128 | expect(refused.ok).toBe(false); | |
| 129 | if (!refused.ok) expect(refused.error).toBe("forbidden"); | |
| 130 | }); | |
| 131 | ||
| 132 | test("a repository that is not a fork has nowhere to offer", async () => { | |
| 133 | const parent = getRepo(app.db, "olive", "yard")!; | |
| 134 | const refused = await offerCommit(app, users[1]!, parent, oids[1]!, "x"); | |
| 135 | if (refused.ok) throw new Error("offered from a non-fork"); | |
| 136 | expect(refused.error).toBe("not_a_fork"); | |
| 137 | }); | |
| 138 | ||
| 139 | test("an archived upstream accepts no offers, and the page says so", async () => { | |
| 140 | const parent = getRepo(app.db, "olive", "yard")!; | |
| 141 | app.db.run("UPDATE repo SET archived_at = ? WHERE id = ?", [new Date().toISOString(), parent.id]); | |
| 142 | const res = await post(`/ravi/yard/commit/${oids[1]}/offer`, await signIn("ravi")); | |
| 143 | expect(res.status).toBe(303); | |
| 144 | expect(res.headers.get("location")).toContain(`/ravi/yard/commit/${oids[1]}`); | |
| 145 | const refused = await offerCommit(app, users[2]!, forkOf(), oids[1]!, "two"); | |
| 146 | if (refused.ok) throw new Error("offered to an archived upstream"); | |
| 147 | expect(refused.error).toBe("upstream_archived"); | |
| 148 | expect(OFFER_COMMIT_WORDS.upstream_archived).toContain("archived"); | |
| 149 | app.db.run("UPDATE repo SET archived_at = NULL WHERE id = ?", [parent.id]); | |
| 150 | }); | |
| 151 | ||
| 152 | test("a cross-origin post is refused", async () => { | |
| 153 | const r = await fetch(`${servers.url}/ravi/yard/commit/${oids[2]}/offer`, { | |
| 154 | method: "POST", | |
| 155 | headers: { cookie: await signIn("ravi"), origin: "https://evil.example" }, | |
| 156 | redirect: "manual", | |
| 157 | }); | |
| 158 | expect(r.status).toBe(403); | |
| 159 | }); | |
| 160 | ||
| 161 | test("the verdict is worded for every state the fork's check can be in", () => { | |
| 162 | const check = (state: CommitCheck["state"]): CommitCheck => ({ | |
| 163 | commit: "a".repeat(40), | |
| 164 | checkedCommit: "a".repeat(40), | |
| 165 | state, | |
| 166 | runId: null, | |
| 167 | summary: "", | |
| 168 | finishedAt: null, | |
| 169 | }); | |
| 170 | expect(verdictWords(check("ok"))).toContain("passed"); | |
| 171 | expect(verdictWords(check("failed"))).toContain("failed"); | |
| 172 | expect(verdictWords(check("pending"))).toContain("running"); | |
| 173 | expect(verdictWords(check("superseded"))).toContain("superseded"); | |
| 174 | expect(verdictWords(check("none"))).toContain("No check"); | |
| 175 | expect(verdictWords(null)).toContain("No check"); | |
| 176 | }); | |
| 177 | ||
| 178 | /** A commit on the fork's default branch, with the fork's check run ending as `state` (or none). */ | |
| 179 | async function forkCommit(name: string, state: "ok" | "failed" | null): Promise<string> { | |
| 180 | const c = await commitToBranch(app, users[2]!, forkOf(), { | |
| 181 | message: `commit ${name}`, | |
| 182 | files: [{ path: `${name}.txt`, content: `${name}\n` }], | |
| 183 | }); | |
| 184 | if (!c.ok) throw new Error(String(c.error)); | |
| 185 | if (state !== null) { | |
| 186 | const run = createRun(app.db, { | |
| 187 | repoId: forkOf().id, | |
| 188 | kind: "check", | |
| 189 | env: forkOf().defaultBranch, | |
| 190 | commitOid: c.value.commitOid, | |
| 191 | }); | |
| 192 | app.db.query("UPDATE run SET state = 'running' WHERE id = ?1").run(run.id); | |
| 193 | finishRun(app.db, run.id, { state, summary: state === "ok" ? "" : "step typecheck failed" }); | |
| 194 | } | |
| 195 | return c.value.commitOid; | |
| 196 | } | |
| 197 | ||
| 198 | const bodyOf = (parent: Repo, number: number): string => { | |
| 199 | const row = app.db | |
| 200 | .query<{ id: string }, [string, number]>("SELECT id FROM issue WHERE repo_id = ? AND number = ?") | |
| 201 | .get(parent.id, number)!; | |
| 202 | return getIssueById(app.db, row.id)!.body; | |
| 203 | }; | |
| 204 | ||
| 205 | const hasBranch = async (name: string): Promise<boolean> => { | |
| 206 | const dir = repoDir(app.reposRoot, "ravi", "yard"); | |
| 207 | return (await resolveOid(dir, `refs/heads/${name}`)) !== undefined; | |
| 208 | }; | |
| 209 | ||
| 210 | test("an id that is not a full object id gets 404 before any git call, and opens nothing", async () => { | |
| 211 | const cookie = await signIn("ravi"); | |
| 212 | const parent = getRepo(app.db, "olive", "yard")!; | |
| 213 | const before = app.db.query<{ n: number }, [string]>("SELECT COUNT(*) AS n FROM issue WHERE repo_id = ?").get(parent.id)!.n; | |
| 214 | for (const bad of ["-bad", "--output=x", "zzzz", "main", oids[0]!.slice(0, 12), "A".repeat(40)]) { | |
| 215 | const res = await post(`/ravi/yard/commit/${bad}/offer`, cookie); | |
| 216 | expect(res.status).toBe(404); | |
| 217 | } | |
| 218 | const after = app.db.query<{ n: number }, [string]>("SELECT COUNT(*) AS n FROM issue WHERE repo_id = ?").get(parent.id)!.n; | |
| 219 | expect(after).toBe(before); | |
| 220 | }); | |
| 221 | ||
| 222 | test("a commit the fork's check passed carries that wording, on an offer/<12 hex> branch in the fork", async () => { | |
| 223 | const oid = await forkCommit("green", "ok"); | |
| 224 | const offered = await offerCommit(app, users[2]!, forkOf(), oid, "green"); | |
| 225 | if (!offered.ok) throw new Error(offered.error); | |
| 226 | expect(bodyOf(offered.value.parent, offered.value.pull.number)).toContain("The fork's check passed on this commit."); | |
| 227 | expect(offerBranch(oid)).toMatch(/^offer\/[0-9a-f]{12}$/); | |
| 228 | expect(await hasBranch(offerBranch(oid))).toBe(true); | |
| 229 | }); | |
| 230 | ||
| 231 | test("a commit the fork's check failed says so", async () => { | |
| 232 | const oid = await forkCommit("red", "failed"); | |
| 233 | const offered = await offerCommit(app, users[2]!, forkOf(), oid, "red"); | |
| 234 | if (!offered.ok) throw new Error(offered.error); | |
| 235 | expect(bodyOf(offered.value.parent, offered.value.pull.number)).toContain("The fork's check failed on this commit."); | |
| 236 | }); | |
| 237 | ||
| 238 | test("an offer/ branch left by a closed pull can be offered again", async () => { | |
| 239 | const oid = await forkCommit("again", null); | |
| 240 | const first = await offerCommit(app, users[2]!, forkOf(), oid, "again"); | |
| 241 | if (!first.ok) throw new Error(first.error); | |
| 242 | app.db.run("UPDATE issue SET state = 'closed' WHERE repo_id = ? AND number = ?", [first.value.parent.id, first.value.pull.number]); | |
| 243 | expect(await hasBranch(offerBranch(oid))).toBe(true); | |
| 244 | const second = await offerCommit(app, users[2]!, forkOf(), oid, "again"); | |
| 245 | if (!second.ok) throw new Error(second.error); | |
| 246 | expect(second.value.pull.number).not.toBe(first.value.pull.number); | |
| 247 | }); | |
| 248 | ||
| 249 | test("when the upstream does not open the pull, the branch the offer cut goes with it", async () => { | |
| 250 | const oid = await forkCommit("fails", null); | |
| 251 | const parent = getRepo(app.db, "olive", "yard")!; | |
| 252 | app.db.run("UPDATE repo SET default_branch = 'nowhere' WHERE id = ?", [parent.id]); | |
| 253 | try { | |
| 254 | const refused = await offerCommit(app, users[2]!, forkOf(), oid, "fails"); | |
| 255 | if (refused.ok) throw new Error("opened against a branch that is not there"); | |
| 256 | expect(refused.error).toBe("not_opened"); | |
| 257 | expect(await hasBranch(offerBranch(oid))).toBe(false); | |
| 258 | } finally { | |
| 259 | app.db.run("UPDATE repo SET default_branch = ? WHERE id = ?", [parent.defaultBranch, parent.id]); | |
| 260 | } | |
| 261 | }); |
new above
offline
HIGH: the :oid param goes to git unvalidated. Check isSafeOid(ctx.params.oid) and return notFoundPage first, and add a test.