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

WorkspaceEntries.ts

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