Public: anyone can read this; the crew can change it.
Take it back: undo a shipped change from the studio #156
scout/forge:scout/92-take-it-back-undo-a-shipped-change-from → main 2 commits fork
11 files
changed +562
−13
src/actions/pulls.ts +4
| @@ -74,6 +74,9 @@ export interface OpenPullInput { | ||
| 74 | 74 | headBranch: string; |
| 75 | 75 | /** For a fork proposing upstream: the fork the head branch lives in. */ |
| 76 | 76 | headRepo?: Repo; |
| 77 | /** The issue id of the pull this one reverts ("Take it back"). Native | |
| 78 | * repos only — a mirror's pull is the origin's, which has no such field. */ | |
| 79 | revertsIssueId?: string; | |
| 77 | 80 | } |
| 78 | 81 | |
| 79 | 82 | export async function openPull( |
| @@ -171,6 +174,7 @@ export async function openPull( | ||
| 171 | 174 | headDir: repoDir(app.reposRoot, head.ownerName, head.name), |
| 172 | 175 | } |
| 173 | 176 | : {}), |
| 177 | ...(input.revertsIssueId ? { revertsIssueId: input.revertsIssueId } : {}), | |
| 174 | 178 | }, |
| 175 | 179 | ); |
| 176 | 180 | if (!created.ok) return created; |
src/actions/revert.ts added +96
| @@ -0,0 +1,96 @@ | ||
| 1 | /** | |
| 2 | * Take it back: land a change that undoes exactly what a shipped pull | |
| 3 | * merged. It never writes to the default branch itself — a branch, a | |
| 4 | * revert commit built as plumbing (`git/revert.ts`), and a pull whose title | |
| 5 | * says what it undoes, exactly like any other change a person opens. Only | |
| 6 | * a fresh branch and a fresh pull commit if the revert applies cleanly; | |
| 7 | * anything that does not land cleanly leaves nothing behind. | |
| 8 | */ | |
| 9 | ||
| 10 | import type { App } from "../app.ts"; | |
| 11 | import { revertOf, type Pull } from "../core/pulls.ts"; | |
| 12 | import type { Repo } from "../core/repos.ts"; | |
| 13 | import type { User } from "../core/users.ts"; | |
| 14 | import { resolveOid } from "../git/merge.ts"; | |
| 15 | import { repoDir } from "../git/repos.ts"; | |
| 16 | import { revertCommit, type RevertError } from "../git/revert.ts"; | |
| 17 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 18 | import { requireWriter, type AccessError } from "./access.ts"; | |
| 19 | import { createBranch, deleteBranch } from "./branches.ts"; | |
| 20 | import { openPull } from "./pulls.ts"; | |
| 21 | ||
| 22 | export type RevertPullError = | |
| 23 | | AccessError | |
| 24 | | RevertError | |
| 25 | | "not_shipped" | |
| 26 | | "mirrored" | |
| 27 | | "already_reverted" | |
| 28 | | { kind: "branch_failed"; reason: string } | |
| 29 | | { kind: "pull_failed"; reason: string }; | |
| 30 | ||
| 31 | export async function revertPull( | |
| 32 | app: App, | |
| 33 | actor: User | undefined, | |
| 34 | repo: Repo, | |
| 35 | pull: Pull, | |
| 36 | ): Promise<Result<Pull, RevertPullError>> { | |
| 37 | const writer = requireWriter(app, actor, repo); | |
| 38 | if (!writer.ok) return writer; | |
| 39 | if (pull.repoId !== repo.id) return err("not_found"); | |
| 40 | // Rule 1 in docs/APPS.md: the crew proposes, a person lands. Taking a | |
| 41 | // change back is a landing verb, not a proposing one. | |
| 42 | if (writer.value.kind === "agent") return err("forbidden"); | |
| 43 | if (pull.mergedAt === null || pull.mergedOid === null) | |
| 44 | return err("not_shipped"); | |
| 45 | // On a mirror the origin owns history; a local revert here would be | |
| 46 | // overwritten by the next sync, exactly as a local merge would. | |
| 47 | if (repo.origin !== null || pull.originHeadRepo !== null) | |
| 48 | return err("mirrored"); | |
| 49 | if (revertOf(app.db, repo.id, pull.id) !== undefined) | |
| 50 | return err("already_reverted"); | |
| 51 | ||
| 52 | const dir = repoDir(app.reposRoot, repo.ownerName, repo.name); | |
| 53 | const onto = await resolveOid(dir, `refs/heads/${repo.defaultBranch}`); | |
| 54 | if (onto === undefined) | |
| 55 | return err({ kind: "git", message: "the default branch has no tip" }); | |
| 56 | ||
| 57 | const built = await revertCommit(dir, { | |
| 58 | commitOid: pull.mergedOid, | |
| 59 | ontoOid: onto, | |
| 60 | message: `Revert "${pull.title}" (#${pull.number})`, | |
| 61 | author: { | |
| 62 | name: writer.value.displayName || writer.value.username, | |
| 63 | email: writer.value.email, | |
| 64 | }, | |
| 65 | }); | |
| 66 | if (!built.ok) return built; | |
| 67 | ||
| 68 | // The branch name is the server's own — never taken from the request — | |
| 69 | // so it always says exactly what it reverts. | |
| 70 | const branchName = `revert-${pull.number}`; | |
| 71 | const branch = await createBranch(app, writer.value, repo, { | |
| 72 | name: branchName, | |
| 73 | from: built.value.commitOid, | |
| 74 | }); | |
| 75 | if (!branch.ok) { | |
| 76 | const reason = typeof branch.error === "string" ? branch.error : "git"; | |
| 77 | return err({ kind: "branch_failed", reason }); | |
| 78 | } | |
| 79 | ||
| 80 | const opened = await openPull(app, writer.value, repo, { | |
| 81 | title: `Revert "${pull.title}"`, | |
| 82 | body: `Reverts #${pull.number}.`, | |
| 83 | baseBranch: repo.defaultBranch, | |
| 84 | headBranch: branchName, | |
| 85 | revertsIssueId: pull.id, | |
| 86 | }); | |
| 87 | if (!opened.ok) { | |
| 88 | // The branch was made for this pull and the pull did not open: take it | |
| 89 | // back so a refused revert leaves nothing half-made behind, the same | |
| 90 | // rule `editFiles` (`actions/contents.ts`) follows for the same reason. | |
| 91 | await deleteBranch(app, writer.value, repo, branchName); | |
| 92 | const reason = typeof opened.error === "string" ? opened.error : "git"; | |
| 93 | return err({ kind: "pull_failed", reason }); | |
| 94 | } | |
| 95 | return ok(opened.value); | |
| 96 | } |
src/core/pulls.ts +32 −2
| @@ -51,6 +51,8 @@ export interface Pull extends Issue { | ||
| 51 | 51 | * not hold): `owner/name` there. Null for a native pull. |
| 52 | 52 | */ |
| 53 | 53 | readonly originHeadRepo: string | null; |
| 54 | /** The pull this one reverts, when it was opened by "Take it back". */ | |
| 55 | readonly revertsPullId: string | null; | |
| 54 | 56 | } |
| 55 | 57 | |
| 56 | 58 | interface PullRow { |
| @@ -62,6 +64,7 @@ interface PullRow { | ||
| 62 | 64 | merged_oid: string | null; |
| 63 | 65 | head_repo_id: string | null; |
| 64 | 66 | origin_head_repo: string | null; |
| 67 | reverts_issue_id: string | null; | |
| 65 | 68 | } |
| 66 | 69 | |
| 67 | 70 | function fromRow(issue: Issue, row: PullRow): Pull { |
| @@ -77,6 +80,7 @@ function fromRow(issue: Issue, row: PullRow): Pull { | ||
| 77 | 80 | headRepoId, |
| 78 | 81 | crossRepo: headRepoId !== issue.repoId, |
| 79 | 82 | originHeadRepo: row.origin_head_repo, |
| 83 | revertsPullId: row.reverts_issue_id, | |
| 80 | 84 | }; |
| 81 | 85 | } |
| 82 | 86 | |
| @@ -110,6 +114,8 @@ export interface CreatePullInput { | ||
| 110 | 114 | headRepoId?: string; |
| 111 | 115 | /** The fork's on-disk dir, required when headRepoId differs from the base. */ |
| 112 | 116 | headDir?: string; |
| 117 | /** The issue id of the pull this one reverts ("Take it back"). */ | |
| 118 | revertsIssueId?: string; | |
| 113 | 119 | } |
| 114 | 120 | |
| 115 | 121 | export async function createPull( |
| @@ -148,8 +154,8 @@ export async function createPull( | ||
| 148 | 154 | |
| 149 | 155 | const headRepoId = input.headRepoId ?? input.repoId; |
| 150 | 156 | db.query( |
| 151 | `INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid, head_repo_id) | |
| 152 | VALUES (?1, ?2, ?3, ?4, ?5, ?6)`, | |
| 157 | `INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid, head_repo_id, reverts_issue_id) | |
| 158 | VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)`, | |
| 153 | 159 | ).run( |
| 154 | 160 | issue.value.id, |
| 155 | 161 | input.baseBranch, |
| @@ -157,6 +163,7 @@ export async function createPull( | ||
| 157 | 163 | baseOid, |
| 158 | 164 | headOid, |
| 159 | 165 | headRepoId, |
| 166 | input.revertsIssueId ?? null, | |
| 160 | 167 | ); |
| 161 | 168 | |
| 162 | 169 | // A durable, fetchable ref for the PR head — the way tooling addresses it, |
| @@ -199,6 +206,29 @@ export function pullForBranch( | ||
| 199 | 206 | return row ? getPull(db, repoId, row.number) : undefined; |
| 200 | 207 | } |
| 201 | 208 | |
| 209 | /** | |
| 210 | * The pull that already reverts this one, if taking it back has already | |
| 211 | * been done — open, or merged, either one counts as "already taken back". | |
| 212 | * A revert pull that was closed *without* merging is an abandoned attempt, | |
| 213 | * not a standing answer, so it does not block a second try. | |
| 214 | */ | |
| 215 | export function revertOf( | |
| 216 | db: Database, | |
| 217 | repoId: string, | |
| 218 | pullId: string, | |
| 219 | ): Pull | undefined { | |
| 220 | const row = db | |
| 221 | .query< | |
| 222 | { number: number }, | |
| 223 | [string, string] | |
| 224 | >(`SELECT issue.number AS number FROM pull JOIN issue ON issue.id = pull.issue_id | |
| 225 | WHERE issue.repo_id = ?1 AND pull.reverts_issue_id = ?2 | |
| 226 | AND (issue.state = 'open' OR pull.merged_at IS NOT NULL) | |
| 227 | ORDER BY issue.created_at DESC LIMIT 1`) | |
| 228 | .get(repoId, pullId); | |
| 229 | return row ? getPull(db, repoId, row.number) : undefined; | |
| 230 | } | |
| 231 | ||
| 202 | 232 | /** |
| 203 | 233 | * Open pulls, in any repository, whose head is this branch of this one: |
| 204 | 234 | * what a push to a fork moves. |
src/core/schema.ts +9
| @@ -783,4 +783,13 @@ export const migrations: readonly string[] = [ | ||
| 783 | 783 | DROP TABLE look; |
| 784 | 784 | ALTER TABLE look_new RENAME TO look; |
| 785 | 785 | `, |
| 786 | ||
| 787 | // 27 — take it back: a pull that reverts another, named explicitly rather | |
| 788 | // than sniffed from its title. `reverts_issue_id` points at the issue the | |
| 789 | // shipped pull was (a pull is its own issue), so "was this already taken | |
| 790 | // back" is one lookup rather than a guess from wording. | |
| 791 | ` | |
| 792 | ALTER TABLE pull ADD COLUMN reverts_issue_id TEXT REFERENCES issue(id) ON DELETE SET NULL; | |
| 793 | CREATE INDEX pull_reverts ON pull(reverts_issue_id) WHERE reverts_issue_id IS NOT NULL; | |
| 794 | `, | |
| 786 | 795 | ]; |
src/git/merge.ts +36 −8
| @@ -30,23 +30,38 @@ export interface MergeResult { | ||
| 30 | 30 | } |
| 31 | 31 | |
| 32 | 32 | /** |
| 33 | * Can head be merged into base, and if so what would the tree be? Pure | |
| 34 | * computation — writes nothing. Returns the merged tree oid or the conflicted | |
| 35 | * paths. Used both to show mergeability and as the first half of a merge. | |
| 33 | * The plumbing both `mergeable` and a revert's three-way merge share: run | |
| 34 | * `merge-tree --write-tree` over two sides and report the merged tree oid or | |
| 35 | * the conflicted paths. `base` overrides the merge base git would otherwise | |
| 36 | * compute from history — a revert needs the commit being undone as the base, | |
| 37 | * not whatever `ours`/`theirs` share an ancestor with. | |
| 36 | 38 | */ |
| 37 | export async function mergeable( | |
| 39 | export async function writeMergeTree( | |
| 38 | 40 | dir: string, |
| 39 | baseOid: string, | |
| 40 | headOid: string, | |
| 41 | ours: string, | |
| 42 | theirs: string, | |
| 43 | base?: string, | |
| 41 | 44 | ): Promise<Result<{ treeOid: string }, MergeError>> { |
| 42 | if (!isSafeOid(baseOid) || !isSafeOid(headOid)) | |
| 45 | if ( | |
| 46 | !isSafeOid(ours) || | |
| 47 | !isSafeOid(theirs) || | |
| 48 | (base !== undefined && !isSafeOid(base)) | |
| 49 | ) { | |
| 43 | 50 | return err({ kind: "unsafe" }); |
| 51 | } | |
| 44 | 52 | |
| 45 | 53 | // merge-tree exits 0 on a clean merge (stdout = tree oid) and 1 on conflict |
| 46 | 54 | // (stdout = tree oid, blank line, then conflicted file names). Both outcomes |
| 47 | 55 | // are data on stdout, so capture regardless of exit code. |
| 48 | 56 | const out = await runGitCapture( |
| 49 | ["merge-tree", "--write-tree", "--name-only", baseOid, headOid], | |
| 57 | [ | |
| 58 | "merge-tree", | |
| 59 | "--write-tree", | |
| 60 | "--name-only", | |
| 61 | ...(base === undefined ? [] : [`--merge-base=${base}`]), | |
| 62 | ours, | |
| 63 | theirs, | |
| 64 | ], | |
| 50 | 65 | { cwd: dir, timeoutMs: 60_000 }, |
| 51 | 66 | ); |
| 52 | 67 | |
| @@ -70,6 +85,19 @@ export async function mergeable( | ||
| 70 | 85 | }); |
| 71 | 86 | } |
| 72 | 87 | |
| 88 | /** | |
| 89 | * Can head be merged into base, and if so what would the tree be? Pure | |
| 90 | * computation — writes nothing. Returns the merged tree oid or the conflicted | |
| 91 | * paths. Used both to show mergeability and as the first half of a merge. | |
| 92 | */ | |
| 93 | export async function mergeable( | |
| 94 | dir: string, | |
| 95 | baseOid: string, | |
| 96 | headOid: string, | |
| 97 | ): Promise<Result<{ treeOid: string }, MergeError>> { | |
| 98 | return writeMergeTree(dir, baseOid, headOid); | |
| 99 | } | |
| 100 | ||
| 73 | 101 | /** Land head onto base with the chosen strategy, only if base is unmoved. */ |
| 74 | 102 | export async function merge( |
| 75 | 103 | dir: string, |
src/git/revert.ts added +79
| @@ -0,0 +1,79 @@ | ||
| 1 | /** | |
| 2 | * Reverting a shipped commit as plumbing — the same three-way merge `git | |
| 3 | * revert` runs, computed with `merge-tree` instead of a checkout: the commit | |
| 4 | * being undone is the merge base, the branch it landed on is one side, and | |
| 5 | * the commit's own parent (the state right before it) is the other. Any | |
| 6 | * change made since keeps its place; only what this one commit did is | |
| 7 | * undone, and a real conflict is reported rather than guessed at. | |
| 8 | */ | |
| 9 | ||
| 10 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 11 | import { runGit } from "./env.ts"; | |
| 12 | import { isSafeOid } from "./guard.ts"; | |
| 13 | import { writeMergeTree, type MergeError, type MergeIdentity } from "./merge.ts"; | |
| 14 | ||
| 15 | export type RevertError = | |
| 16 | | MergeError | |
| 17 | /** More than two parents: an octopus merge the forge never makes itself, | |
| 18 | * so reverting one would be a guess about which side is "the" undo. */ | |
| 19 | | { kind: "octopus"; parents: number }; | |
| 20 | ||
| 21 | export interface RevertResult { | |
| 22 | readonly commitOid: string; | |
| 23 | } | |
| 24 | ||
| 25 | /** A commit's parent oids, in order; empty for a root commit. */ | |
| 26 | export async function commitParents( | |
| 27 | dir: string, | |
| 28 | oid: string, | |
| 29 | ): Promise<string[] | undefined> { | |
| 30 | if (!isSafeOid(oid)) return undefined; | |
| 31 | const result = await runGit(["rev-parse", `${oid}^@`], { cwd: dir }); | |
| 32 | if (!result.ok) return undefined; | |
| 33 | return result.value | |
| 34 | .split("\n") | |
| 35 | .map((line) => line.trim()) | |
| 36 | .filter((line) => line !== ""); | |
| 37 | } | |
| 38 | ||
| 39 | /** | |
| 40 | * Build the commit that undoes `commitOid`, staged on top of `ontoOid`. A | |
| 41 | * squash merge (the forge's own default) has one parent, which is exactly | |
| 42 | * the state to restore; an ordinary merge's first parent is the base | |
| 43 | * branch's own side — `git revert -m 1`'s rule, and the only mainline the | |
| 44 | * forge's own merges ever produce, so that is the one used without asking. | |
| 45 | */ | |
| 46 | export async function revertCommit( | |
| 47 | dir: string, | |
| 48 | input: { | |
| 49 | commitOid: string; | |
| 50 | ontoOid: string; | |
| 51 | message: string; | |
| 52 | author: MergeIdentity; | |
| 53 | }, | |
| 54 | ): Promise<Result<RevertResult, RevertError>> { | |
| 55 | if (!isSafeOid(input.commitOid) || !isSafeOid(input.ontoOid)) | |
| 56 | return err({ kind: "unsafe" }); | |
| 57 | ||
| 58 | const parents = await commitParents(dir, input.commitOid); | |
| 59 | if (parents === undefined || parents.length === 0) | |
| 60 | return err({ kind: "git", message: "could not read the change's parent" }); | |
| 61 | if (parents.length > 2) return err({ kind: "octopus", parents: parents.length }); | |
| 62 | const mainline = parents[0]!; | |
| 63 | ||
| 64 | const tree = await writeMergeTree(dir, input.ontoOid, mainline, input.commitOid); | |
| 65 | if (!tree.ok) return tree; | |
| 66 | ||
| 67 | const env = { | |
| 68 | GIT_AUTHOR_NAME: input.author.name, | |
| 69 | GIT_AUTHOR_EMAIL: input.author.email, | |
| 70 | GIT_COMMITTER_NAME: input.author.name, | |
| 71 | GIT_COMMITTER_EMAIL: input.author.email, | |
| 72 | }; | |
| 73 | const commit = await runGit( | |
| 74 | ["commit-tree", tree.value.treeOid, "-p", input.ontoOid, "-m", input.message], | |
| 75 | { cwd: dir, env }, | |
| 76 | ); | |
| 77 | if (!commit.ok) return err({ kind: "git", message: commit.error.stderr }); | |
| 78 | return ok({ commitOid: commit.value.trim() }); | |
| 79 | } |
src/http/server.ts +2
| @@ -80,6 +80,7 @@ import { globalMapPage, mapPage } from "../web/pages/map.ts"; | ||
| 80 | 80 | import { |
| 81 | 81 | asksSubmit, |
| 82 | 82 | modeSubmit, |
| 83 | revertSubmit, | |
| 83 | 84 | saySubmit, |
| 84 | 85 | shipSubmit, |
| 85 | 86 | tellSubmit, |
| @@ -571,6 +572,7 @@ export function buildRouter(): Router<Handler> { | ||
| 571 | 572 | router.add("POST", "/:owner/:name/tell", tellSubmit); |
| 572 | 573 | router.add("POST", "/:owner/:name/pulls/:number/ship", shipSubmit); |
| 573 | 574 | router.add("POST", "/:owner/:name/pulls/:number/say", saySubmit); |
| 575 | router.add("POST", "/:owner/:name/pulls/:number/revert", revertSubmit); | |
| 574 | 576 | // What an issue waits for: link and unlink, from the issue page. |
| 575 | 577 | router.add( |
| 576 | 578 | "POST", |
src/web/pages/search.ts +9
| @@ -466,6 +466,15 @@ const DESTRUCTIVE: { | ||
| 466 | 466 | phrase: "", |
| 467 | 467 | }), |
| 468 | 468 | }, |
| 469 | { | |
| 470 | pattern: /^\/([^/]+)\/([^/]+)\/pulls\/(\d+)\/revert$/, | |
| 471 | describe: (m) => ({ | |
| 472 | verb: "Take it back", | |
| 473 | title: `Take back #${m[3]}?`, | |
| 474 | detail: `Opens a new change that reverts exactly what #${m[3]} shipped — a branch, one revert commit, and a pull that links back to it. ${m[1]}/${m[2]}'s default branch is untouched until someone merges that pull, the same as any other change.`, | |
| 475 | phrase: "", | |
| 476 | }), | |
| 477 | }, | |
| 469 | 478 | { |
| 470 | 479 | pattern: /^\/settings\/crew\/([^/]+)\/delete$/, |
| 471 | 480 | describe: (m) => ({ |
src/web/studio/actions.ts +43
| @@ -11,6 +11,7 @@ | ||
| 11 | 11 | import { addComment, setIssueStateThrough } from "../../actions/issues.ts"; |
| 12 | 12 | import { tellCrew } from "../../actions/crew.ts"; |
| 13 | 13 | import { mergePull } from "../../actions/pulls.ts"; |
| 14 | import { revertPull, type RevertPullError } from "../../actions/revert.ts"; | |
| 14 | 15 | import { getPull } from "../../core/pulls.ts"; |
| 15 | 16 | import { bringUpToDate } from "../../crew/autonomy.ts"; |
| 16 | 17 | import type { Ctx } from "../../http/context.ts"; |
| @@ -107,6 +108,48 @@ export async function shipSubmit(ctx: Ctx): Promise<Response> { | ||
| 107 | 108 | }); |
| 108 | 109 | } |
| 109 | 110 | |
| 111 | /** A take-it-back refusal in a person's words. */ | |
| 112 | function revertWords(error: RevertPullError): string { | |
| 113 | if (typeof error === "string") return error.replace(/_/g, " "); | |
| 114 | switch (error.kind) { | |
| 115 | case "conflict": | |
| 116 | return `it conflicts with the code shipped since — ${error.files.join(", ") || "see the branch"} — nothing was changed`; | |
| 117 | case "git": | |
| 118 | return `git said ${error.message}`; | |
| 119 | case "branch_failed": | |
| 120 | case "pull_failed": | |
| 121 | return error.reason.replace(/_/g, " "); | |
| 122 | default: | |
| 123 | return error.kind.replace(/_/g, " "); | |
| 124 | } | |
| 125 | } | |
| 126 | ||
| 127 | /** POST /:owner/:name/pulls/:number/revert — open a change that undoes a | |
| 128 | * shipped one, exactly the way "Take it back" describes it on the confirm | |
| 129 | * page (`web/pages/search.ts`'s `DESTRUCTIVE` table). */ | |
| 130 | export async function revertSubmit(ctx: Ctx): Promise<Response> { | |
| 131 | const repo = loadRepo(ctx); | |
| 132 | if (!repo) return notFoundPage(ctx); | |
| 133 | if (!ctx.auth.user) return signInFirst(ctx); | |
| 134 | const form = await readForm(ctx, "rw"); | |
| 135 | if (form instanceof Response) return form; | |
| 136 | const base = repoBase(repo); | |
| 137 | const number = Number(ctx.params.number); | |
| 138 | const pull = Number.isInteger(number) | |
| 139 | ? getPull(ctx.app.db, repo.id, number) | |
| 140 | : undefined; | |
| 141 | if (!pull) return notFoundPage(ctx); | |
| 142 | const reverted = await revertPull(ctx.app, ctx.auth.user, repo, pull); | |
| 143 | if (!reverted.ok) | |
| 144 | return flashOrJson(ctx, base, { | |
| 145 | tone: "danger" as const, | |
| 146 | message: `Could not take it back: ${revertWords(reverted.error)}.`, | |
| 147 | }); | |
| 148 | return flashOrJson(ctx, `${base}/pulls/${reverted.value.number}`, { | |
| 149 | message: `Opened #${reverted.value.number} to take back "${pull.title}".`, | |
| 150 | }); | |
| 151 | } | |
| 152 | ||
| 110 | 153 | /** POST /:owner/:name/pulls/:number/say { text } — feedback to the crew. */ |
| 111 | 154 | export async function saySubmit(ctx: Ctx): Promise<Response> { |
| 112 | 155 | const repo = loadRepo(ctx); |
src/web/studio/change.ts +34 −3
| @@ -9,8 +9,8 @@ | ||
| 9 | 9 | |
| 10 | 10 | import { appsRuntime } from "../../apps/runtime.ts"; |
| 11 | 11 | import type { AppRecord } from "../../core/apps.ts"; |
| 12 | import { pullStatus, type Pull } from "../../core/pulls.ts"; | |
| 13 | import type { Repo } from "../../core/repos.ts"; | |
| 12 | import { pullStatus, revertOf, type Pull } from "../../core/pulls.ts"; | |
| 13 | import { canWrite, type Repo } from "../../core/repos.ts"; | |
| 14 | 14 | import { checkSummary } from "../../core/runs.ts"; |
| 15 | 15 | import { repoDir } from "../../git/repos.ts"; |
| 16 | 16 | import type { Ctx } from "../../http/context.ts"; |
| @@ -21,6 +21,7 @@ import { liveClientJs, liveMount } from "../live.ts"; | ||
| 21 | 21 | import { |
| 22 | 22 | btn, |
| 23 | 23 | card, |
| 24 | confirmAction, | |
| 24 | 25 | icon, |
| 25 | 26 | originTag, |
| 26 | 27 | stateBadge, |
| @@ -123,6 +124,17 @@ export async function studioPull( | ||
| 123 | 124 | </div> |
| 124 | 125 | </div>`; |
| 125 | 126 | |
| 127 | // Taking a shipped change back is a person's verb, offered once it has a | |
| 128 | // merge to undo, to whoever could ship it in the first place — never the | |
| 129 | // crew (rule 1, docs/APPS.md), and never twice: a standing revert (open, | |
| 130 | // or already landed) is said plainly rather than offering a second one. | |
| 131 | const revert = pull.mergedAt === null ? undefined : revertOf(db, repo.id, pull.id); | |
| 132 | const mayRevert = | |
| 133 | pull.mergedAt !== null && | |
| 134 | revert === undefined && | |
| 135 | ctx.auth.user?.kind !== "agent" && | |
| 136 | canWrite(db, repo, ctx.auth.user); | |
| 137 | ||
| 126 | 138 | const checkLine = card( |
| 127 | 139 | html`<p class="studio-pull-check"> |
| 128 | 140 | ${wordBadge(word)} <span class="muted small">${note}</span> |
| @@ -134,7 +146,26 @@ export async function studioPull( | ||
| 134 | 146 | >deploy ${d.commitOid.slice(0, 7)}</a |
| 135 | 147 | >`, |
| 136 | 148 | )} |
| 137 | </p>`, | |
| 149 | </p> | |
| 150 | ${when( | |
| 151 | revert, | |
| 152 | (r) => | |
| 153 | html`<p class="muted small mt"> | |
| 154 | Already taken back — | |
| 155 | <a href="${base}/pulls/${r.number}">#${r.number}</a> | |
| 156 | </p>`, | |
| 157 | )} | |
| 158 | ${when( | |
| 159 | mayRevert, | |
| 160 | () => | |
| 161 | html`<div class="bar mt"> | |
| 162 | ${confirmAction({ | |
| 163 | action: `${thread}/revert`, | |
| 164 | verb: "Take it back", | |
| 165 | size: "sm", | |
| 166 | })} | |
| 167 | </div>`, | |
| 168 | )}`, | |
| 138 | 169 | ); |
| 139 | 170 | |
| 140 | 171 | // A conflicted change never offers Ship as though it would work — pressing |
test/revert.test.ts added +218
| @@ -0,0 +1,218 @@ | ||
| 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 { createApp, type App } from "../src/app.ts"; | |
| 6 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 7 | ||
| 8 | const gitEnv = { | |
| 9 | ...process.env, | |
| 10 | GIT_AUTHOR_NAME: "Dev", | |
| 11 | GIT_AUTHOR_EMAIL: "[email protected]", | |
| 12 | GIT_COMMITTER_NAME: "Dev", | |
| 13 | GIT_COMMITTER_EMAIL: "[email protected]", | |
| 14 | GIT_TERMINAL_PROMPT: "0", | |
| 15 | GIT_CONFIG_GLOBAL: "/dev/null", | |
| 16 | GIT_CONFIG_SYSTEM: "/dev/null", | |
| 17 | }; | |
| 18 | ||
| 19 | describe("take it back: reverting a shipped change", () => { | |
| 20 | let dataDir: string; | |
| 21 | let work: string; | |
| 22 | let app: App; | |
| 23 | let servers: Servers; | |
| 24 | let base: string; | |
| 25 | let cookie = ""; | |
| 26 | let token = ""; | |
| 27 | let repoDirPath: string; | |
| 28 | ||
| 29 | async function git( | |
| 30 | args: string[], | |
| 31 | cwd: string, | |
| 32 | ): Promise<{ code: number; err: string }> { | |
| 33 | const p = Bun.spawn(["git", ...args], { | |
| 34 | cwd, | |
| 35 | env: gitEnv, | |
| 36 | stdout: "ignore", | |
| 37 | stderr: "pipe", | |
| 38 | }); | |
| 39 | const [err, code] = await Promise.all([ | |
| 40 | new Response(p.stderr).text(), | |
| 41 | p.exited, | |
| 42 | ]); | |
| 43 | return { code, err }; | |
| 44 | } | |
| 45 | async function gitOk(args: string[], cwd: string): Promise<void> { | |
| 46 | const r = await git(args, cwd); | |
| 47 | if (r.code !== 0) throw new Error(`git ${args.join(" ")}: ${r.err}`); | |
| 48 | } | |
| 49 | ||
| 50 | const form = (fields: Record<string, string>) => new URLSearchParams(fields); | |
| 51 | const post = (path: string, fields: Record<string, string> = {}, accept?: string) => | |
| 52 | fetch(`${base}${path}`, { | |
| 53 | method: "POST", | |
| 54 | headers: { cookie, ...(accept === undefined ? {} : { accept }) }, | |
| 55 | body: form(fields), | |
| 56 | redirect: "manual", | |
| 57 | }); | |
| 58 | ||
| 59 | const branchExists = async (name: string): Promise<boolean> => { | |
| 60 | const r = await Bun.spawn( | |
| 61 | ["git", "rev-parse", "--verify", `refs/heads/${name}`], | |
| 62 | { cwd: repoDirPath, env: gitEnv, stdout: "ignore", stderr: "ignore" }, | |
| 63 | ).exited; | |
| 64 | return r === 0; | |
| 65 | }; | |
| 66 | ||
| 67 | const blobOnMain = async (): Promise<string> => | |
| 68 | (await fetch(`${base}/dev/app/blob/main/code.txt`)).text(); | |
| 69 | ||
| 70 | beforeAll(async () => { | |
| 71 | dataDir = await mkdtemp(join(tmpdir(), "forge-revert-")); | |
| 72 | work = await mkdtemp(join(tmpdir(), "forge-revert-work-")); | |
| 73 | app = createApp({ dataDir, port: 0 }); | |
| 74 | servers = await serve(app); | |
| 75 | base = servers.url; | |
| 76 | ||
| 77 | const signup = await fetch(`${base}/signup`, { | |
| 78 | method: "POST", | |
| 79 | body: form({ | |
| 80 | username: "dev", | |
| 81 | email: "[email protected]", | |
| 82 | password: "take-it-back-pass", | |
| 83 | }), | |
| 84 | redirect: "manual", | |
| 85 | }); | |
| 86 | cookie = (signup.headers.get("set-cookie") ?? "").split(";")[0]!; | |
| 87 | token = await fetch(`${base}/api/v1/tokens`, { | |
| 88 | method: "POST", | |
| 89 | headers: { "content-type": "application/json" }, | |
| 90 | body: JSON.stringify({ | |
| 91 | username: "dev", | |
| 92 | password: "take-it-back-pass", | |
| 93 | name: "cli", | |
| 94 | scope: "rw", | |
| 95 | }), | |
| 96 | }) | |
| 97 | .then((r) => r.json()) | |
| 98 | .then((j) => (j as { token: string }).token); | |
| 99 | await fetch(`${base}/api/v1/repos`, { | |
| 100 | method: "POST", | |
| 101 | headers: { | |
| 102 | authorization: `Bearer ${token}`, | |
| 103 | "content-type": "application/json", | |
| 104 | }, | |
| 105 | body: JSON.stringify({ name: "app", visibility: "public" }), | |
| 106 | }); | |
| 107 | repoDirPath = join(dataDir, "repos/dev/app.git"); | |
| 108 | ||
| 109 | const remote = `${base.replace("http://", `http://dev:${token}@`)}/dev/app.git`; | |
| 110 | await gitOk(["clone", remote, "app"], work); | |
| 111 | const dir = join(work, "app"); | |
| 112 | await Bun.write(join(dir, "code.txt"), "alpha\n"); | |
| 113 | await gitOk(["add", "."], dir); | |
| 114 | await gitOk(["commit", "-m", "base"], dir); | |
| 115 | await gitOk(["push", "origin", "main"], dir); | |
| 116 | }); | |
| 117 | ||
| 118 | afterAll(async () => { | |
| 119 | servers.stop(); | |
| 120 | app.close(); | |
| 121 | await rm(dataDir, { recursive: true, force: true }); | |
| 122 | await rm(work, { recursive: true, force: true }); | |
| 123 | }); | |
| 124 | ||
| 125 | test("ship a change, take it back: the new pull reverts the file, and main stays put until it merges", async () => { | |
| 126 | const dir = join(work, "app"); | |
| 127 | await gitOk(["checkout", "-b", "loud"], dir); | |
| 128 | await Bun.write(join(dir, "code.txt"), "alpha\nBETA\n"); | |
| 129 | await gitOk(["commit", "-am", "shout"], dir); | |
| 130 | await gitOk(["push", "origin", "loud"], dir); | |
| 131 | ||
| 132 | const opened = await post("/dev/app/pulls/new", { | |
| 133 | base: "main", | |
| 134 | head: "loud", | |
| 135 | title: "Make it loud", | |
| 136 | body: "", | |
| 137 | }); | |
| 138 | expect(opened.headers.get("location")).toBe("/dev/app/pulls/1"); | |
| 139 | const shipped = await post("/dev/app/pulls/1/merge", { strategy: "squash" }); | |
| 140 | expect(shipped.status).toBe(303); | |
| 141 | expect(await blobOnMain()).toBe("alpha\nBETA\n"); | |
| 142 | ||
| 143 | // A test fails on today's code up to here — the assertions below are | |
| 144 | // what "Take it back" adds. | |
| 145 | const taken = await post("/dev/app/pulls/1/revert"); | |
| 146 | expect(taken.status).toBe(303); | |
| 147 | expect(taken.headers.get("location")).toBe("/dev/app/pulls/2"); | |
| 148 | ||
| 149 | // main is untouched until a person merges the revert pull. | |
| 150 | expect(await blobOnMain()).toBe("alpha\nBETA\n"); | |
| 151 | ||
| 152 | const revertPage = await (await fetch(`${base}/dev/app/pulls/2`)).text(); | |
| 153 | expect(revertPage).toContain('Revert "Make it loud"'); | |
| 154 | expect(revertPage).toContain("Reverts #1"); | |
| 155 | ||
| 156 | const landed = await post("/dev/app/pulls/2/merge", { strategy: "squash" }); | |
| 157 | expect(landed.status).toBe(303); | |
| 158 | expect(await blobOnMain()).toBe("alpha\n"); | |
| 159 | }); | |
| 160 | ||
| 161 | test("a change already taken back offers the honest word, not a second inverse", async () => { | |
| 162 | const again = await post("/dev/app/pulls/1/revert", {}, "application/json"); | |
| 163 | expect(again.status).toBe(422); | |
| 164 | const body = (await again.json()) as { ok: boolean; error: string }; | |
| 165 | expect(body.ok).toBe(false); | |
| 166 | expect(body.error).toContain("already reverted"); | |
| 167 | }); | |
| 168 | ||
| 169 | test("a revert that does not apply cleanly changes nothing and leaves no branch behind", async () => { | |
| 170 | const dir = join(work, "app"); | |
| 171 | await gitOk(["checkout", "main"], dir); | |
| 172 | await gitOk(["pull", "origin", "main"], dir); | |
| 173 | await gitOk(["checkout", "-b", "gamma"], dir); | |
| 174 | await Bun.write(join(dir, "code.txt"), "alpha\nGAMMA\n"); | |
| 175 | await gitOk(["commit", "-am", "gamma"], dir); | |
| 176 | await gitOk(["push", "origin", "gamma"], dir); | |
| 177 | const opened = await post("/dev/app/pulls/new", { | |
| 178 | base: "main", | |
| 179 | head: "gamma", | |
| 180 | title: "Add gamma", | |
| 181 | body: "", | |
| 182 | }); | |
| 183 | const loc = opened.headers.get("location")!; | |
| 184 | await post(`${loc}/merge`, { strategy: "squash" }); | |
| 185 | expect(await blobOnMain()).toBe("alpha\nGAMMA\n"); | |
| 186 | ||
| 187 | // Now change the very same line again, so undoing "Add gamma" can no | |
| 188 | // longer apply without a conflict. | |
| 189 | await gitOk(["checkout", "main"], dir); | |
| 190 | await gitOk(["pull", "origin", "main"], dir); | |
| 191 | await gitOk(["checkout", "-b", "delta"], dir); | |
| 192 | await Bun.write(join(dir, "code.txt"), "alpha\nDELTA\n"); | |
| 193 | await gitOk(["commit", "-am", "delta"], dir); | |
| 194 | await gitOk(["push", "origin", "delta"], dir); | |
| 195 | const secondOpen = await post("/dev/app/pulls/new", { | |
| 196 | base: "main", | |
| 197 | head: "delta", | |
| 198 | title: "Change it again", | |
| 199 | body: "", | |
| 200 | }); | |
| 201 | const secondLoc = secondOpen.headers.get("location")!; | |
| 202 | await post(`${secondLoc}/merge`, { strategy: "squash" }); | |
| 203 | expect(await blobOnMain()).toBe("alpha\nDELTA\n"); | |
| 204 | ||
| 205 | const number = loc.split("/").pop()!; | |
| 206 | const refused = await post( | |
| 207 | `/dev/app/pulls/${number}/revert`, | |
| 208 | {}, | |
| 209 | "application/json", | |
| 210 | ); | |
| 211 | expect(refused.status).toBe(422); | |
| 212 | const body = (await refused.json()) as { ok: boolean; error: string }; | |
| 213 | expect(body.ok).toBe(false); | |
| 214 | expect(body.error).toContain("conflicts"); | |
| 215 | expect(await blobOnMain()).toBe("alpha\nDELTA\n"); | |
| 216 | expect(await branchExists(`revert-${number}`)).toBe(false); | |
| 217 | }); | |
| 218 | }); |
new above
offline