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

WorkspaceEntries.ts

532 lines20.9 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 return 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 },
274 );
275​
276 const searchContents: WorkspaceEntries["Service"]["searchContents"] = Effect.fn(
277 "WorkspaceEntries.searchContents",
278 )(function* (input) {
279 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
280 return yield* Effect.gen(function* () {
281 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
282 return yield* searchIndex.searchContents(input);
283 }).pipe(
284 Effect.provide(
285 workspaceSearchIndexes.get(
286 WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, "content"),
287 ),
288 ),
289 );
290 });
291​
292 const list: WorkspaceEntries["Service"]["list"] = Effect.fn("WorkspaceEntries.list")(
293 function* (input) {
294 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
295 if (input.directoryPath !== undefined) {
296 const directoryPath = input.directoryPath;
297 const toError = (cause: unknown) =>
298 new WorkspaceEntriesReadDirectoryError({
299 cwd: normalizedCwd,
300 partialPath: directoryPath,
301 parentPath: path.resolve(normalizedCwd, directoryPath),
302 cause,
303 });
304 const target =
305 directoryPath === ""
306 ? { absolutePath: normalizedCwd, relativePath: "" }
307 : yield* workspacePaths
308 .resolveRelativePathWithinRoot({
309 workspaceRoot: normalizedCwd,
310 relativePath: directoryPath,
311 })
312 .pipe(Effect.mapError(toError));
313 const { entries, throughSymlink, nestedGitRoots } = yield* Effect.tryPromise({
314 try: async () => {
315 const root = await NodeFSP.realpath(normalizedCwd);
316 const directory = await NodeFSP.realpath(target.absolutePath);
317 const relative = path.relative(root, directory);
318 if (
319 relative === ".." ||
320 relative.startsWith(`..${path.sep}`) ||
321 path.isAbsolute(relative) ||
322 relative.split(path.sep).includes(".git") ||
323 target.relativePath.split("/").includes(".git")
324 ) {
325 throw new Error("Directory must be inside the workspace and outside .git.");
326 }
327 const children = await NodeFSP.readdir(directory, { withFileTypes: true });
328 const isSameOrInside = (parent: string, child: string) => {
329 const relativeChild = path.relative(parent, child);
330 return (
331 relativeChild !== ".." &&
332 !relativeChild.startsWith(`..${path.sep}`) &&
333 !path.isAbsolute(relativeChild)
334 );
335 };
336 // Reject canonical ancestors so "Expand all folders" cannot follow a cycle.
337 let visitedFolders: Promise<ReadonlyArray<string>> | undefined;
338 const loadVisitedFolders = () =>
339 (visitedFolders ??= (async () => {
340 const folders = [root];
341 let current = normalizedCwd;
342 for (const segment of target.relativePath.split("/").filter(Boolean)) {
343 current = path.join(current, segment);
344 folders.push(await NodeFSP.realpath(current));
345 }
346 return folders;
347 })());
348 const resolveSymlinkKind = async (
349 name: string,
350 ): Promise<ProjectEntry["kind"] | undefined> => {
351 const resolved = await NodeFSP.realpath(path.join(directory, name)).catch(
352 () => undefined,
353 );
354 if (
355 resolved === undefined ||
356 !isSameOrInside(root, resolved) ||
357 path.relative(root, resolved).split(path.sep).includes(".git")
358 ) {
359 return undefined;
360 }
361 const stat = await NodeFSP.stat(resolved).catch(() => undefined);
362 if (stat?.isFile()) return "file";
363 if (!stat?.isDirectory()) return undefined;
364 const folders = await loadVisitedFolders();
365 return folders.some((folder) => isSameOrInside(resolved, folder))
366 ? undefined
367 : "directory";
368 };
369 // Bound filesystem work for directories such as pnpm node_modules.
370 const kinds: Array<ProjectEntry["kind"] | undefined> = [];
371 for (let offset = 0; offset < children.length; offset += SYMLINK_RESOLVE_BATCH_SIZE) {
372 kinds.push(
373 ...(await Promise.all(
374 children
375 .slice(offset, offset + SYMLINK_RESOLVE_BATCH_SIZE)
376 .map(async (child): Promise<ProjectEntry["kind"] | undefined> => {
377 if (child.name === ".git") return undefined;
378 if (child.isDirectory()) return "directory";
379 if (child.isFile()) return "file";
380 return child.isSymbolicLink() ? resolveSymlinkKind(child.name) : undefined;
381 }),
382 )),
383 );
384 }
385 const nestedGitRoots: Array<string> = [];
386 const segments = target.relativePath.split("/").filter(Boolean);
387 for (let index = 1; index <= segments.length; index += 1) {
388 const candidate = segments.slice(0, index).join("/");
389 const dotGit = await NodeFSP.lstat(path.join(normalizedCwd, candidate, ".git")).catch(
390 () => null,
391 );
392 if (dotGit) nestedGitRoots.push(candidate);
393 }
394 return {
395 nestedGitRoots,
396 entries: children.flatMap((child, index): ProjectEntry[] => {
397 const kind = kinds[index];
398 if (kind === undefined) return [];
399 return [
400 {
401 path: target.relativePath ? `${target.relativePath}/${child.name}` : child.name,
402 kind,
403 },
404 ];
405 }),
406 // Git refuses to classify paths beyond a symbolic link.
407 throughSymlink: relative !== target.relativePath.split("/").join(path.sep),
408 };
409 },
410 catch: toError,
411 });
412 let gitRoot = "";
413 let gitPrefix = "";
414 // stdin avoids argument limits; ignore classification is optional without git/repositories.
415 const checkIgnore = (paths: ReadonlyArray<string>) =>
416 vcsProcess
417 .run({
418 operation: "WorkspaceEntries.list",
419 command: "git",
420 args: ["-c", "core.fsmonitor=false", "check-ignore", "-z", "--stdin"],
421 cwd: path.join(normalizedCwd, gitRoot),
422 stdin: `${paths.map((entryPath) => entryPath.slice(gitPrefix.length)).join("\0")}\0`,
423 allowNonZeroExit: true,
424 timeoutMs: 10_000,
425 maxOutputBytes: 16 * 1024 * 1024,
426 })
427 .pipe(Effect.orElseSucceed(() => undefined));
428 // Git refuses paths inside a submodule (128) but still answers for nested clones.
429 for (const nestedGitRoot of nestedGitRoots) {
430 if ((yield* checkIgnore([`${nestedGitRoot}/.git`]))?.exitCode !== 128) continue;
431 gitRoot = nestedGitRoot;
432 gitPrefix = `${gitRoot}/`;
433 }
434 const directoryGitPath = target.relativePath.slice(gitPrefix.length);
435 // Check ignored folders once to avoid child index lookups; exit 0 guarantees no tracked descendants.
436 // Symlinks and pathspec magic still need per-child checks.
437 if (
438 entries.length > IGNORE_CHECK_CHUNK_SIZE &&
439 directoryGitPath !== "" &&
440 !throughSymlink &&
441 !/^:|[*?[\\]/.test(directoryGitPath) &&
442 (yield* checkIgnore([target.relativePath]))?.exitCode === 0
443 ) {
444 return {
445 entries: entries.map((entry) => ({ ...entry, ignored: true })),
446 truncated: false,
447 };
448 }
449 const ignored = new Set<string>();
450 for (let offset = 0; offset < entries.length; offset += IGNORE_CHECK_CHUNK_SIZE) {
451 const result = yield* checkIgnore(
452 entries.slice(offset, offset + IGNORE_CHECK_CHUNK_SIZE).map((entry) => entry.path),
453 );
454 if (!result || (result.exitCode !== 0 && result.exitCode !== 1)) break;
455 for (const ignoredPath of result.stdout.split("\0")) ignored.add(gitPrefix + ignoredPath);
456 }
457 return {
458 entries: entries.map((entry) =>
459 ignored.has(entry.path) ? { ...entry, ignored: true } : entry,
460 ),
461 truncated: false,
462 };
463 }
464 return yield* Effect.gen(function* () {
465 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
466 return yield* searchIndex.list();
467 }).pipe(
468 Effect.provide(
469 workspaceSearchIndexes.get(
470 WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, "paths"),
471 ),
472 ),
473 );
474 },
475 );
476​
477 const listIgnoredFiles: WorkspaceEntries["Service"]["listIgnoredFiles"] = Effect.fn(
478 "WorkspaceEntries.listIgnoredFiles",
479 )(function* (input) {
480 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
481 // `--directory` reports a folder holding nothing but ignored files as one
482 // `name/` entry, which is how `node_modules` and build output drop out.
483 const result = yield* vcsProcess
484 .run({
485 operation: "WorkspaceEntries.listIgnoredFiles",
486 command: "git",
487 args: [
488 "-c",
489 "core.fsmonitor=false",
490 "ls-files",
491 "--others",
492 "--ignored",
493 "--exclude-standard",
494 "--directory",
495 "--no-empty-directory",
496 "-z",
497 ],
498 cwd: normalizedCwd,
499 allowNonZeroExit: true,
500 timeoutMs: 10_000,
501 maxOutputBytes: 4 * 1024 * 1024,
502 })
503 .pipe(Effect.orElseSucceed(() => undefined));
504 if (!result || result.exitCode !== 0) return { files: [], truncated: false };
505 const paths = result.stdout
506 .split("\0")
507 .filter((entry) => entry.length > 0 && !entry.endsWith("/"))
508 .toSorted();
509 const files = yield* Effect.promise(() =>
510 Promise.all(
511 paths.slice(0, IGNORED_FILES_LIMIT).map(async (relativePath) => {
512 // lstat: a symlink usually points outside the workspace, where reads refuse to go.
513 const stat = await NodeFSP.lstat(path.join(normalizedCwd, relativePath)).catch(
514 () => null,
515 );
516 return stat?.isFile() ? { path: relativePath, byteLength: stat.size } : null;
517 }),
518 ),
519 );
520 return {
521 files: files.filter((file) => file !== null),
522 truncated: paths.length > IGNORED_FILES_LIMIT,
523 };
524 });
525​
526 return WorkspaceEntries.of({ browse, list, listIgnoredFiles, refresh, search, searchContents });
527});
528​
529export const layer = Layer.effect(WorkspaceEntries, make).pipe(
530 Layer.provide(WorkspaceSearchIndex.WorkspaceSearchIndexMap.layer),
531 Layer.provide(VcsProcess.layer),
532);