Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it } from "@effect/vitest";
3import * as Context from "effect/Context";
4import * as Deferred from "effect/Deferred";
5import * as Effect from "effect/Effect";
6import * as Fiber from "effect/Fiber";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as Ref from "effect/Ref";
10import * as Queue from "effect/Queue";
11import * as Tracer from "effect/Tracer";
12import {
13 ProjectId,
14 GitCommandError,
15 type PullRequestActivity,
16 type PullRequestDetail,
17 type PullRequestStack,
18 type PullRequestRef,
19} from "@t3tools/contracts";
20
21import * as ServerConfig from "../config.ts";
22import * as SqlitePersistence from "../persistence/Sqlite.ts";
23import * as PullRequestReviewGuides from "../persistence/PullRequestReviewGuides.ts";
24import * as ProjectService from "../project/ProjectService.ts";
25import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
26import * as ServerSettings from "../serverSettings.ts";
27import * as TextGeneration from "../textGeneration/TextGeneration.ts";
28import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
29import * as VcsProcess from "../vcs/VcsProcess.ts";
30import * as PullRequestReviewGuideService from "./PullRequestReviewGuideService.ts";
31import * as PullRequestService from "./PullRequestService.ts";
32
33const projectId = ProjectId.make("project-1");
34const ACME_APP = {
35 canonicalKey: "github.com/acme/app",
36 locator: {
37 source: "git-remote" as const,
38 remoteName: "origin",
39 remoteUrl: "https://github.com/acme/app.git",
40 },
41 provider: "github",
42 displayName: "acme/app",
43 owner: "acme",
44 name: "app",
45};
46
47const reference: PullRequestRef = {
48 projectId,
49 host: "github.com",
50 repository: "acme/app",
51 number: 7,
52};
53
54const git = (cwd: string, args: ReadonlyArray<string>) =>
55 Effect.gen(function* () {
56 const driver = yield* GitVcsDriver.GitVcsDriver;
57 const result = yield* driver.execute({ operation: "test.git", cwd, args, timeoutMs: 10_000 });
58 return result.stdout.trim();
59 });
60
61const makeRepositories = Effect.gen(function* () {
62 const fs = yield* FileSystem.FileSystem;
63 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-guide-" });
64 const remote = `${root}/remote`;
65 const workspace = `${root}/workspace`;
66 yield* fs.makeDirectory(remote);
67 yield* git(remote, ["init", "--quiet", "--initial-branch=main"]);
68 yield* git(remote, ["config", "user.email", "test@example.com"]);
69 yield* git(remote, ["config", "user.name", "Test"]);
70 const commit = (path: string, message: string, contents = message) =>
71 fs
72 .writeFileString(`${remote}/${path}`, contents)
73 .pipe(
74 Effect.andThen(git(remote, ["add", path])),
75 Effect.andThen(git(remote, ["commit", "--quiet", "-m", message])),
76 Effect.andThen(git(remote, ["rev-parse", "HEAD"])),
77 );
78 yield* commit("base.txt", "base");
79 yield* git(remote, ["checkout", "--quiet", "-b", "stack-base"]);
80 const lowerSha = yield* commit("lower.txt", "lower layer");
81 yield* git(remote, ["checkout", "--quiet", "-b", "feature"]);
82 const headSha = yield* commit(
83 "feature.txt",
84 "the change",
85 Array.from({ length: 10 }, (_, index) => `line ${index + 1}`).join("\n") + "\n",
86 );
87 yield* git(remote, ["checkout", "--quiet", "-b", "upper"]);
88 const upperSha = yield* commit("upper.txt", "upper layer");
89 yield* git(remote, ["checkout", "--quiet", "main"]);
90 yield* commit("unrelated.txt", "main moved on");
91 yield* git(root, ["clone", "--quiet", remote, workspace]);
92 return { root, remote, workspace, headSha, lowerSha, upperSha };
93});
94
95const detail = (workspaceRoot: string, headSha: string): PullRequestDetail =>
96 ({
97 number: 7,
98 title: "Add the feature",
99 body: "Adds the feature.",
100 baseBranch: "stack-base",
101 headBranch: "feature",
102 headSha,
103 workspaceRoot,
104 }) as PullRequestDetail;
105
106const activity: PullRequestActivity = {
107 comments: [],
108 commentCount: 0,
109 commentsTruncated: false,
110 reviewThreads: [],
111 commits: [],
112};
113
114const stack = (repositories: {
115 readonly headSha: string;
116 readonly lowerSha: string;
117 readonly upperSha: string;
118}): PullRequestStack => ({
119 id: "stack",
120 number: 1,
121 url: "https://example.com/stack/1",
122 base: "main",
123 layers: [
124 {
125 number: 6,
126 title: "Lower",
127 headSha: repositories.lowerSha,
128 headBranch: "stack-base",
129 state: "open",
130 },
131 {
132 number: 7,
133 title: "Add the feature",
134 headSha: repositories.headSha,
135 headBranch: "feature",
136 state: "open",
137 },
138 {
139 number: 8,
140 title: "Upper",
141 headSha: repositories.upperSha.slice(0, 12),
142 headBranch: "upper",
143 state: "open",
144 },
145 { number: 9, title: "Unpushed", headSha: "f".repeat(40), headBranch: "gone", state: "open" },
146 ],
147});
148
149const makeLayer = (input: {
150 readonly root: string;
151 readonly remote: string;
152 readonly workspace: string;
153 readonly headSha: string;
154 readonly lowerSha: string;
155 readonly upperSha: string;
156 readonly generate: TextGeneration.TextGeneration["Service"]["generateReviewGuide"];
157 readonly stored: Deferred.Deferred<void>;
158 readonly enabled?: boolean;
159 readonly currentHead?: Ref.Ref<string>;
160 readonly identity?: typeof ACME_APP;
161}) =>
162 PullRequestReviewGuideService.layer.pipe(
163 Layer.provide(
164 Layer.effect(
165 PullRequestReviewGuides.PullRequestReviewGuideRepository,
166 Effect.gen(function* () {
167 const repository = yield* PullRequestReviewGuides.PullRequestReviewGuideRepository;
168 return {
169 get: repository.get,
170 put: (key, guide) =>
171 repository
172 .put(key, guide)
173 .pipe(Effect.tap(() => Deferred.succeed(input.stored, undefined))),
174 } satisfies PullRequestReviewGuides.PullRequestReviewGuideRepository["Service"];
175 }),
176 ).pipe(Layer.provide(PullRequestReviewGuides.layer)),
177 ),
178 Layer.provide(
179 Layer.succeed(PullRequestService.PullRequestService, {
180 detail: () =>
181 (input.currentHead === undefined
182 ? Effect.succeed(input.headSha)
183 : Ref.get(input.currentHead)
184 ).pipe(Effect.map((head) => detail(input.workspace, head))),
185 activity: () => Effect.succeed(activity),
186 invalidate: () => Effect.void,
187 stack: () => Effect.succeed(stack(input)),
188 } as unknown as PullRequestService.PullRequestService["Service"]),
189 ),
190 Layer.provide(
191 Layer.succeed(ProjectService.ProjectService, {
192 getShell: () =>
193 Effect.succeedSome({
194 id: projectId,
195 workspaceRoot: input.workspace,
196 repositoryIdentity: {
197 ...(input.identity ?? ACME_APP),
198 locator: { ...ACME_APP.locator, remoteUrl: input.remote },
199 },
200 }),
201 } as unknown as ProjectService.ProjectService["Service"]),
202 ),
203 Layer.provide(
204 Layer.succeed(ProviderRegistry.ProviderRegistry, {
205 getProviders: Effect.succeed([]),
206 } as unknown as ProviderRegistry.ProviderRegistry["Service"]),
207 ),
208 Layer.provide(
209 Layer.succeed(TextGeneration.TextGeneration, {
210 generateReviewGuide: input.generate,
211 } as unknown as TextGeneration.TextGeneration["Service"]),
212 ),
213 Layer.provide(ServerSettings.layerTest({ reviewGuidesEnabled: input.enabled ?? true })),
214 Layer.provide(ServerConfig.layerTest(input.root, { prefix: "t3-review-guide-config-" })),
215 );
216
217const layerBase = Layer.mergeAll(
218 GitVcsDriver.layer.pipe(
219 Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-review-guide-git-" })),
220 Layer.provideMerge(VcsProcess.layer),
221 ),
222 SqlitePersistence.layerMemory,
223).pipe(Layer.provideMerge(NodeServices.layer));
224
225type Repositories = Effect.Success<typeof makeRepositories>;
226
227// A run forks into the service's scope, so a test learns it settled when the run's `write` span
228// ends; the run records its outcome synchronously right after.
229const watchRuns = Effect.gen(function* () {
230 const ended = yield* Queue.unbounded<void>();
231 const tracer = Tracer.make({
232 span: (options) => {
233 const span = new Tracer.NativeSpan(options);
234 if (options.name !== "PullRequestReviewGuideService.write") return span;
235 const end = span.end.bind(span);
236 span.end = (endTime, exit) => {
237 end(endTime, exit);
238 Queue.offerUnsafe(ended, undefined);
239 };
240 return span;
241 },
242 });
243 return {
244 generate: (
245 service: PullRequestReviewGuideService.PullRequestReviewGuideService["Service"],
246 input: PullRequestRef,
247 ) => service.generate(input).pipe(Effect.withTracer(tracer)),
248 settled: (
249 service: PullRequestReviewGuideService.PullRequestReviewGuideService["Service"],
250 input: PullRequestRef,
251 ) => Queue.take(ended).pipe(Effect.andThen(service.get(input))),
252 };
253});
254
255const startSingleBranchRun = (input: {
256 readonly repositoryName: string;
257 readonly reportedHead: (repositories: Repositories) => string;
258 readonly refuseCommitFetch: boolean;
259 readonly prepare: (
260 repositories: Repositories,
261 workspace: string,
262 ) => Effect.Effect<void, GitCommandError, GitVcsDriver.GitVcsDriver>;
263 readonly onBranchFetch?:
264 | ((
265 repositories: Repositories,
266 ) => Effect.Effect<void, GitCommandError, GitVcsDriver.GitVcsDriver>)
267 | undefined;
268}) =>
269 Effect.gen(function* () {
270 const repositories = yield* makeRepositories;
271 const workspace = `${repositories.root}/single-branch`;
272 yield* git(repositories.root, [
273 "clone",
274 "--quiet",
275 "--no-local",
276 "--single-branch",
277 "--branch",
278 "main",
279 `${repositories.root}/remote`,
280 workspace,
281 ]);
282 yield* input.prepare(repositories, workspace);
283 const reportedHead = input.reportedHead(repositories);
284 const stored = yield* Deferred.make<void>();
285 const driver = yield* GitVcsDriver.GitVcsDriver;
286 const fetchedRefs: Array<string> = [];
287 const observed: Array<{ cwd: string; head: string; changed: string }> = [];
288 const onBranchFetch = input.onBranchFetch;
289 const observedDriver = {
290 ...driver,
291 execute: (call: GitVcsDriver.ExecuteGitInput) =>
292 Effect.gen(function* () {
293 const ref = call.args.at(-1);
294 if (call.args[0] !== "fetch" || ref === undefined) return yield* driver.execute(call);
295 fetchedRefs.push(ref);
296 if (input.refuseCommitFetch && ref === repositories.headSha) {
297 return yield* new GitCommandError({
298 operation: call.operation,
299 command: "git",
300 cwd: call.cwd,
301 detail: "The test remote refuses fetches by commit.",
302 exitCode: 128,
303 });
304 }
305 if (ref === "refs/heads/feature" && onBranchFetch !== undefined) {
306 yield* onBranchFetch(repositories).pipe(
307 Effect.provideService(GitVcsDriver.GitVcsDriver, driver),
308 );
309 }
310 return yield* driver.execute(call);
311 }),
312 };
313 const readCheckout = (cwd: string, args: ReadonlyArray<string>) =>
314 driver
315 .execute({ operation: "test.readCheckout", cwd, args })
316 .pipe(Effect.map((result) => result.stdout.trim()));
317 const context = yield* Layer.build(
318 makeLayer({
319 ...repositories,
320 headSha: reportedHead,
321 workspace,
322 stored,
323 identity: {
324 ...ACME_APP,
325 canonicalKey: `github.com/acme/${input.repositoryName}`,
326 displayName: `acme/${input.repositoryName}`,
327 name: input.repositoryName,
328 },
329 generate: (generation) =>
330 Effect.gen(function* () {
331 observed.push({
332 cwd: generation.cwd,
333 head: yield* readCheckout(generation.cwd, ["rev-parse", "HEAD"]),
334 changed: yield* readCheckout(generation.cwd, [
335 "diff",
336 "--name-only",
337 `${generation.baseCommit}...HEAD`,
338 ]),
339 });
340 return { stops: [] };
341 }).pipe(Effect.orDie),
342 }).pipe(Layer.provide(Layer.succeed(GitVcsDriver.GitVcsDriver, observedDriver))),
343 );
344 const service = Context.get(
345 context,
346 PullRequestReviewGuideService.PullRequestReviewGuideService,
347 );
348 const guideReference = { ...reference, repository: `acme/${input.repositoryName}` };
349 const runs = yield* watchRuns;
350 yield* runs.generate(service, guideReference);
351 return {
352 repositories,
353 reportedHead,
354 service,
355 reference: guideReference,
356 stored,
357 fetchedRefs,
358 observed,
359 settled: runs.settled(service, guideReference),
360 };
361 });
362
363it.layer(layerBase, { excludeTestServices: true })("PullRequestReviewGuideService", (it) => {
364 it.effect.each([
365 {
366 name: "a branch named like the short head",
367 reportedHead: (repositories: Repositories) => repositories.headSha.slice(0, 12),
368 shadow: "branch",
369 expected: ["a branch or tag rather than the commit"],
370 },
371 {
372 name: "a tag named like the short head",
373 reportedHead: (repositories: Repositories) => repositories.headSha.slice(0, 12),
374 shadow: "tag",
375 expected: ["a branch or tag rather than the commit"],
376 },
377 {
378 name: "a head that is not a commit hash",
379 reportedHead: (repositories: Repositories) =>
380 `--upload-pack=touch ${repositories.root}/injected`,
381 shadow: "none",
382 expected: ["not a commit hash"],
383 },
384 {
385 name: "a head no source has",
386 reportedHead: () => "e".repeat(40),
387 shadow: "none",
388 expected: [
389 "local objects:",
390 "the commit:",
391 "branch feature:",
392 "refs/pull/7/head:",
393 "refs/merge-requests/7/head:",
394 ],
395 },
396 ])("refuses to write a guide for $name", ({ reportedHead, shadow, expected }) =>
397 Effect.scoped(
398 Effect.gen(function* () {
399 const run = yield* startSingleBranchRun({
400 repositoryName: "refused-head",
401 reportedHead,
402 refuseCommitFetch: false,
403 prepare: (repositories, workspace) =>
404 git(workspace, ["fetch", "--quiet", "origin", "feature"]).pipe(
405 Effect.andThen(
406 shadow === "none"
407 ? Effect.void
408 : git(workspace, [shadow, repositories.headSha.slice(0, 12), "HEAD"]),
409 ),
410 Effect.asVoid,
411 ),
412 });
413 const result = yield* run.settled;
414 assert.isFalse(yield* Deferred.isDone(run.stored), "a guide was written");
415 assert.strictEqual(result.run?._tag, "Failed");
416 const detail = result.run?._tag === "Failed" ? result.run.detail : "";
417 for (const part of expected) assert.include(detail, part);
418 assert.deepStrictEqual(run.observed, []);
419 assert.isFalse(run.fetchedRefs.some((ref) => ref.startsWith("-")));
420 const fs = yield* FileSystem.FileSystem;
421 assert.isFalse(yield* fs.exists(`${run.repositories.root}/injected`));
422 }),
423 ),
424 );
425
426 it.effect("measures only the PR change using the renamed verified remote's fetch URL", () =>
427 Effect.scoped(
428 Effect.gen(function* () {
429 const repositories = yield* makeRepositories;
430 const fork = `${repositories.root}/fork`;
431 yield* git(repositories.root, ["clone", "--quiet", repositories.remote, fork]);
432 yield* git(fork, ["branch", "stack-base", "main~1"]);
433 // The cached identity still names origin, which now belongs to the stale fork.
434 yield* git(repositories.workspace, ["remote", "rename", "origin", "upstream"]);
435 yield* git(repositories.workspace, ["remote", "add", "origin", fork]);
436 yield* git(repositories.workspace, [
437 "config",
438 `url.${repositories.remote}.insteadOf`,
439 "review-upstream:",
440 ]);
441 yield* git(repositories.workspace, ["remote", "set-url", "upstream", "review-upstream:"]);
442 const changed = yield* Deferred.make<string>();
443 const driver = yield* GitVcsDriver.GitVcsDriver;
444 const stored = yield* Deferred.make<void>();
445 const context = yield* Layer.build(
446 makeLayer({
447 ...repositories,
448 stored,
449 generate: (input) =>
450 git(input.cwd, ["diff", "--name-only", `${input.baseCommit}...HEAD`]).pipe(
451 Effect.provideService(GitVcsDriver.GitVcsDriver, driver),
452 Effect.orDie,
453 Effect.flatMap((names) => Deferred.succeed(changed, names)),
454 Effect.as({ stops: [] }),
455 ),
456 }),
457 );
458 const service = Context.get(
459 context,
460 PullRequestReviewGuideService.PullRequestReviewGuideService,
461 );
462 yield* service.generate(reference);
463 assert.strictEqual(yield* Deferred.await(changed), "feature.txt");
464 yield* Deferred.await(stored);
465 const result = yield* service.get(reference);
466 assert.strictEqual(result.guide?.headSha, repositories.headSha);
467 assert.deepStrictEqual(result.guide?.stops[0]?.files, [{ path: "feature.txt" }]);
468 }),
469 ),
470 );
471
472 it.effect("refuses generation when the verified remote disappeared despite a usable origin", () =>
473 Effect.scoped(
474 Effect.gen(function* () {
475 const repositories = yield* makeRepositories;
476 const fork = `${repositories.root}/fork`;
477 yield* git(repositories.root, ["clone", "--quiet", repositories.remote, fork]);
478 yield* git(fork, ["branch", "stack-base", repositories.lowerSha]);
479 yield* git(repositories.workspace, ["remote", "set-url", "origin", fork]);
480 const started = yield* Deferred.make<Fiber.Fiber<unknown, unknown>>();
481 const stored = yield* Deferred.make<void>();
482 const generated = yield* Ref.make(false);
483 const driver = yield* GitVcsDriver.GitVcsDriver;
484 const context = yield* Layer.build(
485 makeLayer({
486 ...repositories,
487 stored,
488 generate: () => Ref.set(generated, true).pipe(Effect.as({ stops: [] })),
489 }).pipe(
490 Layer.provide(
491 Layer.succeed(GitVcsDriver.GitVcsDriver, {
492 ...driver,
493 execute: (call) =>
494 Effect.withFiber((fiber) =>
495 Deferred.succeed(started, fiber).pipe(Effect.andThen(driver.execute(call))),
496 ),
497 }),
498 ),
499 ),
500 );
501 const service = Context.get(
502 context,
503 PullRequestReviewGuideService.PullRequestReviewGuideService,
504 );
505 const before = yield* service.get(reference);
506 yield* service.generate(reference);
507 // Join the background run so its failure is visible without polling service state.
508 yield* Fiber.await(yield* Deferred.await(started));
509 const result = yield* service.get(reference);
510 assert.strictEqual(result.run?._tag, "Failed");
511 assert.include(
512 result.run?._tag === "Failed" ? result.run.detail : "",
513 "no longer has a remote for the pull request's repository",
514 );
515 assert.deepStrictEqual(result.guide, before.guide);
516 assert.isFalse(yield* Deferred.isDone(stored));
517 assert.isFalse(yield* Ref.get(generated));
518 }),
519 ),
520 );
521
522 it.effect("refuses a pull request from a repository the project is not a checkout of", () =>
523 Effect.scoped(
524 Effect.gen(function* () {
525 const repositories = yield* makeRepositories;
526 const stored = yield* Deferred.make<void>();
527 const context = yield* Layer.build(
528 makeLayer({
529 ...repositories,
530 stored,
531 identity: {
532 ...ACME_APP,
533 canonicalKey: "github.com/acme/other",
534 displayName: "acme/other",
535 name: "other",
536 },
537 generate: () =>
538 Effect.die("a guide must not be written from another repository's checkout"),
539 }),
540 );
541 const service = Context.get(
542 context,
543 PullRequestReviewGuideService.PullRequestReviewGuideService,
544 );
545 const result = yield* Effect.flip(service.generate(reference));
546 assert.include(result.message, "in another repository");
547 }),
548 ),
549 );
550});