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

WorkspaceEntries.ts

296 lines10.6 KB

1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeFSP from "node:fs/promises";
3import * as NodeOS from "node:os";
4​
5import * as Context from "effect/Context";
6import * as Effect from "effect/Effect";
7import * as Layer from "effect/Layer";
8import * as Path from "effect/Path";
9import * as RcMap from "effect/RcMap";
10import * as Schema from "effect/Schema";
11​
12import type {
13 FilesystemBrowseInput,
14 FilesystemBrowseResult,
15 ProjectListEntriesInput,
16 ProjectListEntriesResult,
17 ProjectSearchContentsInput,
18 ProjectSearchContentsResult,
19 ProjectSearchEntriesInput,
20 ProjectSearchEntriesResult,
21} from "@t3tools/contracts";
22import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
23import { isExplicitRelativePath, isWindowsAbsolutePath } from "@t3tools/shared/path";
24import { normalizeSearchQuery } from "@t3tools/shared/searchRanking";
25​
26import * as WorkspacePaths from "./WorkspacePaths.ts";
27import * as WorkspaceSearchIndex from "./WorkspaceSearchIndex.ts";
28​
29export class WorkspaceEntriesWindowsPathUnsupportedError extends Schema.TaggedErrorClass<WorkspaceEntriesWindowsPathUnsupportedError>()(
30 "WorkspaceEntriesWindowsPathUnsupportedError",
31 {
32 cwd: Schema.optional(Schema.String),
33 partialPath: Schema.String,
34 platform: Schema.String,
35 },
36) {
37 override get message(): string {
38 const cwd = this.cwd ? ` from '${this.cwd}'` : "";
39 return `Windows-style workspace path '${this.partialPath}' is not supported on '${this.platform}'${cwd}.`;
40 }
42​
43export class WorkspaceEntriesCurrentProjectRequiredError extends Schema.TaggedErrorClass<WorkspaceEntriesCurrentProjectRequiredError>()(
44 "WorkspaceEntriesCurrentProjectRequiredError",
45 {
46 partialPath: Schema.String,
47 },
48) {
49 override get message(): string {
50 return `A current project is required to browse relative workspace path '${this.partialPath}'.`;
51 }
53​
54export class WorkspaceEntriesReadDirectoryError extends Schema.TaggedErrorClass<WorkspaceEntriesReadDirectoryError>()(
55 "WorkspaceEntriesReadDirectoryError",
56 {
57 cwd: Schema.optional(Schema.String),
58 partialPath: Schema.String,
59 parentPath: Schema.String,
60 cause: Schema.Defect(),
61 },
62) {
63 override get message(): string {
64 const cwd = this.cwd ? ` from '${this.cwd}'` : "";
65 return `Failed to read workspace directory '${this.parentPath}' while browsing '${this.partialPath}'${cwd}.`;
66 }
68​
69export const WorkspaceEntriesBrowseError = Schema.Union([
70 WorkspaceEntriesWindowsPathUnsupportedError,
71 WorkspaceEntriesCurrentProjectRequiredError,
72 WorkspaceEntriesReadDirectoryError,
73]);
74export type WorkspaceEntriesBrowseError = typeof WorkspaceEntriesBrowseError.Type;
75​
76export const WorkspaceEntriesError = Schema.Union([
77 WorkspacePaths.WorkspaceRootNotExistsError,
78 WorkspacePaths.WorkspaceRootCreateFailedError,
79 WorkspacePaths.WorkspaceRootStatFailedError,
80 WorkspacePaths.WorkspaceRootNotDirectoryError,
81 WorkspaceSearchIndex.WorkspaceSearchIndexCreateFailed,
82 WorkspaceSearchIndex.WorkspaceSearchIndexScanTimedOut,
83 WorkspaceSearchIndex.WorkspaceSearchIndexSearchFailed,
84]);
85export type WorkspaceEntriesError = typeof WorkspaceEntriesError.Type;
86​
87export class WorkspaceEntries extends Context.Service<
88 WorkspaceEntries,
89 {
90 readonly browse: (
91 input: FilesystemBrowseInput,
92 ) => Effect.Effect<FilesystemBrowseResult, WorkspaceEntriesBrowseError>;
93 readonly list: (
94 input: ProjectListEntriesInput,
95 ) => Effect.Effect<ProjectListEntriesResult, WorkspaceEntriesError>;
96 readonly search: (
97 input: ProjectSearchEntriesInput,
98 ) => Effect.Effect<ProjectSearchEntriesResult, WorkspaceEntriesError>;
99 readonly searchContents: (
100 input: ProjectSearchContentsInput,
101 ) => Effect.Effect<ProjectSearchContentsResult, WorkspaceEntriesError>;
102 readonly refresh: (cwd: string) => Effect.Effect<void>;
103 }
104>()("t3/workspace/WorkspaceEntries") {}
105​
106function expandHomePath(input: string, path: Path.Path): string {
107 if (input === "~") {
108 return NodeOS.homedir();
109 }
110 if (input.startsWith("~/") || input.startsWith("~\\")) {
111 return path.join(NodeOS.homedir(), input.slice(2));
112 }
113 return input;
115​
116const resolveBrowseTarget = Effect.fn("WorkspaceEntries.resolveBrowseTarget")(function* (
117 input: FilesystemBrowseInput,
118 path: Path.Path,
119): Effect.fn.Return<string, WorkspaceEntriesBrowseError> {
120 const platform = yield* HostProcessPlatform;
121 if (platform !== "win32" && isWindowsAbsolutePath(input.partialPath)) {
122 return yield* new WorkspaceEntriesWindowsPathUnsupportedError({
123 cwd: input.cwd,
124 partialPath: input.partialPath,
125 platform,
126 });
127 }
128​
129 if (!isExplicitRelativePath(input.partialPath)) {
130 return path.resolve(expandHomePath(input.partialPath, path));
131 }
132​
133 if (!input.cwd) {
134 return yield* new WorkspaceEntriesCurrentProjectRequiredError({
135 partialPath: input.partialPath,
136 });
137 }
138 return path.resolve(expandHomePath(input.cwd, path), input.partialPath);
139});
140​
141export const make = Effect.gen(function* () {
142 const path = yield* Path.Path;
143 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
144 const workspaceSearchIndexes = yield* WorkspaceSearchIndex.WorkspaceSearchIndexMap;
145​
146 const normalizeWorkspaceRoot = Effect.fn("WorkspaceEntries.normalizeWorkspaceRoot")(function* (
147 cwd: string,
148 ): Effect.fn.Return<string, WorkspaceEntriesError> {
149 return yield* workspacePaths.normalizeWorkspaceRoot(cwd);
150 });
151​
152 const refresh: WorkspaceEntries["Service"]["refresh"] = Effect.fn("WorkspaceEntries.refresh")(
153 function* (cwd) {
154 const normalizedCwd = yield* normalizeWorkspaceRoot(cwd).pipe(
155 Effect.orElseSucceed(() => cwd),
156 );
157 for (const variant of WorkspaceSearchIndex.WORKSPACE_SEARCH_INDEX_VARIANTS) {
158 const indexKey = WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, variant);
159 if (!(yield* RcMap.has(workspaceSearchIndexes.rcMap, indexKey))) {
160 continue;
161 }
162 const recoverRefreshFailure = (
163 cause:
164 | WorkspaceSearchIndex.WorkspaceSearchIndexCreateFailed
165 | WorkspaceSearchIndex.WorkspaceSearchIndexScanTimedOut
166 | WorkspaceSearchIndex.WorkspaceSearchIndexRefreshFailed,
167 ) =>
168 Effect.gen(function* () {
169 yield* Effect.logWarning("Failed to refresh workspace search index", {
170 cwd,
171 variant,
172 cause,
173 });
174 yield* workspaceSearchIndexes.invalidate(indexKey);
175 });
176 yield* Effect.gen(function* () {
177 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
178 yield* searchIndex.refresh();
179 }).pipe(
180 Effect.provide(workspaceSearchIndexes.get(indexKey)),
181 Effect.catchTags({
182 WorkspaceSearchIndexCreateFailed: recoverRefreshFailure,
183 WorkspaceSearchIndexScanTimedOut: recoverRefreshFailure,
184 WorkspaceSearchIndexRefreshFailed: recoverRefreshFailure,
185 }),
186 );
187 }
188 },
189 );
190​
191 const browse: WorkspaceEntries["Service"]["browse"] = Effect.fn("WorkspaceEntries.browse")(
192 function* (input) {
193 const resolvedInputPath = yield* resolveBrowseTarget(input, path);
194 const endsWithSeparator = /[\\/]$/.test(input.partialPath) || input.partialPath === "~";
195 const parentPath = endsWithSeparator ? resolvedInputPath : path.dirname(resolvedInputPath);
196 const prefix = endsWithSeparator ? "" : path.basename(resolvedInputPath);
197​
198 const dirents = yield* Effect.tryPromise({
199 try: () => NodeFSP.readdir(parentPath, { withFileTypes: true }),
200 catch: (cause) =>
201 new WorkspaceEntriesReadDirectoryError({
202 cwd: input.cwd,
203 partialPath: input.partialPath,
204 parentPath,
205 cause,
206 }),
207 }).pipe(
208 Effect.catchIf(
209 (error) => {
210 const code = (error.cause as NodeJS.ErrnoException | undefined)?.code;
211 return code === "EACCES" || code === "EPERM";
212 },
213 () => Effect.succeed([]),
214 ),
215 );
216​
217 const showHidden = endsWithSeparator || prefix.startsWith(".");
218 const lowerPrefix = prefix.toLowerCase();
219 const entries: Array<{ readonly name: string; readonly fullPath: string }> = [];
220 for (const dirent of dirents) {
221 if (
222 dirent.isDirectory() &&
223 dirent.name.toLowerCase().startsWith(lowerPrefix) &&
224 (showHidden || !dirent.name.startsWith("."))
225 ) {
226 entries.push({
227 name: dirent.name,
228 fullPath: path.join(parentPath, dirent.name),
229 });
230 }
231 }
232​
233 return {
234 parentPath,
235 entries: entries.toSorted((left, right) => left.name.localeCompare(right.name)),
236 };
237 },
238 );
239​
240 const search: WorkspaceEntries["Service"]["search"] = Effect.fn("WorkspaceEntries.search")(
241 function* (input) {
242 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
243 const normalizedQuery = normalizeSearchQuery(input.query, {
244 trimLeadingPattern: /^[@./]+/,
245 });
246 return yield* Effect.gen(function* () {
247 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
248 return yield* searchIndex.search(normalizedQuery, input.limit, input.kind, input.imageOnly);
249 }).pipe(
250 Effect.provide(
251 workspaceSearchIndexes.get(
252 WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, "paths"),
253 ),
254 ),
255 );
256 },
257 );
258​
259 const searchContents: WorkspaceEntries["Service"]["searchContents"] = Effect.fn(
260 "WorkspaceEntries.searchContents",
261 )(function* (input) {
262 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
263 return yield* Effect.gen(function* () {
264 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
265 return yield* searchIndex.searchContents(input);
266 }).pipe(
267 Effect.provide(
268 workspaceSearchIndexes.get(
269 WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, "content"),
270 ),
271 ),
272 );
273 });
274​
275 const list: WorkspaceEntries["Service"]["list"] = Effect.fn("WorkspaceEntries.list")(
276 function* (input) {
277 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
278 return yield* Effect.gen(function* () {
279 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
280 return yield* searchIndex.list();
281 }).pipe(
282 Effect.provide(
283 workspaceSearchIndexes.get(
284 WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, "paths"),
285 ),
286 ),
287 );
288 },
289 );
290​
291 return WorkspaceEntries.of({ browse, list, refresh, search, searchContents });
292});
293​
294export const layer = Layer.effect(WorkspaceEntries, make).pipe(
295 Layer.provide(WorkspaceSearchIndex.WorkspaceSearchIndexMap.layer),
296);