Open History to see the last commit
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, isNetworkPath, isWindowsAbsolutePath } from "@t3tools/shared/path";
29import { normalizeSearchQuery, PATH_QUERY_PREFIX_PATTERN } 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 }
48}
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 }
59}
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 }
78}
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, mode?: "passive") => 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, mode) {
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(mode);
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 // Project workspace roots are trimmed on decode, so a trailing-space folder would add a different path.
280 if (
281 !dirent.name.toLowerCase().startsWith(lowerPrefix) ||
282 (!showHidden && dirent.name.startsWith(".")) ||
283 dirent.name.trimEnd() !== dirent.name
284 ) {
285 continue;
286 }
287 const fullPath = path.join(parentPath, dirent.name);
288 if (dirent.isDirectory()) {
289 entries.push({ name: dirent.name, fullPath });
290 } else if (dirent.isSymbolicLink()) {
291 symlinkCandidates.push({ name: dirent.name, fullPath });
292 }
293 }
294 if (symlinkCandidates.length > 0) {
295 const resolvedSymlinks = yield* Effect.forEach(
296 symlinkCandidates,
297 (candidate) =>
298 Effect.promise(() => statSymlinkTarget(candidate)).pipe(
299 Effect.timeoutOption(SYMLINK_TARGET_STAT_TIMEOUT),
300 Effect.map(Option.getOrNull),
301 ),
302 { concurrency: MAX_PENDING_SYMLINK_TARGET_STATS },
303 );
304 for (const candidate of resolvedSymlinks) {
305 if (candidate !== null) entries.push(candidate);
306 }
307 }
308
309 return {
310 parentPath,
311 entries: entries.toSorted((left, right) =>
312 left.name.localeCompare(right.name, undefined, { numeric: true }),
313 ),
314 };
315 },
316 );
317
318 const search: WorkspaceEntries["Service"]["search"] = Effect.fn("WorkspaceEntries.search")(
319 function* (input) {
320 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
321 const normalizedQuery = normalizeSearchQuery(input.query, {
322 trimLeadingPattern: PATH_QUERY_PREFIX_PATTERN,
323 });
324 const indexKey = WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, "paths");
325 markSearched(indexKey, yield* Clock.currentTimeMillis);
326 const result = yield* Effect.gen(function* () {
327 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
328 return yield* searchIndex.search(normalizedQuery, input.limit, input.kind, input.imageOnly);
329 }).pipe(Effect.provide(workspaceSearchIndexes.get(indexKey)));
330 if (input.kind === "directory" || input.imageOnly) return result;
331 const worktreeFiles = yield* findNestedWorktreeFiles(
332 normalizedCwd,
333 input.query,
334 result.entries,
335 );
336 if (worktreeFiles.length === 0) return result;
337 const entries = [...worktreeFiles, ...result.entries];
338 return {
339 entries: entries.slice(0, input.limit),
340 truncated: result.truncated || entries.length > input.limit,
341 };
342 },
343 );
344
345 // The index skips gitignored folders, where agents often put worktrees (`.worktrees/x`).
346 // A path relative to such a worktree is found only when it names an existing file exactly.
347 const findNestedWorktreeFiles = Effect.fn("WorkspaceEntries.findNestedWorktreeFiles")(function* (
348 cwd: string,
349 query: string,
350 indexed: ReadonlyArray<ProjectEntry>,
351 ) {
352 // Like the index query, `./src/a.ts` names `src/a.ts`.
353 const relativePath = query
354 .trim()
355 .replaceAll("\\", "/")
356 .replace(/^(?:\.\/)+/, "");
357 if (
358 !relativePath.includes("/") ||
359 relativePath.endsWith("/") ||
360 path.isAbsolute(relativePath) ||
361 isWindowsAbsolutePath(relativePath) ||
362 relativePath.split("/").some((segment) => segment === "..") ||
363 indexed.some(
364 (entry) =>
365 entry.kind === "file" &&
366 (entry.path === relativePath || entry.path.endsWith(`/${relativePath}`)),
367 )
368 ) {
369 return [];
370 }
371 const listWorktrees = (args: ReadonlyArray<string>) =>
372 vcsProcess
373 .run({
374 operation: "WorkspaceEntries.listWorktrees",
375 command: "git",
376 args: ["worktree", "list", "--porcelain", ...args],
377 cwd,
378 allowNonZeroExit: true,
379 timeoutMs: 5_000,
380 })
381 .pipe(
382 Effect.map((result) => (result.exitCode === 0 ? result.stdout : undefined)),
383 Effect.orElseSucceed(() => undefined),
384 );
385 // Only NUL framing keeps a newline in a worktree path. Pre-2.36 Git rejects `-z`.
386 const listed =
387 (yield* listWorktrees(["-z"])) ?? (yield* listWorktrees([]))?.replaceAll("\n", "\0");
388 if (listed === undefined) return [];
389 const realCwd = yield* Effect.promise(() => NodeFSP.realpath(cwd).catch(() => cwd));
390 const worktreeRoots = listed.split("\0\0").flatMap((record) => {
391 const fields = record.split("\0");
392 const worktree = fields.find((field) => field.startsWith("worktree "));
393 // A `prunable` record's directory is gone; another checkout may now sit there.
394 if (worktree === undefined || fields.some((field) => field.startsWith("prunable"))) return [];
395 const root = worktree.slice("worktree ".length);
396 const relativeRoot = path.relative(realCwd, root);
397 return relativeRoot === "" ||
398 relativeRoot === ".." ||
399 relativeRoot.startsWith(`..${path.sep}`) ||
400 path.isAbsolute(relativeRoot)
401 ? []
402 : [relativeRoot.split(path.sep).join("/")];
403 });
404 const matches = yield* Effect.promise(() =>
405 Promise.all(
406 worktreeRoots.map(async (relativeRoot) => {
407 const candidate = `${relativeRoot}/${relativePath}`;
408 const stat = await NodeFSP.stat(path.join(realCwd, candidate)).catch(() => null);
409 return stat?.isFile() ? candidate : null;
410 }),
411 ),
412 );
413 return matches
414 .filter((candidate) => candidate !== null)
415 .map((candidate): ProjectEntry => ({ path: candidate, kind: "file" }));
416 });
417
418 const searchContents: WorkspaceEntries["Service"]["searchContents"] = Effect.fn(
419 "WorkspaceEntries.searchContents",
420 )(function* (input) {
421 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
422 const indexKey = WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, "content");
423 markSearched(indexKey, yield* Clock.currentTimeMillis);
424 return yield* Effect.gen(function* () {
425 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
426 return yield* searchIndex.searchContents(input);
427 }).pipe(Effect.provide(workspaceSearchIndexes.get(indexKey)));
428 });
429
430 const list: WorkspaceEntries["Service"]["list"] = Effect.fn("WorkspaceEntries.list")(
431 function* (input) {
432 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
433 if (input.directoryPath !== undefined) {
434 const directoryPath = input.directoryPath;
435 const toError = (cause: unknown) =>
436 new WorkspaceEntriesReadDirectoryError({
437 cwd: normalizedCwd,
438 partialPath: directoryPath,
439 parentPath: path.resolve(normalizedCwd, directoryPath),
440 cause,
441 });
442 const target =
443 directoryPath === ""
444 ? { absolutePath: normalizedCwd, relativePath: "" }
445 : yield* workspacePaths
446 .resolveRelativePathWithinRoot({
447 workspaceRoot: normalizedCwd,
448 relativePath: directoryPath,
449 })
450 .pipe(Effect.mapError(toError));
451 const { entries, throughSymlink, nestedGitRoots } = yield* Effect.tryPromise({
452 try: async () => {
453 const root = await NodeFSP.realpath(normalizedCwd);
454 const isSameOrInside = (parent: string, child: string) => {
455 const relativeChild = path.relative(parent, child);
456 return (
457 relativeChild !== ".." &&
458 !relativeChild.startsWith(`..${path.sep}`) &&
459 !path.isAbsolute(relativeChild)
460 );
461 };
462 // `filesystem:read` covers the whole OS account, so links may lead out of the
463 // root, but not onto a share: Windows signs in to it with the user's credentials.
464 const isListable = (resolved: string) =>
465 isSameOrInside(root, resolved)
466 ? !path.relative(root, resolved).split(path.sep).includes(".git")
467 : !isNetworkPath(resolved) && !resolved.split(path.sep).includes(".git");
468 const directory = await NodeFSP.realpath(target.absolutePath);
469 const relative = path.relative(root, directory);
470 if (!isListable(directory) || target.relativePath.split("/").includes(".git")) {
471 throw new Error("Directory must not be a network share or inside .git.");
472 }
473 const children = await NodeFSP.readdir(directory, { withFileTypes: true });
474 // Reject canonical ancestors so "Expand all folders" cannot follow a cycle.
475 let visitedFolders: Promise<ReadonlyArray<string>> | undefined;
476 const loadVisitedFolders = () =>
477 (visitedFolders ??= (async () => {
478 const folders = [root];
479 let current = normalizedCwd;
480 for (const segment of target.relativePath.split("/").filter(Boolean)) {
481 current = path.join(current, segment);
482 folders.push(await NodeFSP.realpath(current));
483 }
484 return folders;
485 })());
486 const resolveSymlinkKind = async (
487 name: string,
488 ): Promise<ProjectEntry["kind"] | undefined> => {
489 const resolved = await NodeFSP.realpath(path.join(directory, name)).catch(
490 () => undefined,
491 );
492 if (resolved === undefined || !isListable(resolved)) return undefined;
493 const stat = await NodeFSP.stat(resolved).catch(() => undefined);
494 if (stat?.isFile()) return "file";
495 if (!stat?.isDirectory()) return undefined;
496 const folders = await loadVisitedFolders();
497 return folders.some((folder) => isSameOrInside(resolved, folder))
498 ? undefined
499 : "directory";
500 };
501 // Bound filesystem work for directories such as pnpm node_modules.
502 const kinds: Array<ProjectEntry["kind"] | undefined> = [];
503 for (let offset = 0; offset < children.length; offset += SYMLINK_RESOLVE_BATCH_SIZE) {
504 kinds.push(
505 ...(await Promise.all(
506 children
507 .slice(offset, offset + SYMLINK_RESOLVE_BATCH_SIZE)
508 .map(async (child): Promise<ProjectEntry["kind"] | undefined> => {
509 if (child.name === ".git") return undefined;
510 if (child.isDirectory()) return "directory";
511 if (child.isFile()) return "file";
512 return child.isSymbolicLink() ? resolveSymlinkKind(child.name) : undefined;
513 }),
514 )),
515 );
516 }
517 const nestedGitRoots: Array<string> = [];
518 const segments = target.relativePath.split("/").filter(Boolean);
519 for (let index = 1; index <= segments.length; index += 1) {
520 const candidate = segments.slice(0, index).join("/");
521 const dotGit = await NodeFSP.lstat(path.join(normalizedCwd, candidate, ".git")).catch(
522 () => null,
523 );
524 if (dotGit) nestedGitRoots.push(candidate);
525 }
526 return {
527 nestedGitRoots,
528 entries: children.flatMap((child, index): ProjectEntry[] => {
529 const kind = kinds[index];
530 if (kind === undefined) return [];
531 return [
532 {
533 path: target.relativePath ? `${target.relativePath}/${child.name}` : child.name,
534 kind,
535 },
536 ];
537 }),
538 // Git refuses to classify paths beyond a symbolic link.
539 throughSymlink: relative !== target.relativePath.split("/").join(path.sep),
540 };
541 },
542 catch: toError,
543 });
544 let gitRoot = "";
545 let gitPrefix = "";
546 // stdin avoids argument limits; ignore classification is optional without git/repositories.
547 // ./ avoids leading : pathspec magic; check-ignore rejects --literal-pathspecs.
548 const checkIgnore = (paths: ReadonlyArray<string>) =>
549 vcsProcess
550 .run({
551 operation: "WorkspaceEntries.list",
552 command: "git",
553 args: ["-c", "core.fsmonitor=false", "check-ignore", "-z", "--stdin"],
554 cwd: path.join(normalizedCwd, gitRoot),
555 stdin: `${paths.map((entryPath) => `./${entryPath.slice(gitPrefix.length)}`).join("\0")}\0`,
556 allowNonZeroExit: true,
557 timeoutMs: 10_000,
558 maxOutputBytes: 16 * 1024 * 1024,
559 })
560 .pipe(Effect.orElseSucceed(() => undefined));
561 // Git refuses paths inside a submodule (128) but still answers for nested clones.
562 for (const nestedGitRoot of nestedGitRoots) {
563 if ((yield* checkIgnore([`${nestedGitRoot}/.git`]))?.exitCode !== 128) continue;
564 gitRoot = nestedGitRoot;
565 gitPrefix = `${gitRoot}/`;
566 }
567 const directoryGitPath = target.relativePath.slice(gitPrefix.length);
568 // Check ignored folders once to avoid child index lookups; exit 0 guarantees no tracked descendants.
569 // Symlinks and glob characters still need per-child checks.
570 if (
571 entries.length > IGNORE_CHECK_CHUNK_SIZE &&
572 directoryGitPath !== "" &&
573 !throughSymlink &&
574 !/[*?[\\]/.test(directoryGitPath) &&
575 (yield* checkIgnore([target.relativePath]))?.exitCode === 0
576 ) {
577 return {
578 entries: entries.map((entry) => ({ ...entry, ignored: true })),
579 truncated: false,
580 };
581 }
582 const ignored = new Set<string>();
583 for (let offset = 0; offset < entries.length; offset += IGNORE_CHECK_CHUNK_SIZE) {
584 const result = yield* checkIgnore(
585 entries.slice(offset, offset + IGNORE_CHECK_CHUNK_SIZE).map((entry) => entry.path),
586 );
587 if (!result || (result.exitCode !== 0 && result.exitCode !== 1)) break;
588 for (const ignoredPath of result.stdout.split("\0")) {
589 ignored.add(gitPrefix + ignoredPath.replace(/^\.\//, ""));
590 }
591 }
592 return {
593 entries: entries.map((entry) =>
594 ignored.has(entry.path) ? { ...entry, ignored: true } : entry,
595 ),
596 truncated: false,
597 };
598 }
599 const indexKey = WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, "paths");
600 markSearched(indexKey, yield* Clock.currentTimeMillis);
601 return yield* Effect.gen(function* () {
602 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
603 return yield* searchIndex.list();
604 }).pipe(Effect.provide(workspaceSearchIndexes.get(indexKey)));
605 },
606 );
607
608 const listIgnoredFiles: WorkspaceEntries["Service"]["listIgnoredFiles"] = Effect.fn(
609 "WorkspaceEntries.listIgnoredFiles",
610 )(function* (input) {
611 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
612 // `--directory` reports a folder holding nothing but ignored files as one
613 // `name/` entry, which is how `node_modules` and build output drop out.
614 const result = yield* vcsProcess
615 .run({
616 operation: "WorkspaceEntries.listIgnoredFiles",
617 command: "git",
618 args: [
619 "-c",
620 "core.fsmonitor=false",
621 "ls-files",
622 "--others",
623 "--ignored",
624 "--exclude-standard",
625 "--directory",
626 "--no-empty-directory",
627 "-z",
628 ],
629 cwd: normalizedCwd,
630 allowNonZeroExit: true,
631 timeoutMs: 10_000,
632 maxOutputBytes: 4 * 1024 * 1024,
633 })
634 .pipe(Effect.orElseSucceed(() => undefined));
635 if (!result || result.exitCode !== 0) return { files: [], truncated: false };
636 // Filter before the cap so files sorting past it stay reachable by search.
637 const query = input.query?.toLowerCase() ?? "";
638 const paths = result.stdout
639 .split("\0")
640 .filter(
641 (entry) => entry.length > 0 && !entry.endsWith("/") && entry.toLowerCase().includes(query),
642 )
643 .toSorted();
644 const files = yield* Effect.promise(() =>
645 Promise.all(
646 paths.slice(0, IGNORED_FILES_LIMIT).map(async (relativePath) => {
647 // lstat: following a link could stall on a slow or remote target.
648 const stat = await NodeFSP.lstat(path.join(normalizedCwd, relativePath)).catch(
649 () => null,
650 );
651 return stat?.isFile() ? { path: relativePath, byteLength: stat.size } : null;
652 }),
653 ),
654 );
655 return {
656 files: files.filter((file) => file !== null),
657 truncated: paths.length > IGNORED_FILES_LIMIT,
658 };
659 });
660
661 return WorkspaceEntries.of({ browse, list, listIgnoredFiles, refresh, search, searchContents });
662});
663
664export const layer = Layer.effect(WorkspaceEntries, make).pipe(
665 Layer.provide(WorkspaceSearchIndex.WorkspaceSearchIndexMap.layer),
666 Layer.provide(VcsProcess.layer),
667);