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 ProjectStore from "../orchestration-v2/ProjectStore.ts";
20import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
21import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
22import * as ServerSettings from "../serverSettings.ts";
23import { isFilesystemRoot, managedWorktreesDirectories } from "../worktreesDirectory.ts";
24import * as HostProcess from "@t3tools/shared/HostProcess";
25
26export class ReviewService extends Context.Service<
27 ReviewService,
28 {
29 readonly getDiffPreview: (
30 input: ReviewDiffPreviewInput,
31 ) => Effect.Effect<ReviewDiffPreviewResult, ReviewDiffPreviewError>;
32 readonly getDiffFileContents: (
33 input: ReviewDiffFileContentsInput,
34 ) => Effect.Effect<ReviewDiffFileContentsResult, ReviewDiffPreviewError>;
35 }
36>()("t3/review/ReviewService") {}
37
38/** @public Service construction is part of the canonical Effect module API. */
39export const make = Effect.gen(function* () {
40 const config = yield* ServerConfig.ServerConfig;
41 const fileSystem = yield* FileSystem.FileSystem;
42 const path = yield* Path.Path;
43 const vcsRegistry = yield* VcsDriverRegistry.VcsDriverRegistry;
44 const git = yield* GitVcsDriver.GitVcsDriver;
45 const settings = yield* ServerSettings.ServerSettingsService;
46 const projectStore = yield* ProjectStore.ProjectStoreV2;
47
48 const canonicalizePath = (value: string) => {
49 const resolvedPath = path.resolve(value);
50 return fileSystem.realPath(resolvedPath).pipe(
51 Effect.catchTags({
52 PlatformError: (cause) =>
53 cause.reason._tag === "NotFound"
54 ? Effect.succeed(resolvedPath)
55 : Effect.fail(
56 new VcsRepositoryDetectionError({
57 operation: "ReviewService.assertWorkspaceBoundCwd.canonicalizePath",
58 cwd: resolvedPath,
59 detail: "Failed to resolve a path while validating the review workspace.",
60 cause,
61 }),
62 ),
63 }),
64 );
65 };
66
67 const isWithinRoot = (candidate: string, root: string) => {
68 const relative = path.relative(root, candidate);
69 return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
70 };
71
72 const assertWorkspaceBoundCwd = Effect.fn("ReviewService.assertWorkspaceBoundCwd")(function* (
73 operation: "ReviewService.getDiffPreview" | "ReviewService.getDiffFileContents",
74 cwd: string,
75 ) {
76 const worktreesDirectories = yield* settings.getSettings.pipe(
77 Effect.orElseSucceed(() => ({ worktreesDirectory: "", previousWorktreesDirectories: [] })),
78 );
79 const home = yield* HostProcess.HomeDirectory;
80 const [candidate, workspaceRoot, worktreesRoots] = yield* Effect.all([
81 canonicalizePath(cwd),
82 canonicalizePath(config.cwd),
83 Effect.forEach(
84 managedWorktreesDirectories(worktreesDirectories, config.worktreesDir, path, home),
85 (directory) => canonicalizePath(directory).pipe(Effect.orElseSucceed(() => null)),
86 ).pipe(
87 Effect.map((roots) =>
88 roots.filter((root): root is string => root !== null && !isFilesystemRoot(root, path)),
89 ),
90 ),
91 ]);
92
93 if (
94 isWithinRoot(candidate, workspaceRoot) ||
95 worktreesRoots.some((root) => isWithinRoot(candidate, root))
96 ) {
97 return;
98 }
99
100 // Registered projects can live outside the server cwd, which is the home
101 // directory in packaged desktop builds, e.g. a repository on another
102 // Windows drive. Unreadable or unresolvable project roots grant nothing.
103 const projects = yield* projectStore.listShells().pipe(Effect.orElseSucceed(() => []));
104 for (const project of projects) {
105 const root = yield* canonicalizePath(project.workspaceRoot).pipe(
106 Effect.orElseSucceed(() => null),
107 );
108 if (root !== null && isWithinRoot(candidate, root)) {
109 return;
110 }
111 }
112
113 return yield* new VcsRepositoryDetectionError({
114 operation,
115 cwd,
116 detail:
117 operation === "ReviewService.getDiffPreview"
118 ? "Review diff preview cwd must stay within the configured workspace root."
119 : "Review diff file contents cwd must stay within the configured workspace root.",
120 });
121 });
122
123 const getDiffPreview: ReviewService["Service"]["getDiffPreview"] = Effect.fn(
124 "ReviewService.getDiffPreview",
125 )(function* (input) {
126 yield* assertWorkspaceBoundCwd("ReviewService.getDiffPreview", input.cwd);
127
128 const handle = yield* vcsRegistry.detect({ cwd: input.cwd, requestedKind: "auto" });
129 if (!handle) {
130 return {
131 cwd: input.cwd,
132 generatedAt: yield* DateTime.now,
133 sources: [],
134 };
135 }
136
137 const getDriverDiffPreview = handle.driver.getDiffPreview;
138 if (!getDriverDiffPreview) {
139 if (handle.kind === "git") {
140 return yield* git.getReviewDiffPreview(input);
141 }
142 return yield* new VcsUnsupportedOperationError({
143 operation: "ReviewService.getDiffPreview",
144 kind: handle.kind,
145 detail: `The ${handle.kind} VCS driver does not support review diff previews.`,
146 });
147 }
148
149 return yield* getDriverDiffPreview(input);
150 });
151
152 const getDiffFileContents: ReviewService["Service"]["getDiffFileContents"] = Effect.fn(
153 "ReviewService.getDiffFileContents",
154 )(function* (input) {
155 yield* assertWorkspaceBoundCwd("ReviewService.getDiffFileContents", input.cwd);
156
157 const handle = yield* vcsRegistry.detect({ cwd: input.cwd, requestedKind: "auto" });
158 if (handle?.kind !== "git") {
159 return yield* new VcsUnsupportedOperationError({
160 operation: "ReviewService.getDiffFileContents",
161 kind: handle?.kind ?? "unknown",
162 detail: "Unchanged diff expansion currently requires a Git repository.",
163 });
164 }
165
166 return yield* git.getReviewDiffFileContents(input);
167 });
168
169 return ReviewService.of({
170 getDiffPreview,
171 getDiffFileContents,
172 });
173});
174
175export const layer = Layer.effect(ReviewService, make);