Open History to see the last commit
1import * as Context from "effect/Context";
2import * as DateTime from "effect/DateTime";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as Layer from "effect/Layer";
6import * as Path from "effect/Path";
7
8import {
9 VcsRepositoryDetectionError,
10 VcsUnsupportedOperationError,
11 type ReviewDiffFileContentsInput,
12 type ReviewDiffFileContentsResult,
13 type ReviewDiffPreviewError,
14 type ReviewDiffPreviewInput,
15 type ReviewDiffPreviewResult,
16} from "@t3tools/contracts";
17
18import * as ServerConfig from "../config.ts";
19import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
20import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
21import * as ServerSettings from "../serverSettings.ts";
22import { isFilesystemRoot, managedWorktreesDirectories } from "../worktreesDirectory.ts";
23
24export class ReviewService extends Context.Service<
25 ReviewService,
26 {
27 readonly getDiffPreview: (
28 input: ReviewDiffPreviewInput,
29 ) => Effect.Effect<ReviewDiffPreviewResult, ReviewDiffPreviewError>;
30 readonly getDiffFileContents: (
31 input: ReviewDiffFileContentsInput,
32 ) => Effect.Effect<ReviewDiffFileContentsResult, ReviewDiffPreviewError>;
33 }
34>()("t3/review/ReviewService") {}
35
36/** @public Service construction is part of the canonical Effect module API. */
37export const make = Effect.gen(function* () {
38 const config = yield* ServerConfig.ServerConfig;
39 const fileSystem = yield* FileSystem.FileSystem;
40 const path = yield* Path.Path;
41 const vcsRegistry = yield* VcsDriverRegistry.VcsDriverRegistry;
42 const git = yield* GitVcsDriver.GitVcsDriver;
43 const settings = yield* ServerSettings.ServerSettingsService;
44
45 const canonicalizePath = (value: string) => {
46 const resolvedPath = path.resolve(value);
47 return fileSystem.realPath(resolvedPath).pipe(
48 Effect.catchTags({
49 PlatformError: (cause) =>
50 cause.reason._tag === "NotFound"
51 ? Effect.succeed(resolvedPath)
52 : Effect.fail(
53 new VcsRepositoryDetectionError({
54 operation: "ReviewService.assertWorkspaceBoundCwd.canonicalizePath",
55 cwd: resolvedPath,
56 detail: "Failed to resolve a path while validating the review workspace.",
57 cause,
58 }),
59 ),
60 }),
61 );
62 };
63
64 const isWithinRoot = (candidate: string, root: string) => {
65 const relative = path.relative(root, candidate);
66 return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
67 };
68
69 const assertWorkspaceBoundCwd = Effect.fn("ReviewService.assertWorkspaceBoundCwd")(function* (
70 operation: "ReviewService.getDiffPreview" | "ReviewService.getDiffFileContents",
71 cwd: string,
72 ) {
73 const worktreesDirectories = yield* settings.getSettings.pipe(
74 Effect.orElseSucceed(() => ({ worktreesDirectory: "", previousWorktreesDirectories: [] })),
75 );
76 const [candidate, workspaceRoot, worktreesRoots] = yield* Effect.all([
77 canonicalizePath(cwd),
78 canonicalizePath(config.cwd),
79 // A managed root that cannot be resolved, or resolves to a filesystem
80 // root through a symlink, is skipped rather than failing every review.
81 Effect.forEach(
82 managedWorktreesDirectories(worktreesDirectories, config.worktreesDir, path),
83 (directory) => canonicalizePath(directory).pipe(Effect.orElseSucceed(() => null)),
84 ).pipe(
85 Effect.map((roots) =>
86 roots.filter((root): root is string => root !== null && !isFilesystemRoot(root, path)),
87 ),
88 ),
89 ]);
90
91 if (
92 isWithinRoot(candidate, workspaceRoot) ||
93 worktreesRoots.some((root) => isWithinRoot(candidate, root))
94 ) {
95 return;
96 }
97
98 return yield* new VcsRepositoryDetectionError({
99 operation,
100 cwd,
101 detail:
102 operation === "ReviewService.getDiffPreview"
103 ? "Review diff preview cwd must stay within the configured workspace root."
104 : "Review diff file contents cwd must stay within the configured workspace root.",
105 });
106 });
107
108 const getDiffPreview: ReviewService["Service"]["getDiffPreview"] = Effect.fn(
109 "ReviewService.getDiffPreview",
110 )(function* (input) {
111 yield* assertWorkspaceBoundCwd("ReviewService.getDiffPreview", input.cwd);
112
113 const handle = yield* vcsRegistry.detect({ cwd: input.cwd, requestedKind: "auto" });
114 if (!handle) {
115 return {
116 cwd: input.cwd,
117 generatedAt: yield* DateTime.now,
118 sources: [],
119 };
120 }
121
122 const getDriverDiffPreview = handle.driver.getDiffPreview;
123 if (!getDriverDiffPreview) {
124 if (handle.kind === "git") {
125 return yield* git.getReviewDiffPreview(input);
126 }
127 return yield* new VcsUnsupportedOperationError({
128 operation: "ReviewService.getDiffPreview",
129 kind: handle.kind,
130 detail: `The ${handle.kind} VCS driver does not support review diff previews.`,
131 });
132 }
133
134 return yield* getDriverDiffPreview(input);
135 });
136
137 const getDiffFileContents: ReviewService["Service"]["getDiffFileContents"] = Effect.fn(
138 "ReviewService.getDiffFileContents",
139 )(function* (input) {
140 yield* assertWorkspaceBoundCwd("ReviewService.getDiffFileContents", input.cwd);
141
142 const handle = yield* vcsRegistry.detect({ cwd: input.cwd, requestedKind: "auto" });
143 if (handle?.kind !== "git") {
144 return yield* new VcsUnsupportedOperationError({
145 operation: "ReviewService.getDiffFileContents",
146 kind: handle?.kind ?? "unknown",
147 detail: "Unchanged diff expansion currently requires a Git repository.",
148 });
149 }
150
151 return yield* git.getReviewDiffFileContents(input);
152 });
153
154 return ReviewService.of({
155 getDiffPreview,
156 getDiffFileContents,
157 });
158});
159
160export const layer = Layer.effect(ReviewService, make);