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

githubStackRebase.ts

139 lines5.3 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 GitHubRest from "./GitHubRest.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 host: string;
40 readonly repository: string;
41 readonly base: string;
42 readonly layers: ReadonlyArray<CascadeLayer>;
43 readonly remote?: string;
44}) {
45 const api = yield* GitHubRest.GitHubRest;
46 const { process } = yield* SourceControlHost.SourceControlHost;
47 const fileSystem = yield* FileSystem.FileSystem;
48 const { token } = yield* api.credential(input.host);
49 const first = input.layers[0];
50 if (first === undefined) return 0;
51 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-stack-rebase-" }).pipe(
52 Effect.mapError(
53 (cause) =>
54 new GitHubStackRebaseGitError({
55 step: "preparing",
56 number: first.number,
57 completed: 0,
58 cause,
59 }),
60 ),
61 );
62 // Keep the token in this process's header, outside URLs, argv and git config.
63 const remote = input.remote ?? remoteUrl(input.host, input.repository);
64 const authorization = `AUTHORIZATION: basic ${Base64.encode(`x-access-token:${Redacted.value(token)}`)}`;
65 const env = {
66 GIT_TERMINAL_PROMPT: "0",
67 GIT_CONFIG_COUNT: "3",
68 GIT_CONFIG_KEY_0: `http.${remote}.extraheader`,
69 GIT_CONFIG_VALUE_0: authorization,
70 GIT_CONFIG_KEY_1: "user.name",
71 GIT_CONFIG_VALUE_1: "T3 Code",
72 GIT_CONFIG_KEY_2: "user.email",
73 GIT_CONFIG_VALUE_2: "noreply@t3.codes",
74 };
75 const git = (args: ReadonlyArray<string>, allowNonZeroExit = false) =>
76 process.run({
77 operation: "cascadeRebaseStack",
78 command: "git",
79 args,
80 cwd: directory,
81 env,
82 timeoutMs: 120_000,
83 ...(allowNonZeroExit ? { allowNonZeroExit: true } : {}),
84 });
85 const failed = (step: string, number: number, completed: number) => (cause: unknown) =>
86 new GitHubStackRebaseGitError({ step, number, completed, cause });
87​
88 yield* git(["init", "--quiet"]).pipe(Effect.mapError(failed("preparing", first.number, 0)));
89 yield* git(["remote", "add", "origin", remote]).pipe(
90 Effect.mapError(failed("preparing", first.number, 0)),
91 );
92 yield* git([
93 "fetch",
94 "--quiet",
95 "--no-tags",
96 "origin",
97 `+refs/heads/${input.base}:refs/remotes/origin/${input.base}`,
98 ...input.layers.map(
99 (layer) => `+refs/heads/${layer.headBranch}:refs/remotes/origin/${layer.headBranch}`,
100 ),
101 ]).pipe(Effect.mapError(failed("fetching", first.number, 0)));
102​
103 let parentOld = `origin/${input.base}`;
104 let parentNew = `origin/${input.base}`;
105 for (const [index, layer] of input.layers.entries()) {
106 // Exclude old parents: the base fork point for the bottom, the reviewed lower head above it.
107 const upstream =
108 index === 0
109 ? (yield* git(["merge-base", parentOld, layer.headSha]).pipe(
110 Effect.mapError(failed("reading the fork point", layer.number, index)),
111 )).stdout.trim()
112 : parentOld;
113 yield* git(["checkout", "--quiet", "--detach", layer.headSha]).pipe(
114 Effect.mapError(failed("checking out", layer.number, index)),
115 );
116 const rebase = yield* git(["rebase", "--quiet", "--onto", parentNew, upstream], true).pipe(
117 Effect.mapError(failed("rebasing", layer.number, index)),
118 );
119 if (rebase.exitCode !== 0) {
120 yield* git(["rebase", "--abort"], true).pipe(Effect.ignore);
121 return yield* new GitHubStackRebaseConflictError({ number: layer.number, completed: index });
122 }
123 const rebased = (yield* git(["rev-parse", "HEAD"]).pipe(
124 Effect.mapError(failed("rebasing", layer.number, index)),
125 )).stdout.trim();
126 if (rebased !== layer.headSha) {
127 yield* git([
128 "push",
129 "--quiet",
130 `--force-with-lease=refs/heads/${layer.headBranch}:${layer.headSha}`,
131 "origin",
132 `${rebased}:refs/heads/${layer.headBranch}`,
133 ]).pipe(Effect.mapError(failed("pushing", layer.number, index)));
134 }
135 parentOld = layer.headSha;
136 parentNew = rebased;
137 }
138 return input.layers.length;
139}, Effect.scoped);