Open History to see the last commit
1import { expect, it } from "@effect/vitest";
2import * as Layer from "effect/Layer";
3import * as Effect from "effect/Effect";
4import * as Schema from "effect/Schema";
5import * as FileSystem from "effect/FileSystem";
6import * as Redacted from "effect/Redacted";
7import { HttpClient, HttpClientResponse } from "effect/http";
8import { ChildProcessSpawner } from "effect/process";
9import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
10import * as GitHubRest from "./GitHubRest.ts";
11import * as GitHubCredentials from "./GitHubCredentials.ts";
12import * as GitHubQuota from "./GitHubQuota.ts";
13import * as GitHubRequestPolicy from "./GitHubRequestPolicy.ts";
14import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
15import { runGitHubStackAction as runStackAction } from "./githubStackActions.ts";
16
17type Call = ReadonlyArray<string>;
18type Send = (call: Call, kind: "graphql" | "rest") => Effect.Effect<unknown>;
19
20let gitCalls: Array<ReadonlyArray<string>> = [];
21const fakeGit = Layer.mergeAll(
22 TestSourceControlHost.layer({
23 process: {
24 run: (input) =>
25 Effect.sync(() => {
26 gitCalls.push(input.args);
27 const stdout =
28 input.args[0] === "rev-parse" || input.args[0] === "merge-base" ? "new-sha\n" : "";
29 return {
30 exitCode: ChildProcessSpawner.ExitCode(0),
31 stdout,
32 stderr: "",
33 stdoutTruncated: false,
34 stderrTruncated: false,
35 };
36 }),
37 },
38 }),
39 FileSystem.layerNoop({ makeTempDirectoryScoped: () => Effect.succeed("/tmp/scratch") }),
40);
41
42const graphQlHttp = (send: Send) =>
43 HttpClient.make((request) =>
44 Effect.gen(function* () {
45 const sent =
46 request.body._tag === "Uint8Array"
47 ? (JSON.parse(new TextDecoder().decode(request.body.body)) as {
48 readonly query: string;
49 readonly variables: Readonly<Record<string, unknown>>;
50 })
51 : { query: "", variables: {} };
52 const data = yield* send(words(sent.query, sent.variables), "graphql");
53 return HttpClientResponse.fromWeb(
54 request,
55 new Response(encodeJson({ data }), { headers: { "content-type": "application/json" } }),
56 );
57 }),
58 );
59
60const runGitHubStackAction = (send: Send, input: Parameters<typeof runStackAction>[0]) =>
61 runStackAction(input).pipe(
62 Effect.provide(
63 Layer.mergeAll(
64 fakeGit,
65 Layer.mock(GitHubRest.GitHubRest)({
66 credential: () => Effect.succeed({ token: Redacted.make("token"), fingerprint: "fp" }),
67 rest: (request) =>
68 send(words(request.path, request.body), "rest").pipe(
69 Effect.map((body) => ({
70 status: 200,
71 headers: {},
72 body: encodeJson(body),
73 truncated: false,
74 invalidUtf8: false,
75 })),
76 ),
77 }),
78 GitHubRequestPolicy.layer.pipe(
79 Layer.provide(
80 Layer.mergeAll(
81 Layer.succeed(GitHubCredentials.GitHubCredentials, {
82 get: (host) =>
83 Effect.succeed({
84 host,
85 token: Redacted.make("token"),
86 source: "gh" as const,
87 fingerprint: "fp",
88 }),
89 invalidate: () => Effect.void,
90 }),
91 GitHubQuota.layer,
92 SourceControlRateLimit.layer,
93 ),
94 ),
95 ),
96 Layer.succeed(HttpClient.HttpClient, graphQlHttp(send)),
97 ),
98 ),
99 );
100
101const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
102
103function words(head: string, fields: unknown): Call {
104 return [
105 head,
106 ...Object.entries((fields ?? {}) as Record<string, unknown>).map(
107 ([key, value]) => `${key}=${typeof value === "string" ? value : encodeJson(value)}`,
108 ),
109 ];
110}
111
112const isMutation = (call: Call) => call[0]!.startsWith("mutation");
113
114const stack = [
115 {
116 number: 50,
117 url: "https://api.github.com/repos/acme/web/stacks/50",
118 base: { ref: "main" },
119 pull_requests: [
120 {
121 number: 1,
122 title: "Base",
123 head: { ref: "base", sha: "aaa" },
124 state: "closed",
125 merged_at: "2026-01-01T00:00:00Z",
126 },
127 {
128 number: 2,
129 title: "Middle",
130 head: { ref: "middle", sha: "bbb" },
131 state: "open",
132 draft: false,
133 },
134 { number: 3, title: "Top", head: { ref: "top", sha: "ccc" }, state: "open", draft: false },
135 ],
136 },
137];
138const input = {
139 cwd: "/repo",
140 repository: "acme/web",
141 host: "github.com",
142 number: 3,
143 stackNumber: 50,
144 expectedStackHeads: [
145 { number: 2, headSha: "bbb" },
146 { number: 3, headSha: "ccc" },
147 ],
148 action: "merge" as const,
149};
150const writable = { headRepository: { viewerPermission: "WRITE" }, maintainerCanModify: false };
151const accessOf = (...pullRequests: ReadonlyArray<unknown>) =>
152 Object.fromEntries(
153 pullRequests.map((pullRequest, index) => [`_${index}_repository`, { pullRequest }]),
154 );
155const access = accessOf(writable, writable);
156
157const branch = (number: number, headRefOid: string, behindBy = 1, processed: string[] = []) => ({
158 data: {
159 processed: processed.map((headRefOid) => ({ headRefOid })),
160 repository: {
161 pullRequest: { id: `PR_${number}`, headRefOid, baseRef: { compare: { behindBy } } },
162 },
163 },
164});
165const rebased = {
166 data: { updatePullRequestBranch: { pullRequest: { headRefOid: "rebased-sha" } } },
167};
168const rebaseResponses = [branch(2, "bbb"), rebased, branch(3, "ccc", 1, ["rebased-sha"]), rebased];
169
170function fake(responses: readonly unknown[]) {
171 const calls: Call[] = [];
172 const execute: Send = (call) =>
173 Effect.sync(() => {
174 calls.push(call);
175 const value = responses[calls.length - 1];
176 if (value === undefined) throw new Error("Unexpected GitHub request");
177 return value;
178 });
179 return { execute, calls };
180}
181
182it.effect("submits one atomic merge with the reviewed head and respects the merge queue", () =>
183 Effect.gen(function* () {
184 const api = fake([stack, { status: "enqueued", details: {} }]);
185 yield* runGitHubStackAction(api.execute, { ...input, mergeMethod: "squash" });
186 expect(api.calls).toHaveLength(2);
187 expect(api.calls[1]).toContain("repos/acme/web/pulls/3/merge-async");
188 expect(api.calls[1]).toContain("sha=ccc");
189 expect(api.calls[1]).toContain("merge_action=default");
190 expect(api.calls[1]).toContain("merge_method=squash");
191 }),
192);
193
194it.effect("merges through the selected layer without including later draft layers", () =>
195 Effect.gen(function* () {
196 const fiveLayers = [
197 {
198 ...stack[0],
199 pull_requests: Array.from({ length: 5 }, (_, index) => ({
200 number: index + 1,
201 head: { ref: `layer-${index + 1}`, sha: `sha-${index + 1}` },
202 state: "open",
203 draft: index >= 3,
204 })),
205 },
206 ];
207 const api = fake([fiveLayers, { status: "merged", details: {} }]);
208 yield* runGitHubStackAction(api.execute, {
209 ...input,
210 number: 3,
211 expectedStackHeads: [1, 2, 3].map((number) => ({ number, headSha: `sha-${number}` })),
212 });
213 expect(api.calls).toHaveLength(2);
214 expect(api.calls[1]).toContain("repos/acme/web/pulls/3/merge-async");
215 expect(api.calls[1]).toContain("sha=sha-3");
216 expect(api.calls[1]).toContain("merge_action=default");
217 }),
218);
219
220it.effect("rejects stale reviewed heads below a selected middle layer", () =>
221 Effect.gen(function* () {
222 const api = fake([stack]);
223 const result = yield* runGitHubStackAction(api.execute, {
224 ...input,
225 number: 2,
226 expectedStackHeads: [{ number: 2, headSha: "old-head" }],
227 }).pipe(Effect.result);
228 expect(result).toMatchObject({ _tag: "Failure", failure: { _tag: "GitHubStackChangedError" } });
229 expect(api.calls).toHaveLength(1);
230 }),
231);
232
233it.effect("does not merge from an already merged layer", () =>
234 Effect.gen(function* () {
235 const api = fake([stack]);
236 const result = yield* runGitHubStackAction(api.execute, {
237 ...input,
238 number: 1,
239 expectedStackHeads: [],
240 }).pipe(Effect.result);
241 expect(result).toMatchObject({
242 _tag: "Failure",
243 failure: { _tag: "GitHubStackUnsupportedError" },
244 });
245 expect(api.calls).toHaveLength(1);
246 }),
247);
248
249it.effect("retains stack identity and a rejection response without a message", () =>
250 Effect.gen(function* () {
251 const rejection = { status: "failed", details: {} };
252 const api = fake([stack, rejection]);
253 const result = yield* runGitHubStackAction(api.execute, input).pipe(Effect.result);
254 expect(result).toMatchObject({
255 _tag: "Failure",
256 failure: {
257 _tag: "GitHubStackMergeRejectedError",
258 repository: input.repository,
259 number: input.number,
260 stackNumber: input.stackNumber,
261 cause: rejection,
262 },
263 });
264 }),
265);
266
267it.effect("refuses the entire rebase before mutation when a later fork denies write access", () =>
268 Effect.gen(function* () {
269 const api = fake([
270 stack,
271 accessOf(writable, {
272 headRepository: { viewerPermission: "READ" },
273 maintainerCanModify: false,
274 }),
275 ]);
276 const result = yield* runGitHubStackAction(api.execute, {
277 ...input,
278 action: "update-branch",
279 }).pipe(Effect.result);
280 expect(result).toMatchObject({
281 _tag: "Failure",
282 failure: { _tag: "GitHubStackPermissionError" },
283 });
284 expect(api.calls).toHaveLength(2);
285 }),
286);
287
288it.effect("allows a fork that explicitly permits maintainer updates", () =>
289 Effect.gen(function* () {
290 const api = fake([
291 stack,
292 accessOf(writable, {
293 headRepository: { viewerPermission: "READ" },
294 maintainerCanModify: true,
295 }),
296 ...rebaseResponses,
297 ]);
298 yield* runGitHubStackAction(api.execute, { ...input, action: "update-branch" });
299 expect(gitCalls.filter((args) => args[0] === "push")).toHaveLength(2);
300 }),
301);
302
303it.effect("rebases for a GitHub App, which GitHub gives no permission to read", () =>
304 Effect.gen(function* () {
305 gitCalls = [];
306 const api = fake([
307 stack,
308 accessOf(
309 { headRepository: { viewerPermission: null }, maintainerCanModify: false },
310 { headRepository: { viewerPermission: null }, maintainerCanModify: false },
311 ),
312 ...rebaseResponses,
313 ]);
314 yield* runGitHubStackAction(api.execute, { ...input, action: "update-branch" });
315 expect(gitCalls.filter((args) => args[0] === "push")).toHaveLength(2);
316 }),
317);
318
319it.effect("rebases the open layers bottom to top in a scratch clone, each onto the one below", () =>
320 Effect.gen(function* () {
321 gitCalls = [];
322 const api = fake([stack, access]);
323 yield* runGitHubStackAction(api.execute, { ...input, action: "update-branch" });
324 expect(api.calls[1]).toEqual(
325 expect.arrayContaining(["_0_number=2", "_1_number=3", "_0_owner=acme", "_0_name=web"]),
326 );
327 expect(api.calls.some(isMutation)).toBe(false);
328 const rebases = gitCalls.filter((args) => args[0] === "rebase");
329 expect(rebases).toEqual([
330 ["rebase", "--quiet", "--onto", "origin/main", "new-sha"],
331 ["rebase", "--quiet", "--onto", "new-sha", "bbb"],
332 ]);
333 expect(gitCalls.filter((args) => args[0] === "push")).toEqual([
334 [
335 "push",
336 "--quiet",
337 "--force-with-lease=refs/heads/middle:bbb",
338 "origin",
339 "new-sha:refs/heads/middle",
340 ],
341 [
342 "push",
343 "--quiet",
344 "--force-with-lease=refs/heads/top:ccc",
345 "origin",
346 "new-sha:refs/heads/top",
347 ],
348 ]);
349 }),
350);