git / pulls.tsmain at 517348b
// pulls.ts — WHAT A PULL IS: a branch that someone asks to have squashed into `main`, with a
// title, a body and a conversation.
//
// A REPO'S PULLS ARE EVENTS ON THE REPO'S OWN CONTEXT (/repos/<name>), beside the repo's own
// (`repo/pushed`, `repo/commit-completed`). Nothing else holds them:
//
// pull/opened { branch, title, body }
// pull/edited { pull, title, body }
// pull/commented { pull, body, replyTo, at } at: { path, side, line, endLine, quote }, or null
// pull/resolved { pull, comment }
// pull/merged { pull, commitOid }
// pull/closed { pull }
//
// A PULL'S NUMBER IS ITS PLACE AMONG THE `pull/opened` EVENTS: the seventh one is #7. The log's
// order decides, so nothing hands numbers out. A COMMENT'S ID IS ITS EVENT'S OFFSET: `replyTo`
// and `comment` name offsets. WHO AND WHEN are the event's own (`source.principal`, `createdAt`),
// which the platform stamps and no writer can set.
//
// To open a pull, to comment or to close one is one append to the repo's context, by a member's
// page or by an agent:
//
// itx.cd("/repos/git").append({ type: "pull/commented", payload: { pull: 7, body, replyTo: null, at: null } })
//
// TO MERGE IS THE ONE CALL (`mergePull`, which the mind's API offers as `itx.config.pullMerge`).
// A pull is squashed: one commit on main with the branch's files, named `<title> (#7)` with the
// body under it. It is taken only while the branch has main's newest commit in its history, so
// no two changes are ever woven together here: when main has moved, merge main into the branch
// and push. Main is then a straight line, each commit one pull.
import type { RepoLogEntry } from "iterate/api";
import type { IterateConfigEntrypoint } from "iterate/sdk";
import type { StreamEvent } from "iterate/stream/processor";
import { z } from "zod";
type Itx = ReturnType<IterateConfigEntrypoint["getItx"]>;
type Repo = ReturnType<Itx["repos"]["get"]>;
type Files = Awaited<ReturnType<Repo["files"]>>;
/** Where a comment on lines is: the file, the side of the diff, the first line's number on that
* side and the last one's (`endLine`, which a comment on one line may leave out), and the text
* of those lines when the comment was written. The comment stays on its lines while they still
* read so. */
const LinePlace = z
.object({
path: z.string().min(1),
side: z.enum(["additions", "deletions"]),
line: z.number().int().positive(),
endLine: z.number().int().positive().optional(),
quote: z.string(),
})
.transform((place) => ({ ...place, endLine: Math.max(place.endLine || place.line, place.line) }));
export type LinePlace = z.infer<typeof LinePlace>;
const Opened = z.object({ branch: z.string().min(1), title: z.string().min(1), body: z.string() });
const Edited = z.object({ pull: z.number(), title: z.string().min(1), body: z.string() });
const Commented = z.object({
pull: z.number(),
body: z.string().min(1),
replyTo: z.number().nullable(),
at: LinePlace.nullable(),
});
const Resolved = z.object({ pull: z.number(), comment: z.number() });
const Merged = z.object({ pull: z.number(), commitOid: z.string().regex(/^[0-9a-f]{40}$/) });
const Closed = z.object({ pull: z.number() });
export type PullComment = { id: number; by: string; at: string; body: string };
/** A comment and the replies to it. `place` is there for a comment on a line. */
export type PullThread = {
id: number;
place: LinePlace | null;
resolved: boolean;
comments: PullComment[];
};
export type Pull = {
number: number;
branch: string;
title: string;
body: string;
/** Who opened it, as a page shows them, and as git names an author. */
by: string;
author: { name: string; email: string } | null;
openedAt: string;
status: "open" | "merged" | "closed";
/** When it was merged or closed, and who did it: null while it is open, and `doneBy` also
* when code did it with nobody behind. */
doneAt: string | null;
doneBy: string | null;
/** The commit on main that a merged pull became. */
commitOid: string | null;
threads: PullThread[];
};
/** The person behind an event, as a page shows them: the name before the `@` of their address.
* They wrote it themselves, or code wrote it for them. Null for code with nobody behind it. */
function personOf(event: Pick<StreamEvent, "source">): string | null {
const person = event.source.principal || event.source.onBehalfOf?.principal;
return person?.email?.split("@")[0] || person?.name || null;
}
/** Who wrote an event: the person behind it, or for code with nobody behind it the context it
* ran in. */
export const writerOf = (event: Pick<StreamEvent, "source">) =>
personOf(event) || event.source.origin;
/** THE PULLS THAT A REPO'S EVENTS MAKE, oldest first. An event that is no pull's, or whose
* payload does not parse, changes nothing. */
export function pullsOf(events: StreamEvent[]): Pull[] {
const pulls: Pull[] = [];
const open = (number: number) => pulls.find((pull) => pull.number === number);
for (const event of events) {
const payload = event.payload || {};
if (event.type === "pull/opened") {
const opened = Opened.safeParse(payload);
if (!opened.success) continue;
const person = event.source.principal || event.source.onBehalfOf?.principal;
pulls.push({
...opened.data,
number: pulls.length + 1,
by: writerOf(event),
author: person?.email ? { name: writerOf(event), email: person.email } : null,
openedAt: event.createdAt,
status: "open",
doneAt: null,
doneBy: null,
commitOid: null,
threads: [],
});
} else if (event.type === "pull/edited") {
const edited = Edited.safeParse(payload);
const pull = edited.success ? open(edited.data.pull) : undefined;
if (pull && edited.success) Object.assign(pull, { title: edited.data.title, body: edited.data.body });
} else if (event.type === "pull/commented") {
const commented = Commented.safeParse(payload);
const pull = commented.success ? open(commented.data.pull) : undefined;
if (!pull || !commented.success) continue;
const comment = { id: event.offset, by: writerOf(event), at: event.createdAt, body: commented.data.body };
const thread = pull.threads.find(({ id }) => id === commented.data.replyTo);
if (thread) thread.comments.push(comment);
else pull.threads.push({ id: event.offset, place: commented.data.at, resolved: false, comments: [comment] });
} else if (event.type === "pull/resolved") {
const resolved = Resolved.safeParse(payload);
const pull = resolved.success ? open(resolved.data.pull) : undefined;
const thread = pull?.threads.find(({ id }) => resolved.success && id === resolved.data.comment);
if (thread) thread.resolved = true;
} else if (event.type === "pull/merged") {
const merged = Merged.safeParse(payload);
const pull = merged.success ? open(merged.data.pull) : undefined;
const done = { doneAt: event.createdAt, doneBy: personOf(event) };
if (pull?.status === "open" && merged.success)
Object.assign(pull, { status: "merged", commitOid: merged.data.commitOid, ...done });
} else if (event.type === "pull/closed") {
const closed = Closed.safeParse(payload);
const pull = closed.success ? open(closed.data.pull) : undefined;
if (pull?.status === "open")
Object.assign(pull, { status: "closed", doneAt: event.createdAt, doneBy: personOf(event) });
}
}
return pulls;
}
/** The repo's pulls, read from its context's whole log. */
export async function pullsIn(itx: Itx, repo: string): Promise<Pull[]> {
const events: StreamEvent[] = [];
let after = 0;
for (;;) {
const page = await itx.cd(repo).readEvents(after, 1000);
events.push(...page.events);
if (page.atHead) return pullsOf(events);
after = page.scannedThroughOffset;
}
}
/** How far back the two histories are read to find where a branch stands. */
const HISTORY_READ = 300;
/** WHERE A BRANCH STANDS ON MAIN. `head` is its newest commit, `own` the commits that are its
* own (newest first), and `base` the newest commit of main that it has in its history: where it
* left main, or the commit of main it last merged in. `upToDate` says that `base` is main's
* newest, which is what a squash asks for. `head` is null for a branch the repo has not got, and
* `base` when the two share no commit in the history read. */
export type Standing = {
head: string | null;
mainTip: string | null;
base: string | null;
own: RepoLogEntry[];
upToDate: boolean;
};
export async function standingOf(handle: Repo, branch: string): Promise<Standing> {
const head = (await handle.branches()).find(({ name }) => name === branch)?.commitOid || null;
const main = await handle.log({ limit: HISTORY_READ });
const mainTip = main[0]?.oid || null;
if (!head) return { head, mainTip, base: null, own: [], upToDate: false };
return { head, mainTip, ...baseOf(main, await handle.log({ limit: HISTORY_READ, from: head })) };
}
/** `main` and `branch` are each a history, newest first, along first parents. Main is a straight
* line, so a commit of main reaches a branch in two ways alone: the branch began at it, or the
* branch merged it in, where it is a merge's second parent. The newest of those is the base. */
export function baseOf(main: RepoLogEntry[], branch: RepoLogEntry[]) {
const placeOnMain = new Map(main.map(({ oid }, index) => [oid, index]));
const own: RepoLogEntry[] = [];
const reached: number[] = [];
for (const commit of branch) {
const place = placeOnMain.get(commit.oid);
// the commit where the branch began: everything older is main's own
if (place !== undefined) {
reached.push(place);
break;
}
own.push(commit);
for (const merged of commit.parents.slice(1)) {
const mergedAt = placeOnMain.get(merged);
if (mergedAt !== undefined) reached.push(mergedAt);
}
}
const newest = reached.length ? Math.min(...reached) : null;
return { base: newest === null ? null : main[newest]!.oid, own, upToDate: newest === 0 };
}
/** The message of the commit that a pull becomes: `Make the header red (#7)`, then the body. */
export const squashMessage = (pull: Pick<Pull, "number" | "title" | "body">) =>
`${pull.title} (#${pull.number})\n\n${pull.body.trim()}`.trim() + "\n";
/** SQUASH A PULL INTO MAIN: one commit on main that makes main's files the branch's, then the
* `pull/merged` event that says so. It throws, in words for the person who asked, when the pull
* is not open, its branch is gone, or main has moved past what the branch has. */
export async function mergePull(itx: Itx, repo: string, number: number) {
const pull = (await pullsIn(itx, repo)).find((pull) => pull.number === number);
if (!pull) throw new Error(`${repo} has no pull #${number}`);
if (pull.status !== "open") throw new Error(`#${number} is ${pull.status} already`);
const handle = itx.repos.get(repo);
const { head, mainTip, upToDate } = await standingOf(handle, pull.branch);
if (!head) throw new Error(`the branch ${pull.branch} is gone`);
if (!upToDate || !mainTip)
throw new Error(
`main has moved since ${pull.branch} last had it: merge main into ${pull.branch}, push, and merge again`,
);
const changes = fileChanges(
await handle.files({ commitOid: mainTip }),
await handle.files({ commitOid: head }),
);
if (changes.length === 0) throw new Error(`${pull.branch} changes nothing on main`);
const { commitOid } = await handle.commitFiles({
message: squashMessage(pull),
changes,
// refused if main moved while this was read
parent: mainTip,
...(pull.author && { author: pull.author }),
});
if (!commitOid) throw new Error("the commit was not made");
await itx.cd(repo).append({
type: "pull/merged",
// one pull is merged once: a second try of this call lands no second event
idempotencyKey: `pull/merged:${number}`,
payload: { pull: number, commitOid },
});
return { commitOid };
}
/** What a commit must change to turn the files `before` into the files `after`. */
function fileChanges(before: Files, after: Files) {
const changes: Parameters<Repo["commitFiles"]>[0]["changes"] = [];
for (const path of Object.keys({ ...before, ...after }).sort()) {
const was = Object.hasOwn(before, path) ? before[path]! : null;
const is = Object.hasOwn(after, path) ? after[path]! : null;
if (is === null) changes.push({ path, delete: true });
else if (typeof is === "string") {
if (was !== is) changes.push({ path, content: is });
} else if (was === null || typeof was === "string" || was.base64 !== is.base64)
changes.push({ path, bytes: Uint8Array.from(atob(is.base64), (c) => c.charCodeAt(0)) });
}
return changes;
}