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

WorkspaceEntries.ts

617 lines24.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 ProjectListIgnoredFilesInput,
18 ProjectListIgnoredFilesResult,
19 ProjectSearchContentsInput,
20 ProjectSearchContentsResult,
21 ProjectSearchEntriesInput,
22 ProjectSearchEntriesResult,
23} from "@t3tools/contracts";
24import * as HostProcess from "@t3tools/shared/HostProcess";
25import { isExplicitRelativePath, isWindowsAbsolutePath } from "@t3tools/shared/path";
26import { normalizeSearchQuery } from "@t3tools/shared/searchRanking";
27​
28import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
29import * as VcsProcess from "../vcs/VcsProcess.ts";
30import * as WorkspacePaths from "./WorkspacePaths.ts";
31import * as WorkspaceSearchIndex from "./WorkspaceSearchIndex.ts";
32​
33export class WorkspaceEntriesWindowsPathUnsupportedError extends Schema.TaggedError<WorkspaceEntriesWindowsPathUnsupportedError>()(
34 "WorkspaceEntriesWindowsPathUnsupportedError",
35 {
36 cwd: Schema.optional(Schema.String),
37 partialPath: Schema.String,
38 platform: Schema.String,
39 },
40) {
41 override get message(): string {
42 const cwd = this.cwd ? ` from '${this.cwd}'` : "";
43 return `Windows-style workspace path '${this.partialPath}' is not supported on '${this.platform}'${cwd}.`;
44 }
46​
47export class WorkspaceEntriesCurrentProjectRequiredError extends Schema.TaggedError<WorkspaceEntriesCurrentProjectRequiredError>()(
48 "WorkspaceEntriesCurrentProjectRequiredError",
49 {
50 partialPath: Schema.String,
51 },
52) {
53 override get message(): string {
54 return `A current project is required to browse relative workspace path '${this.partialPath}'.`;
55 }
57​
58export class WorkspaceEntriesReadDirectoryError extends Schema.TaggedError<WorkspaceEntriesReadDirectoryError>()(
59 "WorkspaceEntriesReadDirectoryError",
60 {
61 cwd: Schema.optional(Schema.String),
62 partialPath: Schema.String,
63 parentPath: Schema.String,
64 cause: Schema.Defect(),
65 },
66) {
67 get pathMissing(): boolean {
68 return (this.cause as NodeJS.ErrnoException | undefined)?.code === "ENOENT";
69 }
70​
71 override get message(): string {
72 const cwd = this.cwd ? ` from '${this.cwd}'` : "";
73 return `Failed to read workspace directory '${this.parentPath}' while browsing '${this.partialPath}'${cwd}.`;
74 }
76​
77export const WorkspaceEntriesBrowseError = Schema.Union([
78 WorkspaceEntriesWindowsPathUnsupportedError,
79 WorkspaceEntriesCurrentProjectRequiredError,
80 WorkspaceEntriesReadDirectoryError,
81]);
82export type WorkspaceEntriesBrowseError = typeof WorkspaceEntriesBrowseError.Type;
83​
84export const WorkspaceEntriesError = Schema.Union([
85 WorkspaceEntriesReadDirectoryError,
86 WorkspacePaths.WorkspaceRootNotExistsError,
87 WorkspacePaths.WorkspaceRootCreateFailedError,
88 WorkspacePaths.WorkspaceRootStatFailedError,
89 WorkspacePaths.WorkspaceRootNotDirectoryError,
90 WorkspaceSearchIndex.WorkspaceSearchIndexCreateFailed,
91 WorkspaceSearchIndex.WorkspaceSearchIndexScanTimedOut,
92 WorkspaceSearchIndex.WorkspaceSearchIndexSearchFailed,
93]);
94export type WorkspaceEntriesError = typeof WorkspaceEntriesError.Type;
95​
96export class WorkspaceEntries extends Context.Service<
97 WorkspaceEntries,
98 {
99 readonly browse: (
100 input: FilesystemBrowseInput,
101 ) => Effect.Effect<FilesystemBrowseResult, WorkspaceEntriesBrowseError>;
102 readonly list: (
103 input: ProjectListEntriesInput,
104 ) => Effect.Effect<ProjectListEntriesResult, WorkspaceEntriesError>;
105 readonly search: (
106 input: ProjectSearchEntriesInput,
107 ) => Effect.Effect<ProjectSearchEntriesResult, WorkspaceEntriesError>;
108 readonly listIgnoredFiles: (
109 input: ProjectListIgnoredFilesInput,
110 ) => Effect.Effect<ProjectListIgnoredFilesResult, WorkspaceEntriesError>;
111 readonly searchContents: (
112 input: ProjectSearchContentsInput,
113 ) => Effect.Effect<ProjectSearchContentsResult, WorkspaceEntriesError>;
114 readonly refresh: (cwd: string) => Effect.Effect<void>;
115 }
116>()("t3/workspace/WorkspaceEntries") {}
117​
118/** Ignored files offered for copying; more than this is a build folder, not config. */
119const IGNORED_FILES_LIMIT = 200;
120​
121/** Paths sent to one `git check-ignore` call when labelling a folder's children. */
122const IGNORE_CHECK_CHUNK_SIZE = 1000;
123​
124/** Children classified at once when listing a folder; each symlink costs a realpath and a stat. */
125const SYMLINK_RESOLVE_BATCH_SIZE = 64;
126​
127const resolveBrowseTarget = Effect.fn("WorkspaceEntries.resolveBrowseTarget")(function* (
128 input: FilesystemBrowseInput,
129 path: Path.Path,
130): Effect.fn.Return<string, WorkspaceEntriesBrowseError> {
131 const platform = yield* HostProcess.Platform;
132 if (platform !== "win32" && isWindowsAbsolutePath(input.partialPath)) {
133 return yield* new WorkspaceEntriesWindowsPathUnsupportedError({
134 cwd: input.cwd,
135 partialPath: input.partialPath,
136 platform,
137 });
138 }
139​
140 if (!isExplicitRelativePath(input.partialPath)) {
141 return path.resolve(expandHomePath(input.partialPath, yield* HostProcess.HomeDirectory));
142 }
143​
144 if (!input.cwd) {
145 return yield* new WorkspaceEntriesCurrentProjectRequiredError({
146 partialPath: input.partialPath,
147 });
148 }
149 return path.resolve(
150 expandHomePath(input.cwd, yield* HostProcess.HomeDirectory),
151 input.partialPath,
152 );
153});
154​
155/** @public */
156export const make = Effect.gen(function* () {
157 const path = yield* Path.Path;
158 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
159 const workspaceSearchIndexes = yield* WorkspaceSearchIndex.WorkspaceSearchIndexMap;
160 const vcsProcess = yield* VcsProcess.VcsProcess;
161​
162 const normalizeWorkspaceRoot = Effect.fn("WorkspaceEntries.normalizeWorkspaceRoot")(function* (
163 cwd: string,
164 ): Effect.fn.Return<string, WorkspaceEntriesError> {
165 return yield* workspacePaths.normalizeWorkspaceRoot(cwd);
166 });
167​
168 const refresh: WorkspaceEntries["Service"]["refresh"] = Effect.fn("WorkspaceEntries.refresh")(
169 function* (cwd) {
170 const normalizedCwd = yield* normalizeWorkspaceRoot(cwd).pipe(
171 Effect.orElseSucceed(() => cwd),
172 );
173 for (const variant of WorkspaceSearchIndex.WORKSPACE_SEARCH_INDEX_VARIANTS) {
174 const indexKey = WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, variant);
175 if (!(yield* RcMap.has(workspaceSearchIndexes.rcMap, indexKey))) {
176 continue;
177 }
178 const recoverRefreshFailure = Effect.fn("WorkspaceEntries.recoverRefreshFailure")(
179 function* (
180 cause:
181 | WorkspaceSearchIndex.WorkspaceSearchIndexCreateFailed
182 | WorkspaceSearchIndex.WorkspaceSearchIndexScanTimedOut
183 | WorkspaceSearchIndex.WorkspaceSearchIndexRefreshFailed,
184 ) {
185 yield* Effect.logWarning("Failed to refresh workspace search index", {
186 cwd,
187 variant,
188 cause,
189 });
190 yield* workspaceSearchIndexes.invalidate(indexKey);
191 },
192 );
193 yield* Effect.gen(function* () {
194 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
195 yield* searchIndex.refresh();
196 }).pipe(
197 Effect.provide(workspaceSearchIndexes.get(indexKey)),
198 Effect.catchTags({
199 WorkspaceSearchIndexCreateFailed: recoverRefreshFailure,
200 WorkspaceSearchIndexScanTimedOut: recoverRefreshFailure,
201 WorkspaceSearchIndexRefreshFailed: recoverRefreshFailure,
202 }),
203 );
204 }
205 },
206 );
207​
208 const browse: WorkspaceEntries["Service"]["browse"] = Effect.fn("WorkspaceEntries.browse")(
209 function* (input) {
210 const resolvedInputPath = yield* resolveBrowseTarget(input, path);
211 const endsWithSeparator = /[\\/]$/.test(input.partialPath) || input.partialPath === "~";
212 const parentPath = endsWithSeparator ? resolvedInputPath : path.dirname(resolvedInputPath);
213 const prefix = endsWithSeparator ? "" : path.basename(resolvedInputPath);
214​
215 const dirents = yield* Effect.tryPromise({
216 try: () => NodeFSP.readdir(parentPath, { withFileTypes: true }),
217 catch: (cause) =>
218 new WorkspaceEntriesReadDirectoryError({
219 cwd: input.cwd,
220 partialPath: input.partialPath,
221 parentPath,
222 cause,
223 }),
224 }).pipe(
225 Effect.catchIf(
226 (error) => {
227 const code = (error.cause as NodeJS.ErrnoException | undefined)?.code;
228 return code === "EACCES" || code === "EPERM";
229 },
230 () => Effect.succeed([]),
231 ),
232 );
233​
234 const showHidden = endsWithSeparator || prefix.startsWith(".");
235 const lowerPrefix = prefix.toLowerCase();
236 const entries: Array<{ readonly name: string; readonly fullPath: string }> = [];
237 for (const dirent of dirents) {
238 if (
239 dirent.isDirectory() &&
240 dirent.name.toLowerCase().startsWith(lowerPrefix) &&
241 (showHidden || !dirent.name.startsWith("."))
242 ) {
243 entries.push({
244 name: dirent.name,
245 fullPath: path.join(parentPath, dirent.name),
246 });
247 }
248 }
249​
250 return {
251 parentPath,
252 entries: entries.toSorted((left, right) => left.name.localeCompare(right.name)),
253 };
254 },
255 );
256​
257 const search: WorkspaceEntries["Service"]["search"] = Effect.fn("WorkspaceEntries.search")(
258 function* (input) {
259 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
260 const normalizedQuery = normalizeSearchQuery(input.query, {
261 trimLeadingPattern: /^[@./]+/,
262 });
263 const result = yield* Effect.gen(function* () {
264 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
265 return yield* searchIndex.search(normalizedQuery, input.limit, input.kind, input.imageOnly);
266 }).pipe(
267 Effect.provide(
268 workspaceSearchIndexes.get(
269 WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, "paths"),
270 ),
271 ),
272 );
273 if (input.kind === "directory" || input.imageOnly) return result;
274 const worktreeFiles = yield* findNestedWorktreeFiles(
275 normalizedCwd,
276 input.query,
277 result.entries,
278 );
279 if (worktreeFiles.length === 0) return result;
280 const entries = [...worktreeFiles, ...result.entries];
281 return {
282 entries: entries.slice(0, input.limit),
283 truncated: result.truncated || entries.length > input.limit,
284 };
285 },
286 );
287​
288 // The index skips gitignored folders, where agents often put worktrees (`.worktrees/x`).
289 // A path relative to such a worktree is found only when it names an existing file exactly.
290 const findNestedWorktreeFiles = Effect.fn("WorkspaceEntries.findNestedWorktreeFiles")(function* (
291 cwd: string,
292 query: string,
293 indexed: ReadonlyArray<ProjectEntry>,
294 ) {
295 const relativePath = query.trim().replaceAll("\\", "/");
296 if (
297 !relativePath.includes("/") ||
298 relativePath.endsWith("/") ||
299 path.isAbsolute(relativePath) ||
300 isWindowsAbsolutePath(relativePath) ||
301 relativePath.split("/").some((segment) => segment === "..") ||
302 indexed.some(
303 (entry) =>
304 entry.kind === "file" &&
305 (entry.path === relativePath || entry.path.endsWith(`/${relativePath}`)),
306 )
307 ) {
308 return [];
309 }
310 const listWorktrees = (args: ReadonlyArray<string>) =>
311 vcsProcess
312 .run({
313 operation: "WorkspaceEntries.listWorktrees",
314 command: "git",
315 args: ["worktree", "list", "--porcelain", ...args],
316 cwd,
317 allowNonZeroExit: true,
318 timeoutMs: 5_000,
319 })
320 .pipe(
321 Effect.map((result) => (result.exitCode === 0 ? result.stdout : undefined)),
322 Effect.orElseSucceed(() => undefined),
323 );
324 // Only NUL framing keeps a newline in a worktree path. Pre-2.36 Git rejects `-z`.
325 const listed =
326 (yield* listWorktrees(["-z"])) ?? (yield* listWorktrees([]))?.replaceAll("\n", "\0");
327 if (listed === undefined) return [];
328 const realCwd = yield* Effect.promise(() => NodeFSP.realpath(cwd).catch(() => cwd));
329 const worktreeRoots = listed.split("\0\0").flatMap((record) => {
330 const fields = record.split("\0");
331 const worktree = fields.find((field) => field.startsWith("worktree "));
332 // A `prunable` record's directory is gone; another checkout may now sit there.
333 if (worktree === undefined || fields.some((field) => field.startsWith("prunable"))) return [];
334 const root = worktree.slice("worktree ".length);
335 const relativeRoot = path.relative(realCwd, root);
336 return relativeRoot === "" ||
337 relativeRoot === ".." ||
338 relativeRoot.startsWith(`..${path.sep}`) ||
339 path.isAbsolute(relativeRoot)
340 ? []
341 : [relativeRoot.split(path.sep).join("/")];
342 });
343 const matches = yield* Effect.promise(() =>
344 Promise.all(
345 worktreeRoots.map(async (relativeRoot) => {
346 const candidate = `${relativeRoot}/${relativePath}`;
347 const stat = await NodeFSP.stat(path.join(realCwd, candidate)).catch(() => null);
348 return stat?.isFile() ? candidate : null;
349 }),
350 ),
351 );
352 return matches
353 .filter((candidate) => candidate !== null)
354 .map((candidate): ProjectEntry => ({ path: candidate, kind: "file" }));
355 });
356​
357 const searchContents: WorkspaceEntries["Service"]["searchContents"] = Effect.fn(
358 "WorkspaceEntries.searchContents",
359 )(function* (input) {
360 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
361 return yield* Effect.gen(function* () {
362 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
363 return yield* searchIndex.searchContents(input);
364 }).pipe(
365 Effect.provide(
366 workspaceSearchIndexes.get(
367 WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, "content"),
368 ),
369 ),
370 );
371 });
372​
373 const list: WorkspaceEntries["Service"]["list"] = Effect.fn("WorkspaceEntries.list")(
374 function* (input) {
375 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
376 if (input.directoryPath !== undefined) {
377 const directoryPath = input.directoryPath;
378 const toError = (cause: unknown) =>
379 new WorkspaceEntriesReadDirectoryError({
380 cwd: normalizedCwd,
381 partialPath: directoryPath,
382 parentPath: path.resolve(normalizedCwd, directoryPath),
383 cause,
384 });
385 const target =
386 directoryPath === ""
387 ? { absolutePath: normalizedCwd, relativePath: "" }
388 : yield* workspacePaths
389 .resolveRelativePathWithinRoot({
390 workspaceRoot: normalizedCwd,
391 relativePath: directoryPath,
392 })
393 .pipe(Effect.mapError(toError));
394 const { entries, throughSymlink, nestedGitRoots } = yield* Effect.tryPromise({
395 try: async () => {
396 const root = await NodeFSP.realpath(normalizedCwd);
397 const directory = await NodeFSP.realpath(target.absolutePath);
398 const relative = path.relative(root, directory);
399 if (
400 relative === ".." ||
401 relative.startsWith(`..${path.sep}`) ||
402 path.isAbsolute(relative) ||
403 relative.split(path.sep).includes(".git") ||
404 target.relativePath.split("/").includes(".git")
405 ) {
406 throw new Error("Directory must be inside the workspace and outside .git.");
407 }
408 const children = await NodeFSP.readdir(directory, { withFileTypes: true });
409 const isSameOrInside = (parent: string, child: string) => {
410 const relativeChild = path.relative(parent, child);
411 return (
412 relativeChild !== ".." &&
413 !relativeChild.startsWith(`..${path.sep}`) &&
414 !path.isAbsolute(relativeChild)
415 );
416 };
417 // Reject canonical ancestors so "Expand all folders" cannot follow a cycle.
418 let visitedFolders: Promise<ReadonlyArray<string>> | undefined;
419 const loadVisitedFolders = () =>
420 (visitedFolders ??= (async () => {
421 const folders = [root];
422 let current = normalizedCwd;
423 for (const segment of target.relativePath.split("/").filter(Boolean)) {
424 current = path.join(current, segment);
425 folders.push(await NodeFSP.realpath(current));
426 }
427 return folders;
428 })());
429 const resolveSymlinkKind = async (
430 name: string,
431 ): Promise<ProjectEntry["kind"] | undefined> => {
432 const resolved = await NodeFSP.realpath(path.join(directory, name)).catch(
433 () => undefined,
434 );
435 if (
436 resolved === undefined ||
437 !isSameOrInside(root, resolved) ||
438 path.relative(root, resolved).split(path.sep).includes(".git")
439 ) {
440 return undefined;
441 }
442 const stat = await NodeFSP.stat(resolved).catch(() => undefined);
443 if (stat?.isFile()) return "file";
444 if (!stat?.isDirectory()) return undefined;
445 const folders = await loadVisitedFolders();
446 return folders.some((folder) => isSameOrInside(resolved, folder))
447 ? undefined
448 : "directory";
449 };
450 // Bound filesystem work for directories such as pnpm node_modules.
451 const kinds: Array<ProjectEntry["kind"] | undefined> = [];
452 for (let offset = 0; offset < children.length; offset += SYMLINK_RESOLVE_BATCH_SIZE) {
453 kinds.push(
454 ...(await Promise.all(
455 children
456 .slice(offset, offset + SYMLINK_RESOLVE_BATCH_SIZE)
457 .map(async (child): Promise<ProjectEntry["kind"] | undefined> => {
458 if (child.name === ".git") return undefined;
459 if (child.isDirectory()) return "directory";
460 if (child.isFile()) return "file";
461 return child.isSymbolicLink() ? resolveSymlinkKind(child.name) : undefined;
462 }),
463 )),
464 );
465 }
466 const nestedGitRoots: Array<string> = [];
467 const segments = target.relativePath.split("/").filter(Boolean);
468 for (let index = 1; index <= segments.length; index += 1) {
469 const candidate = segments.slice(0, index).join("/");
470 const dotGit = await NodeFSP.lstat(path.join(normalizedCwd, candidate, ".git")).catch(
471 () => null,
472 );
473 if (dotGit) nestedGitRoots.push(candidate);
474 }
475 return {
476 nestedGitRoots,
477 entries: children.flatMap((child, index): ProjectEntry[] => {
478 const kind = kinds[index];
479 if (kind === undefined) return [];
480 return [
481 {
482 path: target.relativePath ? `${target.relativePath}/${child.name}` : child.name,
483 kind,
484 },
485 ];
486 }),
487 // Git refuses to classify paths beyond a symbolic link.
488 throughSymlink: relative !== target.relativePath.split("/").join(path.sep),
489 };
490 },
491 catch: toError,
492 });
493 let gitRoot = "";
494 let gitPrefix = "";
495 // stdin avoids argument limits; ignore classification is optional without git/repositories.
496 const checkIgnore = (paths: ReadonlyArray<string>) =>
497 vcsProcess
498 .run({
499 operation: "WorkspaceEntries.list",
500 command: "git",
501 args: ["-c", "core.fsmonitor=false", "check-ignore", "-z", "--stdin"],
502 cwd: path.join(normalizedCwd, gitRoot),
503 stdin: `${paths.map((entryPath) => entryPath.slice(gitPrefix.length)).join("\0")}\0`,
504 allowNonZeroExit: true,
505 timeoutMs: 10_000,
506 maxOutputBytes: 16 * 1024 * 1024,
507 })
508 .pipe(Effect.orElseSucceed(() => undefined));
509 // Git refuses paths inside a submodule (128) but still answers for nested clones.
510 for (const nestedGitRoot of nestedGitRoots) {
511 if ((yield* checkIgnore([`${nestedGitRoot}/.git`]))?.exitCode !== 128) continue;
512 gitRoot = nestedGitRoot;
513 gitPrefix = `${gitRoot}/`;
514 }
515 const directoryGitPath = target.relativePath.slice(gitPrefix.length);
516 // Check ignored folders once to avoid child index lookups; exit 0 guarantees no tracked descendants.
517 // Symlinks and pathspec magic still need per-child checks.
518 if (
519 entries.length > IGNORE_CHECK_CHUNK_SIZE &&
520 directoryGitPath !== "" &&
521 !throughSymlink &&
522 !/^:|[*?[\\]/.test(directoryGitPath) &&
523 (yield* checkIgnore([target.relativePath]))?.exitCode === 0
524 ) {
525 return {
526 entries: entries.map((entry) => ({ ...entry, ignored: true })),
527 truncated: false,
528 };
529 }
530 const ignored = new Set<string>();
531 for (let offset = 0; offset < entries.length; offset += IGNORE_CHECK_CHUNK_SIZE) {
532 const result = yield* checkIgnore(
533 entries.slice(offset, offset + IGNORE_CHECK_CHUNK_SIZE).map((entry) => entry.path),
534 );
535 if (!result || (result.exitCode !== 0 && result.exitCode !== 1)) break;
536 for (const ignoredPath of result.stdout.split("\0")) ignored.add(gitPrefix + ignoredPath);
537 }
538 return {
539 entries: entries.map((entry) =>
540 ignored.has(entry.path) ? { ...entry, ignored: true } : entry,
541 ),
542 truncated: false,
543 };
544 }
545 return yield* Effect.gen(function* () {
546 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
547 return yield* searchIndex.list();
548 }).pipe(
549 Effect.provide(
550 workspaceSearchIndexes.get(
551 WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, "paths"),
552 ),
553 ),
554 );
555 },
556 );
557​
558 const listIgnoredFiles: WorkspaceEntries["Service"]["listIgnoredFiles"] = Effect.fn(
559 "WorkspaceEntries.listIgnoredFiles",
560 )(function* (input) {
561 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
562 // `--directory` reports a folder holding nothing but ignored files as one
563 // `name/` entry, which is how `node_modules` and build output drop out.
564 const result = yield* vcsProcess
565 .run({
566 operation: "WorkspaceEntries.listIgnoredFiles",
567 command: "git",
568 args: [
569 "-c",
570 "core.fsmonitor=false",
571 "ls-files",
572 "--others",
573 "--ignored",
574 "--exclude-standard",
575 "--directory",
576 "--no-empty-directory",
577 "-z",
578 ],
579 cwd: normalizedCwd,
580 allowNonZeroExit: true,
581 timeoutMs: 10_000,
582 maxOutputBytes: 4 * 1024 * 1024,
583 })
584 .pipe(Effect.orElseSucceed(() => undefined));
585 if (!result || result.exitCode !== 0) return { files: [], truncated: false };
586 // Filter before the cap so files sorting past it stay reachable by search.
587 const query = input.query?.toLowerCase() ?? "";
588 const paths = result.stdout
589 .split("\0")
590 .filter(
591 (entry) => entry.length > 0 && !entry.endsWith("/") && entry.toLowerCase().includes(query),
592 )
593 .toSorted();
594 const files = yield* Effect.promise(() =>
595 Promise.all(
596 paths.slice(0, IGNORED_FILES_LIMIT).map(async (relativePath) => {
597 // lstat: a symlink usually points outside the workspace, where reads refuse to go.
598 const stat = await NodeFSP.lstat(path.join(normalizedCwd, relativePath)).catch(
599 () => null,
600 );
601 return stat?.isFile() ? { path: relativePath, byteLength: stat.size } : null;
602 }),
603 ),
604 );
605 return {
606 files: files.filter((file) => file !== null),
607 truncated: paths.length > IGNORED_FILES_LIMIT,
608 };
609 });
610​
611 return WorkspaceEntries.of({ browse, list, listIgnoredFiles, refresh, search, searchContents });
612});
613​
614export const layer = Layer.effect(WorkspaceEntries, make).pipe(
615 Layer.provide(WorkspaceSearchIndex.WorkspaceSearchIndexMap.layer),
616 Layer.provide(VcsProcess.layer),
617);