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