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

WorkspaceEntries.ts

396 lines15.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 ProjectEntry,
15 ProjectListEntriesInput,
16 ProjectListEntriesResult,
17 ProjectSearchContentsInput,
18 ProjectSearchContentsResult,
19 ProjectSearchEntriesInput,
20 ProjectSearchEntriesResult,
21} from "@t3tools/contracts";
22import * as HostProcess from "@t3tools/shared/HostProcess";
23import { isExplicitRelativePath, isWindowsAbsolutePath } from "@t3tools/shared/path";
24import { normalizeSearchQuery } from "@t3tools/shared/searchRanking";
25​
26import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
27import * as VcsProcess from "../vcs/VcsProcess.ts";
28import * as WorkspacePaths from "./WorkspacePaths.ts";
29import * as WorkspaceSearchIndex from "./WorkspaceSearchIndex.ts";
30​
31export class WorkspaceEntriesWindowsPathUnsupportedError extends Schema.TaggedError<WorkspaceEntriesWindowsPathUnsupportedError>()(
32 "WorkspaceEntriesWindowsPathUnsupportedError",
33 {
34 cwd: Schema.optional(Schema.String),
35 partialPath: Schema.String,
36 platform: Schema.String,
37 },
38) {
39 override get message(): string {
40 const cwd = this.cwd ? ` from '${this.cwd}'` : "";
41 return `Windows-style workspace path '${this.partialPath}' is not supported on '${this.platform}'${cwd}.`;
42 }
44​
45export class WorkspaceEntriesCurrentProjectRequiredError extends Schema.TaggedError<WorkspaceEntriesCurrentProjectRequiredError>()(
46 "WorkspaceEntriesCurrentProjectRequiredError",
47 {
48 partialPath: Schema.String,
49 },
50) {
51 override get message(): string {
52 return `A current project is required to browse relative workspace path '${this.partialPath}'.`;
53 }
55​
56export class WorkspaceEntriesReadDirectoryError extends Schema.TaggedError<WorkspaceEntriesReadDirectoryError>()(
57 "WorkspaceEntriesReadDirectoryError",
58 {
59 cwd: Schema.optional(Schema.String),
60 partialPath: Schema.String,
61 parentPath: Schema.String,
62 cause: Schema.Defect(),
63 },
64) {
65 override get message(): string {
66 const cwd = this.cwd ? ` from '${this.cwd}'` : "";
67 return `Failed to read workspace directory '${this.parentPath}' while browsing '${this.partialPath}'${cwd}.`;
68 }
70​
71export const WorkspaceEntriesBrowseError = Schema.Union([
72 WorkspaceEntriesWindowsPathUnsupportedError,
73 WorkspaceEntriesCurrentProjectRequiredError,
74 WorkspaceEntriesReadDirectoryError,
75]);
76export type WorkspaceEntriesBrowseError = typeof WorkspaceEntriesBrowseError.Type;
77​
78export const WorkspaceEntriesError = Schema.Union([
79 WorkspaceEntriesReadDirectoryError,
80 WorkspacePaths.WorkspaceRootNotExistsError,
81 WorkspacePaths.WorkspaceRootCreateFailedError,
82 WorkspacePaths.WorkspaceRootStatFailedError,
83 WorkspacePaths.WorkspaceRootNotDirectoryError,
84 WorkspaceSearchIndex.WorkspaceSearchIndexCreateFailed,
85 WorkspaceSearchIndex.WorkspaceSearchIndexScanTimedOut,
86 WorkspaceSearchIndex.WorkspaceSearchIndexSearchFailed,
87]);
88export type WorkspaceEntriesError = typeof WorkspaceEntriesError.Type;
89​
90export class WorkspaceEntries extends Context.Service<
91 WorkspaceEntries,
92 {
93 readonly browse: (
94 input: FilesystemBrowseInput,
95 ) => Effect.Effect<FilesystemBrowseResult, WorkspaceEntriesBrowseError>;
96 readonly list: (
97 input: ProjectListEntriesInput,
98 ) => Effect.Effect<ProjectListEntriesResult, WorkspaceEntriesError>;
99 readonly search: (
100 input: ProjectSearchEntriesInput,
101 ) => Effect.Effect<ProjectSearchEntriesResult, WorkspaceEntriesError>;
102 readonly searchContents: (
103 input: ProjectSearchContentsInput,
104 ) => Effect.Effect<ProjectSearchContentsResult, WorkspaceEntriesError>;
105 readonly refresh: (cwd: string) => Effect.Effect<void>;
106 }
107>()("t3/workspace/WorkspaceEntries") {}
108​
109/** Paths sent to one `git check-ignore` call when labelling a folder's children. */
110const IGNORE_CHECK_CHUNK_SIZE = 1000;
111​
112const resolveBrowseTarget = Effect.fn("WorkspaceEntries.resolveBrowseTarget")(function* (
113 input: FilesystemBrowseInput,
114 path: Path.Path,
115): Effect.fn.Return<string, WorkspaceEntriesBrowseError> {
116 const platform = yield* HostProcess.Platform;
117 if (platform !== "win32" && isWindowsAbsolutePath(input.partialPath)) {
118 return yield* new WorkspaceEntriesWindowsPathUnsupportedError({
119 cwd: input.cwd,
120 partialPath: input.partialPath,
121 platform,
122 });
123 }
124​
125 if (!isExplicitRelativePath(input.partialPath)) {
126 return path.resolve(expandHomePath(input.partialPath, yield* HostProcess.HomeDirectory));
127 }
128​
129 if (!input.cwd) {
130 return yield* new WorkspaceEntriesCurrentProjectRequiredError({
131 partialPath: input.partialPath,
132 });
133 }
134 return path.resolve(
135 expandHomePath(input.cwd, yield* HostProcess.HomeDirectory),
136 input.partialPath,
137 );
138});
139​
140/** @public Service construction is part of the canonical Effect module API. */
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 const vcsProcess = yield* VcsProcess.VcsProcess;
146​
147 const normalizeWorkspaceRoot = Effect.fn("WorkspaceEntries.normalizeWorkspaceRoot")(function* (
148 cwd: string,
149 ): Effect.fn.Return<string, WorkspaceEntriesError> {
150 return yield* workspacePaths.normalizeWorkspaceRoot(cwd);
151 });
152​
153 const refresh: WorkspaceEntries["Service"]["refresh"] = Effect.fn("WorkspaceEntries.refresh")(
154 function* (cwd) {
155 const normalizedCwd = yield* normalizeWorkspaceRoot(cwd).pipe(
156 Effect.orElseSucceed(() => cwd),
157 );
158 for (const variant of WorkspaceSearchIndex.WORKSPACE_SEARCH_INDEX_VARIANTS) {
159 const indexKey = WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, variant);
160 if (!(yield* RcMap.has(workspaceSearchIndexes.rcMap, indexKey))) {
161 continue;
162 }
163 const recoverRefreshFailure = (
164 cause:
165 | WorkspaceSearchIndex.WorkspaceSearchIndexCreateFailed
166 | WorkspaceSearchIndex.WorkspaceSearchIndexScanTimedOut
167 | WorkspaceSearchIndex.WorkspaceSearchIndexRefreshFailed,
168 ) =>
169 Effect.gen(function* () {
170 yield* Effect.logWarning("Failed to refresh workspace search index", {
171 cwd,
172 variant,
173 cause,
174 });
175 yield* workspaceSearchIndexes.invalidate(indexKey);
176 });
177 yield* Effect.gen(function* () {
178 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
179 yield* searchIndex.refresh();
180 }).pipe(
181 Effect.provide(workspaceSearchIndexes.get(indexKey)),
182 Effect.catchTags({
183 WorkspaceSearchIndexCreateFailed: recoverRefreshFailure,
184 WorkspaceSearchIndexScanTimedOut: recoverRefreshFailure,
185 WorkspaceSearchIndexRefreshFailed: recoverRefreshFailure,
186 }),
187 );
188 }
189 },
190 );
191​
192 const browse: WorkspaceEntries["Service"]["browse"] = Effect.fn("WorkspaceEntries.browse")(
193 function* (input) {
194 const resolvedInputPath = yield* resolveBrowseTarget(input, path);
195 const endsWithSeparator = /[\\/]$/.test(input.partialPath) || input.partialPath === "~";
196 const parentPath = endsWithSeparator ? resolvedInputPath : path.dirname(resolvedInputPath);
197 const prefix = endsWithSeparator ? "" : path.basename(resolvedInputPath);
198​
199 const dirents = yield* Effect.tryPromise({
200 try: () => NodeFSP.readdir(parentPath, { withFileTypes: true }),
201 catch: (cause) =>
202 new WorkspaceEntriesReadDirectoryError({
203 cwd: input.cwd,
204 partialPath: input.partialPath,
205 parentPath,
206 cause,
207 }),
208 }).pipe(
209 Effect.catchIf(
210 (error) => {
211 const code = (error.cause as NodeJS.ErrnoException | undefined)?.code;
212 return code === "EACCES" || code === "EPERM";
213 },
214 () => Effect.succeed([]),
215 ),
216 );
217​
218 const showHidden = endsWithSeparator || prefix.startsWith(".");
219 const lowerPrefix = prefix.toLowerCase();
220 const entries: Array<{ readonly name: string; readonly fullPath: string }> = [];
221 for (const dirent of dirents) {
222 if (
223 dirent.isDirectory() &&
224 dirent.name.toLowerCase().startsWith(lowerPrefix) &&
225 (showHidden || !dirent.name.startsWith("."))
226 ) {
227 entries.push({
228 name: dirent.name,
229 fullPath: path.join(parentPath, dirent.name),
230 });
231 }
232 }
233​
234 return {
235 parentPath,
236 entries: entries.toSorted((left, right) => left.name.localeCompare(right.name)),
237 };
238 },
239 );
240​
241 const search: WorkspaceEntries["Service"]["search"] = Effect.fn("WorkspaceEntries.search")(
242 function* (input) {
243 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
244 const normalizedQuery = normalizeSearchQuery(input.query, {
245 trimLeadingPattern: /^[@./]+/,
246 });
247 return yield* Effect.gen(function* () {
248 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
249 return yield* searchIndex.search(normalizedQuery, input.limit, input.kind, input.imageOnly);
250 }).pipe(
251 Effect.provide(
252 workspaceSearchIndexes.get(
253 WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, "paths"),
254 ),
255 ),
256 );
257 },
258 );
259​
260 const searchContents: WorkspaceEntries["Service"]["searchContents"] = Effect.fn(
261 "WorkspaceEntries.searchContents",
262 )(function* (input) {
263 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
264 return yield* Effect.gen(function* () {
265 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
266 return yield* searchIndex.searchContents(input);
267 }).pipe(
268 Effect.provide(
269 workspaceSearchIndexes.get(
270 WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, "content"),
271 ),
272 ),
273 );
274 });
275​
276 const list: WorkspaceEntries["Service"]["list"] = Effect.fn("WorkspaceEntries.list")(
277 function* (input) {
278 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
279 if (input.directoryPath !== undefined) {
280 const directoryPath = input.directoryPath;
281 const toError = (cause: unknown) =>
282 new WorkspaceEntriesReadDirectoryError({
283 cwd: normalizedCwd,
284 partialPath: directoryPath,
285 parentPath: path.resolve(normalizedCwd, directoryPath),
286 cause,
287 });
288 const target =
289 directoryPath === ""
290 ? { absolutePath: normalizedCwd, relativePath: "" }
291 : yield* workspacePaths
292 .resolveRelativePathWithinRoot({
293 workspaceRoot: normalizedCwd,
294 relativePath: directoryPath,
295 })
296 .pipe(Effect.mapError(toError));
297 const { entries, throughSymlink } = yield* Effect.tryPromise({
298 try: async () => {
299 const root = await NodeFSP.realpath(normalizedCwd);
300 const directory = await NodeFSP.realpath(target.absolutePath);
301 const relative = path.relative(root, directory);
302 if (
303 relative === ".." ||
304 relative.startsWith(`..${path.sep}`) ||
305 path.isAbsolute(relative) ||
306 relative.split(path.sep).includes(".git") ||
307 target.relativePath.split("/").includes(".git")
308 ) {
309 throw new Error("Directory must be inside the workspace and outside .git.");
310 }
311 const children = await NodeFSP.readdir(directory, { withFileTypes: true });
312 return {
313 entries: children.flatMap((child): ProjectEntry[] => {
314 if (child.name === ".git" || (!child.isDirectory() && !child.isFile())) return [];
315 return [
316 {
317 path: target.relativePath ? `${target.relativePath}/${child.name}` : child.name,
318 kind: child.isDirectory() ? "directory" : "file",
319 },
320 ];
321 }),
322 // Git refuses to classify paths beyond a symbolic link.
323 throughSymlink: relative !== target.relativePath.split("/").join(path.sep),
324 };
325 },
326 catch: toError,
327 });
328 // Use stdin so large directories cannot exceed the command-line argument limit.
329 // Ignore classification is optional in non-git workspaces or when git is unavailable.
330 const checkIgnore = (paths: ReadonlyArray<string>) =>
331 vcsProcess
332 .run({
333 operation: "WorkspaceEntries.list",
334 command: "git",
335 args: ["-c", "core.fsmonitor=false", "check-ignore", "-z", "--stdin"],
336 cwd: normalizedCwd,
337 stdin: `${paths.join("\0")}\0`,
338 allowNonZeroExit: true,
339 timeoutMs: 10_000,
340 maxOutputBytes: 16 * 1024 * 1024,
341 })
342 .pipe(Effect.orElseSucceed(() => undefined));
343 // Git consults the index for every path it classifies, which costs hundreds of
344 // milliseconds for a `node_modules`-sized folder. Asking about the folder itself answers
345 // for every child: `check-ignore` exits 0 only when the folder is ignored and nothing
346 // under it is tracked, and an ignored folder hides all of its children. Git reads paths as
347 // pathspecs, so a folder whose path has magic (`:foo`) or glob (`[id]`) characters, or
348 // one reached through a symlink, can get a different answer per child and still asks git
349 // about each.
350 if (
351 entries.length > IGNORE_CHECK_CHUNK_SIZE &&
352 target.relativePath !== "" &&
353 !throughSymlink &&
354 !/^:|[*?[\\]/.test(target.relativePath) &&
355 (yield* checkIgnore([target.relativePath]))?.exitCode === 0
356 ) {
357 return {
358 entries: entries.map((entry) => ({ ...entry, ignored: true })),
359 truncated: false,
360 };
361 }
362 const ignored = new Set<string>();
363 for (let offset = 0; offset < entries.length; offset += IGNORE_CHECK_CHUNK_SIZE) {
364 const result = yield* checkIgnore(
365 entries.slice(offset, offset + IGNORE_CHECK_CHUNK_SIZE).map((entry) => entry.path),
366 );
367 if (!result || (result.exitCode !== 0 && result.exitCode !== 1)) break;
368 for (const ignoredPath of result.stdout.split("\0")) ignored.add(ignoredPath);
369 }
370 return {
371 entries: entries.map((entry) =>
372 ignored.has(entry.path) ? { ...entry, ignored: true } : entry,
373 ),
374 truncated: false,
375 };
376 }
377 return yield* Effect.gen(function* () {
378 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
379 return yield* searchIndex.list();
380 }).pipe(
381 Effect.provide(
382 workspaceSearchIndexes.get(
383 WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, "paths"),
384 ),
385 ),
386 );
387 },
388 );
389​
390 return WorkspaceEntries.of({ browse, list, refresh, search, searchContents });
391});
392​
393export const layer = Layer.effect(WorkspaceEntries, make).pipe(
394 Layer.provide(WorkspaceSearchIndex.WorkspaceSearchIndexMap.layer),
395 Layer.provide(VcsProcess.layer),
396);