Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

githubStackRebase.ts

157 lines6.6 KB

1import * as Effect from "effect/Effect";
2import * as FileSystem from "effect/FileSystem";
3import * as Redacted from "effect/Redacted";
4import * as Schema from "effect/Schema";
5import * as Base64 from "effect/encoding/Base64";
6​
7import * as GitHubApi from "../sourceControl/GitHubApi.ts";
8import * as VcsProcess from "../vcs/VcsProcess.ts";
9​
10/** One open layer of a stack, bottom to top, with the head the reader reviewed. */
11export interface CascadeLayer {
12 readonly number: number;
13 readonly headBranch: string;
14 readonly headSha: string;
16​
17/** A layer's rebase hit a conflict; the layers below it are already rebased on GitHub. */
18export class GitHubStackRebaseConflictError extends Schema.TaggedError<GitHubStackRebaseConflictError>()(
19 "GitHubStackRebaseConflictError",
20 { number: Schema.Int, completed: Schema.Int },
21) {
22 override get message(): string {
23 return `PR #${this.number} conflicts with the layer below it. ${this.completed} layers were rebased; resolve #${this.number} with \`gh stack rebase\` and push.`;
24 }
26​
27/** Git failed for a reason other than a conflict: the fetch, or a push GitHub refused. */
28export class GitHubStackRebaseGitError extends Schema.TaggedError<GitHubStackRebaseGitError>()(
29 "GitHubStackRebaseGitError",
30 { step: Schema.String, number: Schema.Int, completed: Schema.Int, cause: Schema.Defect() },
31) {
32 override get message(): string {
33 return `Stack rebase stopped at PR #${this.number} while ${this.step}. ${this.completed} layers were rebased.`;
34 }
36​
37/** The git URL of a repository on a GitHub host, which is also where its token is good. */
38function remoteUrl(host: string, repository: string): string {
39 return `https://${host.trim().toLowerCase()}/${repository}.git`;
41​
42/**
43 * GitHub's own "Rebase stack": every open layer, bottom to top, onto the new head of the layer
44 * below it (the bottom one onto the stack's base). Each layer moves only its own commits —
45 * `git rebase --onto <new parent> <old parent>` — so a rebased lower layer is never replayed into
46 * the one above it, which is what GitHub's per-PR "update branch" does and why it conflicts.
47 *
48 * It works in a throwaway clone, so the environment's checkout never moves, and pushes each
49 * layer with a lease on the head that was reviewed, so a push that landed meanwhile is refused
50 * rather than overwritten. The stacks API has no rebase endpoint to call instead.
51 */
52export const cascadeRebaseStack = Effect.fn("cascadeRebaseStack")(function* (input: {
53 readonly host: string;
54 readonly repository: string;
55 readonly base: string;
56 readonly layers: ReadonlyArray<CascadeLayer>;
57 /** Where to fetch and push; the repository's own URL on its host unless a test points elsewhere. */
58 readonly remote?: string;
59}) {
60 const api = yield* GitHubApi.GitHubApi;
61 const process = yield* VcsProcess.VcsProcess;
62 const fileSystem = yield* FileSystem.FileSystem;
63 // Fetching and pushing below act on the repository's own remote, so the token must belong to the
64 // account that owns it rather than to whichever login `gh` has active.
65 const { token } = yield* api.credential(input.host, input.repository.split("/")[0] ?? "");
66 const first = input.layers[0];
67 if (first === undefined) return 0;
68 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-stack-rebase-" }).pipe(
69 Effect.mapError(
70 (cause) =>
71 new GitHubStackRebaseGitError({
72 step: "preparing",
73 number: first.number,
74 completed: 0,
75 cause,
76 }),
77 ),
78 );
79 // The token rides in a header for this process only: never in the URL, argv, or git config.
80 const remote = input.remote ?? remoteUrl(input.host, input.repository);
81 const authorization = `AUTHORIZATION: basic ${Base64.encode(`x-access-token:${Redacted.value(token)}`)}`;
82 const env = {
83 GIT_TERMINAL_PROMPT: "0",
84 GIT_CONFIG_COUNT: "3",
85 GIT_CONFIG_KEY_0: `http.${remote}.extraheader`,
86 GIT_CONFIG_VALUE_0: authorization,
87 GIT_CONFIG_KEY_1: "user.name",
88 GIT_CONFIG_VALUE_1: "T3 Code",
89 GIT_CONFIG_KEY_2: "user.email",
90 GIT_CONFIG_VALUE_2: "noreply@t3.codes",
91 };
92 const git = (args: ReadonlyArray<string>, allowNonZeroExit = false) =>
93 process.run({
94 operation: "cascadeRebaseStack",
95 command: "git",
96 args,
97 cwd: directory,
98 env,
99 timeoutMs: 120_000,
100 ...(allowNonZeroExit ? { allowNonZeroExit: true } : {}),
101 });
102 const failed = (step: string, number: number, completed: number) => (cause: unknown) =>
103 new GitHubStackRebaseGitError({ step, number, completed, cause });
104​
105 yield* git(["init", "--quiet"]).pipe(Effect.mapError(failed("preparing", first.number, 0)));
106 yield* git(["remote", "add", "origin", remote]).pipe(
107 Effect.mapError(failed("preparing", first.number, 0)),
108 );
109 yield* git([
110 "fetch",
111 "--quiet",
112 "--no-tags",
113 "origin",
114 `+refs/heads/${input.base}:refs/remotes/origin/${input.base}`,
115 ...input.layers.map(
116 (layer) => `+refs/heads/${layer.headBranch}:refs/remotes/origin/${layer.headBranch}`,
117 ),
118 ]).pipe(Effect.mapError(failed("fetching", first.number, 0)));
119​
120 let parentOld = `origin/${input.base}`;
121 let parentNew = `origin/${input.base}`;
122 for (const [index, layer] of input.layers.entries()) {
123 // The bottom layer's old parent is where it forked from the base; above that it is the
124 // reviewed head of the layer below, which is exactly the commits this layer must not replay.
125 const upstream =
126 index === 0
127 ? (yield* git(["merge-base", parentOld, layer.headSha]).pipe(
128 Effect.mapError(failed("reading the fork point", layer.number, index)),
129 )).stdout.trim()
130 : parentOld;
131 yield* git(["checkout", "--quiet", "--detach", layer.headSha]).pipe(
132 Effect.mapError(failed("checking out", layer.number, index)),
133 );
134 const rebase = yield* git(["rebase", "--quiet", "--onto", parentNew, upstream], true).pipe(
135 Effect.mapError(failed("rebasing", layer.number, index)),
136 );
137 if (rebase.exitCode !== 0) {
138 yield* git(["rebase", "--abort"], true).pipe(Effect.ignore);
139 return yield* new GitHubStackRebaseConflictError({ number: layer.number, completed: index });
140 }
141 const rebased = (yield* git(["rev-parse", "HEAD"]).pipe(
142 Effect.mapError(failed("rebasing", layer.number, index)),
143 )).stdout.trim();
144 if (rebased !== layer.headSha) {
145 yield* git([
146 "push",
147 "--quiet",
148 `--force-with-lease=refs/heads/${layer.headBranch}:${layer.headSha}`,
149 "origin",
150 `${rebased}:refs/heads/${layer.headBranch}`,
151 ]).pipe(Effect.mapError(failed("pushing", layer.number, index)));
152 }
153 parentOld = layer.headSha;
154 parentNew = rebased;
155 }
156 return input.layers.length;
157}, Effect.scoped);