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

WorkspaceEntries.ts

286 lines10.4 KB

1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeFSP from "node:fs/promises";
3​
4import * as Context from "effect/Context";
5import * as Effect from "effect/Effect";
6import * as Layer from "effect/Layer";
7import * as Path from "effect/Path";
8import * as RcMap from "effect/RcMap";
9import * as Schema from "effect/Schema";
10​
11import type {
12 FilesystemBrowseInput,
13 FilesystemBrowseResult,
14 ProjectListEntriesInput,
15 ProjectListEntriesResult,
16 ProjectSearchContentsInput,
17 ProjectSearchContentsResult,
18 ProjectSearchEntriesInput,
19 ProjectSearchEntriesResult,
20} from "@t3tools/contracts";
21import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
22import { isExplicitRelativePath, isWindowsAbsolutePath } from "@t3tools/shared/path";
23import { normalizeSearchQuery } from "@t3tools/shared/searchRanking";
24​
25import { expandHomePathWith } from "../pathExpansion.ts";
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​
106const resolveBrowseTarget = Effect.fn("WorkspaceEntries.resolveBrowseTarget")(function* (
107 input: FilesystemBrowseInput,
108 path: Path.Path,
109): Effect.fn.Return<string, WorkspaceEntriesBrowseError> {
110 const platform = yield* HostProcessPlatform;
111 if (platform !== "win32" && isWindowsAbsolutePath(input.partialPath)) {
112 return yield* new WorkspaceEntriesWindowsPathUnsupportedError({
113 cwd: input.cwd,
114 partialPath: input.partialPath,
115 platform,
116 });
117 }
118​
119 if (!isExplicitRelativePath(input.partialPath)) {
120 return path.resolve(expandHomePathWith(input.partialPath, path));
121 }
122​
123 if (!input.cwd) {
124 return yield* new WorkspaceEntriesCurrentProjectRequiredError({
125 partialPath: input.partialPath,
126 });
127 }
128 return path.resolve(expandHomePathWith(input.cwd, path), input.partialPath);
129});
130​
131export const make = Effect.gen(function* () {
132 const path = yield* Path.Path;
133 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
134 const workspaceSearchIndexes = yield* WorkspaceSearchIndex.WorkspaceSearchIndexMap;
135​
136 const normalizeWorkspaceRoot = Effect.fn("WorkspaceEntries.normalizeWorkspaceRoot")(function* (
137 cwd: string,
138 ): Effect.fn.Return<string, WorkspaceEntriesError> {
139 return yield* workspacePaths.normalizeWorkspaceRoot(cwd);
140 });
141​
142 const refresh: WorkspaceEntries["Service"]["refresh"] = Effect.fn("WorkspaceEntries.refresh")(
143 function* (cwd) {
144 const normalizedCwd = yield* normalizeWorkspaceRoot(cwd).pipe(
145 Effect.orElseSucceed(() => cwd),
146 );
147 for (const variant of WorkspaceSearchIndex.WORKSPACE_SEARCH_INDEX_VARIANTS) {
148 const indexKey = WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, variant);
149 if (!(yield* RcMap.has(workspaceSearchIndexes.rcMap, indexKey))) {
150 continue;
151 }
152 const recoverRefreshFailure = (
153 cause:
154 | WorkspaceSearchIndex.WorkspaceSearchIndexCreateFailed
155 | WorkspaceSearchIndex.WorkspaceSearchIndexScanTimedOut
156 | WorkspaceSearchIndex.WorkspaceSearchIndexRefreshFailed,
157 ) =>
158 Effect.gen(function* () {
159 yield* Effect.logWarning("Failed to refresh workspace search index", {
160 cwd,
161 variant,
162 cause,
163 });
164 yield* workspaceSearchIndexes.invalidate(indexKey);
165 });
166 yield* Effect.gen(function* () {
167 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
168 yield* searchIndex.refresh();
169 }).pipe(
170 Effect.provide(workspaceSearchIndexes.get(indexKey)),
171 Effect.catchTags({
172 WorkspaceSearchIndexCreateFailed: recoverRefreshFailure,
173 WorkspaceSearchIndexScanTimedOut: recoverRefreshFailure,
174 WorkspaceSearchIndexRefreshFailed: recoverRefreshFailure,
175 }),
176 );
177 }
178 },
179 );
180​
181 const browse: WorkspaceEntries["Service"]["browse"] = Effect.fn("WorkspaceEntries.browse")(
182 function* (input) {
183 const resolvedInputPath = yield* resolveBrowseTarget(input, path);
184 const endsWithSeparator = /[\\/]$/.test(input.partialPath) || input.partialPath === "~";
185 const parentPath = endsWithSeparator ? resolvedInputPath : path.dirname(resolvedInputPath);
186 const prefix = endsWithSeparator ? "" : path.basename(resolvedInputPath);
187​
188 const dirents = yield* Effect.tryPromise({
189 try: () => NodeFSP.readdir(parentPath, { withFileTypes: true }),
190 catch: (cause) =>
191 new WorkspaceEntriesReadDirectoryError({
192 cwd: input.cwd,
193 partialPath: input.partialPath,
194 parentPath,
195 cause,
196 }),
197 }).pipe(
198 Effect.catchIf(
199 (error) => {
200 const code = (error.cause as NodeJS.ErrnoException | undefined)?.code;
201 return code === "EACCES" || code === "EPERM";
202 },
203 () => Effect.succeed([]),
204 ),
205 );
206​
207 const showHidden = endsWithSeparator || prefix.startsWith(".");
208 const lowerPrefix = prefix.toLowerCase();
209 const entries: Array<{ readonly name: string; readonly fullPath: string }> = [];
210 for (const dirent of dirents) {
211 if (
212 dirent.isDirectory() &&
213 dirent.name.toLowerCase().startsWith(lowerPrefix) &&
214 (showHidden || !dirent.name.startsWith("."))
215 ) {
216 entries.push({
217 name: dirent.name,
218 fullPath: path.join(parentPath, dirent.name),
219 });
220 }
221 }
222​
223 return {
224 parentPath,
225 entries: entries.toSorted((left, right) => left.name.localeCompare(right.name)),
226 };
227 },
228 );
229​
230 const search: WorkspaceEntries["Service"]["search"] = Effect.fn("WorkspaceEntries.search")(
231 function* (input) {
232 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
233 const normalizedQuery = normalizeSearchQuery(input.query, {
234 trimLeadingPattern: /^[@./]+/,
235 });
236 return yield* Effect.gen(function* () {
237 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
238 return yield* searchIndex.search(normalizedQuery, input.limit, input.kind, input.imageOnly);
239 }).pipe(
240 Effect.provide(
241 workspaceSearchIndexes.get(
242 WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, "paths"),
243 ),
244 ),
245 );
246 },
247 );
248​
249 const searchContents: WorkspaceEntries["Service"]["searchContents"] = Effect.fn(
250 "WorkspaceEntries.searchContents",
251 )(function* (input) {
252 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
253 return yield* Effect.gen(function* () {
254 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
255 return yield* searchIndex.searchContents(input);
256 }).pipe(
257 Effect.provide(
258 workspaceSearchIndexes.get(
259 WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, "content"),
260 ),
261 ),
262 );
263 });
264​
265 const list: WorkspaceEntries["Service"]["list"] = Effect.fn("WorkspaceEntries.list")(
266 function* (input) {
267 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
268 return yield* Effect.gen(function* () {
269 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
270 return yield* searchIndex.list();
271 }).pipe(
272 Effect.provide(
273 workspaceSearchIndexes.get(
274 WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, "paths"),
275 ),
276 ),
277 );
278 },
279 );
280​
281 return WorkspaceEntries.of({ browse, list, refresh, search, searchContents });
282});
283​
284export const layer = Layer.effect(WorkspaceEntries, make).pipe(
285 Layer.provide(WorkspaceSearchIndex.WorkspaceSearchIndexMap.layer),
286);