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

githubStackRebase.ts

152 lines6.0 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 GitHubAppAccess from "./GitHubAppAccess.ts";
8import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
9​
10export interface CascadeLayer {
11 readonly number: number;
12 readonly headBranch: string;
13 readonly headSha: string;
15​
16export class GitHubStackRebaseConflictError extends Schema.TaggedError<GitHubStackRebaseConflictError>()(
17 "GitHubStackRebaseConflictError",
18 { number: Schema.Int, completed: Schema.Int },
19) {
20 override get message(): string {
21 return `PR #${this.number} conflicts with the layer below it. ${this.completed} layers were rebased; resolve #${this.number} with \`gh stack rebase\` and push.`;
22 }
24​
25export class GitHubStackRebaseGitError extends Schema.TaggedError<GitHubStackRebaseGitError>()(
26 "GitHubStackRebaseGitError",
27 { step: Schema.String, number: Schema.Int, completed: Schema.Int, cause: Schema.Defect() },
28) {
29 override get message(): string {
30 return `Stack rebase stopped at PR #${this.number} while ${this.step}. ${this.completed} layers were rebased.`;
31 }
33​
34function remoteUrl(host: string, repository: string): string {
35 return `https://${host.trim().toLowerCase()}/${repository}.git`;
37​
38export const cascadeRebaseStack = Effect.fn("cascadeRebaseStack")(function* (input: {
39 readonly cwd: string;
40 readonly host: string;
41 readonly repository: string;
42 readonly base: string;
43 readonly layers: ReadonlyArray<CascadeLayer>;
44 /** Last head of the merged layer directly below the bottom open layer. */
45 readonly mergedHeadSha?: string;
46 readonly remote?: string;
47}) {
48 const appAccess = yield* GitHubAppAccess.GitHubAppAccess;
49 const { process } = yield* SourceControlHost.SourceControlHost;
50 const fileSystem = yield* FileSystem.FileSystem;
51 // A push takes one credential up front, so it must be one that reaches the repository.
52 const { token } = yield* appAccess.credentialFor(input.host, input.repository, input.cwd);
53 const first = input.layers[0];
54 if (first === undefined) return 0;
55 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-stack-rebase-" }).pipe(
56 Effect.mapError(
57 (cause) =>
58 new GitHubStackRebaseGitError({
59 step: "preparing",
60 number: first.number,
61 completed: 0,
62 cause,
63 }),
64 ),
65 );
66 // Keep the token in this process's header, outside URLs, argv and git config.
67 const remote = input.remote ?? remoteUrl(input.host, input.repository);
68 const authorization = `AUTHORIZATION: basic ${Base64.encode(`x-access-token:${Redacted.value(token)}`)}`;
69 const env = {
70 GIT_TERMINAL_PROMPT: "0",
71 GIT_CONFIG_COUNT: "3",
72 GIT_CONFIG_KEY_0: `http.${remote}.extraheader`,
73 GIT_CONFIG_VALUE_0: authorization,
74 GIT_CONFIG_KEY_1: "user.name",
75 GIT_CONFIG_VALUE_1: "T3 Code",
76 GIT_CONFIG_KEY_2: "user.email",
77 GIT_CONFIG_VALUE_2: "noreply@t3.codes",
78 };
79 const git = (args: ReadonlyArray<string>, allowNonZeroExit = false) =>
80 process.run({
81 operation: "cascadeRebaseStack",
82 command: "git",
83 args,
84 cwd: directory,
85 env,
86 timeoutMs: 120_000,
87 ...(allowNonZeroExit ? { allowNonZeroExit: true } : {}),
88 });
89 const failed = (step: string, number: number, completed: number) => (cause: unknown) =>
90 new GitHubStackRebaseGitError({ step, number, completed, cause });
91​
92 yield* git(["init", "--quiet"]).pipe(Effect.mapError(failed("preparing", first.number, 0)));
93 yield* git(["remote", "add", "origin", remote]).pipe(
94 Effect.mapError(failed("preparing", first.number, 0)),
95 );
96 yield* git([
97 "fetch",
98 "--quiet",
99 "--no-tags",
100 "origin",
101 `+refs/heads/${input.base}:refs/remotes/origin/${input.base}`,
102 ...input.layers.map(
103 (layer) => `+refs/heads/${layer.headBranch}:refs/remotes/origin/${layer.headBranch}`,
104 ),
105 ]).pipe(Effect.mapError(failed("fetching", first.number, 0)));
106​
107 let parentOld = `origin/${input.base}`;
108 let parentNew = `origin/${input.base}`;
109 // A squash or rebase merge leaves the merged layer's commits outside the base's history.
110 const mergedParent =
111 input.mergedHeadSha !== undefined &&
112 (yield* git(["merge-base", "--is-ancestor", input.mergedHeadSha, first.headSha], true).pipe(
113 Effect.mapError(failed("reading the fork point", first.number, 0)),
114 )).exitCode === 0
115 ? input.mergedHeadSha
116 : undefined;
117 for (const [index, layer] of input.layers.entries()) {
118 // Exclude old parents: the merged layer or fork point for the bottom, the reviewed head above.
119 const upstream =
120 index === 0
121 ? (mergedParent ??
122 (yield* git(["merge-base", parentOld, layer.headSha]).pipe(
123 Effect.mapError(failed("reading the fork point", layer.number, index)),
124 )).stdout.trim())
125 : parentOld;
126 yield* git(["checkout", "--quiet", "--detach", layer.headSha]).pipe(
127 Effect.mapError(failed("checking out", layer.number, index)),
128 );
129 const rebase = yield* git(["rebase", "--quiet", "--onto", parentNew, upstream], true).pipe(
130 Effect.mapError(failed("rebasing", layer.number, index)),
131 );
132 if (rebase.exitCode !== 0) {
133 yield* git(["rebase", "--abort"], true).pipe(Effect.ignore);
134 return yield* new GitHubStackRebaseConflictError({ number: layer.number, completed: index });
135 }
136 const rebased = (yield* git(["rev-parse", "HEAD"]).pipe(
137 Effect.mapError(failed("rebasing", layer.number, index)),
138 )).stdout.trim();
139 if (rebased !== layer.headSha) {
140 yield* git([
141 "push",
142 "--quiet",
143 `--force-with-lease=refs/heads/${layer.headBranch}:${layer.headSha}`,
144 "origin",
145 `${rebased}:refs/heads/${layer.headBranch}`,
146 ]).pipe(Effect.mapError(failed("pushing", layer.number, index)));
147 }
148 parentOld = layer.headSha;
149 parentNew = rebased;
150 }
151 return input.layers.length;
152}, Effect.scoped);