Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ReviewService.ts

162 lines5.8 KB

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