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

WorkspaceEntries.ts

662 lines26.9 KB

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