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

WorkspaceEntries.ts

528 lines20.8 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 override get message(): string {
68 const cwd = this.cwd ? ` from '${this.cwd}'` : "";
69 return `Failed to read workspace directory '${this.parentPath}' while browsing '${this.partialPath}'${cwd}.`;
70 }
72​
73export const WorkspaceEntriesBrowseError = Schema.Union([
74 WorkspaceEntriesWindowsPathUnsupportedError,
75 WorkspaceEntriesCurrentProjectRequiredError,
76 WorkspaceEntriesReadDirectoryError,
77]);
78export type WorkspaceEntriesBrowseError = typeof WorkspaceEntriesBrowseError.Type;
79​
80export const WorkspaceEntriesError = Schema.Union([
81 WorkspaceEntriesReadDirectoryError,
82 WorkspacePaths.WorkspaceRootNotExistsError,
83 WorkspacePaths.WorkspaceRootCreateFailedError,
84 WorkspacePaths.WorkspaceRootStatFailedError,
85 WorkspacePaths.WorkspaceRootNotDirectoryError,
86 WorkspaceSearchIndex.WorkspaceSearchIndexCreateFailed,
87 WorkspaceSearchIndex.WorkspaceSearchIndexScanTimedOut,
88 WorkspaceSearchIndex.WorkspaceSearchIndexSearchFailed,
89]);
90export type WorkspaceEntriesError = typeof WorkspaceEntriesError.Type;
91​
92export class WorkspaceEntries extends Context.Service<
93 WorkspaceEntries,
94 {
95 readonly browse: (
96 input: FilesystemBrowseInput,
97 ) => Effect.Effect<FilesystemBrowseResult, WorkspaceEntriesBrowseError>;
98 readonly list: (
99 input: ProjectListEntriesInput,
100 ) => Effect.Effect<ProjectListEntriesResult, WorkspaceEntriesError>;
101 readonly search: (
102 input: ProjectSearchEntriesInput,
103 ) => Effect.Effect<ProjectSearchEntriesResult, WorkspaceEntriesError>;
104 readonly listIgnoredFiles: (
105 input: ProjectListIgnoredFilesInput,
106 ) => Effect.Effect<ProjectListIgnoredFilesResult, WorkspaceEntriesError>;
107 readonly searchContents: (
108 input: ProjectSearchContentsInput,
109 ) => Effect.Effect<ProjectSearchContentsResult, WorkspaceEntriesError>;
110 readonly refresh: (cwd: string) => Effect.Effect<void>;
111 }
112>()("t3/workspace/WorkspaceEntries") {}
113​
114/** Ignored files offered for copying; more than this is a build folder, not config. */
115const IGNORED_FILES_LIMIT = 200;
116​
117/** Paths sent to one `git check-ignore` call when labelling a folder's children. */
118const IGNORE_CHECK_CHUNK_SIZE = 1000;
119​
120/** Children classified at once when listing a folder; each symlink costs a realpath and a stat. */
121const SYMLINK_RESOLVE_BATCH_SIZE = 64;
122​
123const resolveBrowseTarget = Effect.fn("WorkspaceEntries.resolveBrowseTarget")(function* (
124 input: FilesystemBrowseInput,
125 path: Path.Path,
126): Effect.fn.Return<string, WorkspaceEntriesBrowseError> {
127 const platform = yield* HostProcess.Platform;
128 if (platform !== "win32" && isWindowsAbsolutePath(input.partialPath)) {
129 return yield* new WorkspaceEntriesWindowsPathUnsupportedError({
130 cwd: input.cwd,
131 partialPath: input.partialPath,
132 platform,
133 });
134 }
135​
136 if (!isExplicitRelativePath(input.partialPath)) {
137 return path.resolve(expandHomePath(input.partialPath, yield* HostProcess.HomeDirectory));
138 }
139​
140 if (!input.cwd) {
141 return yield* new WorkspaceEntriesCurrentProjectRequiredError({
142 partialPath: input.partialPath,
143 });
144 }
145 return path.resolve(
146 expandHomePath(input.cwd, yield* HostProcess.HomeDirectory),
147 input.partialPath,
148 );
149});
150​
151/** @public */
152export const make = Effect.gen(function* () {
153 const path = yield* Path.Path;
154 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
155 const workspaceSearchIndexes = yield* WorkspaceSearchIndex.WorkspaceSearchIndexMap;
156 const vcsProcess = yield* VcsProcess.VcsProcess;
157​
158 const normalizeWorkspaceRoot = Effect.fn("WorkspaceEntries.normalizeWorkspaceRoot")(function* (
159 cwd: string,
160 ): Effect.fn.Return<string, WorkspaceEntriesError> {
161 return yield* workspacePaths.normalizeWorkspaceRoot(cwd);
162 });
163​
164 const refresh: WorkspaceEntries["Service"]["refresh"] = Effect.fn("WorkspaceEntries.refresh")(
165 function* (cwd) {
166 const normalizedCwd = yield* normalizeWorkspaceRoot(cwd).pipe(
167 Effect.orElseSucceed(() => cwd),
168 );
169 for (const variant of WorkspaceSearchIndex.WORKSPACE_SEARCH_INDEX_VARIANTS) {
170 const indexKey = WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, variant);
171 if (!(yield* RcMap.has(workspaceSearchIndexes.rcMap, indexKey))) {
172 continue;
173 }
174 const recoverRefreshFailure = Effect.fn("WorkspaceEntries.recoverRefreshFailure")(
175 function* (
176 cause:
177 | WorkspaceSearchIndex.WorkspaceSearchIndexCreateFailed
178 | WorkspaceSearchIndex.WorkspaceSearchIndexScanTimedOut
179 | WorkspaceSearchIndex.WorkspaceSearchIndexRefreshFailed,
180 ) {
181 yield* Effect.logWarning("Failed to refresh workspace search index", {
182 cwd,
183 variant,
184 cause,
185 });
186 yield* workspaceSearchIndexes.invalidate(indexKey);
187 },
188 );
189 yield* Effect.gen(function* () {
190 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
191 yield* searchIndex.refresh();
192 }).pipe(
193 Effect.provide(workspaceSearchIndexes.get(indexKey)),
194 Effect.catchTags({
195 WorkspaceSearchIndexCreateFailed: recoverRefreshFailure,
196 WorkspaceSearchIndexScanTimedOut: recoverRefreshFailure,
197 WorkspaceSearchIndexRefreshFailed: recoverRefreshFailure,
198 }),
199 );
200 }
201 },
202 );
203​
204 const browse: WorkspaceEntries["Service"]["browse"] = Effect.fn("WorkspaceEntries.browse")(
205 function* (input) {
206 const resolvedInputPath = yield* resolveBrowseTarget(input, path);
207 const endsWithSeparator = /[\\/]$/.test(input.partialPath) || input.partialPath === "~";
208 const parentPath = endsWithSeparator ? resolvedInputPath : path.dirname(resolvedInputPath);
209 const prefix = endsWithSeparator ? "" : path.basename(resolvedInputPath);
210​
211 const dirents = yield* Effect.tryPromise({
212 try: () => NodeFSP.readdir(parentPath, { withFileTypes: true }),
213 catch: (cause) =>
214 new WorkspaceEntriesReadDirectoryError({
215 cwd: input.cwd,
216 partialPath: input.partialPath,
217 parentPath,
218 cause,
219 }),
220 }).pipe(
221 Effect.catchIf(
222 (error) => {
223 const code = (error.cause as NodeJS.ErrnoException | undefined)?.code;
224 return code === "EACCES" || code === "EPERM";
225 },
226 () => Effect.succeed([]),
227 ),
228 );
229​
230 const showHidden = endsWithSeparator || prefix.startsWith(".");
231 const lowerPrefix = prefix.toLowerCase();
232 const entries: Array<{ readonly name: string; readonly fullPath: string }> = [];
233 for (const dirent of dirents) {
234 if (
235 dirent.isDirectory() &&
236 dirent.name.toLowerCase().startsWith(lowerPrefix) &&
237 (showHidden || !dirent.name.startsWith("."))
238 ) {
239 entries.push({
240 name: dirent.name,
241 fullPath: path.join(parentPath, dirent.name),
242 });
243 }
244 }
245​
246 return {
247 parentPath,
248 entries: entries.toSorted((left, right) => left.name.localeCompare(right.name)),
249 };
250 },
251 );
252​
253 const search: WorkspaceEntries["Service"]["search"] = Effect.fn("WorkspaceEntries.search")(
254 function* (input) {
255 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
256 const normalizedQuery = normalizeSearchQuery(input.query, {
257 trimLeadingPattern: /^[@./]+/,
258 });
259 return yield* Effect.gen(function* () {
260 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
261 return yield* searchIndex.search(normalizedQuery, input.limit, input.kind, input.imageOnly);
262 }).pipe(
263 Effect.provide(
264 workspaceSearchIndexes.get(
265 WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, "paths"),
266 ),
267 ),
268 );
269 },
270 );
271​
272 const searchContents: WorkspaceEntries["Service"]["searchContents"] = Effect.fn(
273 "WorkspaceEntries.searchContents",
274 )(function* (input) {
275 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
276 return yield* Effect.gen(function* () {
277 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
278 return yield* searchIndex.searchContents(input);
279 }).pipe(
280 Effect.provide(
281 workspaceSearchIndexes.get(
282 WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, "content"),
283 ),
284 ),
285 );
286 });
287​
288 const list: WorkspaceEntries["Service"]["list"] = Effect.fn("WorkspaceEntries.list")(
289 function* (input) {
290 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
291 if (input.directoryPath !== undefined) {
292 const directoryPath = input.directoryPath;
293 const toError = (cause: unknown) =>
294 new WorkspaceEntriesReadDirectoryError({
295 cwd: normalizedCwd,
296 partialPath: directoryPath,
297 parentPath: path.resolve(normalizedCwd, directoryPath),
298 cause,
299 });
300 const target =
301 directoryPath === ""
302 ? { absolutePath: normalizedCwd, relativePath: "" }
303 : yield* workspacePaths
304 .resolveRelativePathWithinRoot({
305 workspaceRoot: normalizedCwd,
306 relativePath: directoryPath,
307 })
308 .pipe(Effect.mapError(toError));
309 const { entries, throughSymlink, nestedGitRoots } = yield* Effect.tryPromise({
310 try: async () => {
311 const root = await NodeFSP.realpath(normalizedCwd);
312 const directory = await NodeFSP.realpath(target.absolutePath);
313 const relative = path.relative(root, directory);
314 if (
315 relative === ".." ||
316 relative.startsWith(`..${path.sep}`) ||
317 path.isAbsolute(relative) ||
318 relative.split(path.sep).includes(".git") ||
319 target.relativePath.split("/").includes(".git")
320 ) {
321 throw new Error("Directory must be inside the workspace and outside .git.");
322 }
323 const children = await NodeFSP.readdir(directory, { withFileTypes: true });
324 const isSameOrInside = (parent: string, child: string) => {
325 const relativeChild = path.relative(parent, child);
326 return (
327 relativeChild !== ".." &&
328 !relativeChild.startsWith(`..${path.sep}`) &&
329 !path.isAbsolute(relativeChild)
330 );
331 };
332 // Reject canonical ancestors so "Expand all folders" cannot follow a cycle.
333 let visitedFolders: Promise<ReadonlyArray<string>> | undefined;
334 const loadVisitedFolders = () =>
335 (visitedFolders ??= (async () => {
336 const folders = [root];
337 let current = normalizedCwd;
338 for (const segment of target.relativePath.split("/").filter(Boolean)) {
339 current = path.join(current, segment);
340 folders.push(await NodeFSP.realpath(current));
341 }
342 return folders;
343 })());
344 const resolveSymlinkKind = async (
345 name: string,
346 ): Promise<ProjectEntry["kind"] | undefined> => {
347 const resolved = await NodeFSP.realpath(path.join(directory, name)).catch(
348 () => undefined,
349 );
350 if (
351 resolved === undefined ||
352 !isSameOrInside(root, resolved) ||
353 path.relative(root, resolved).split(path.sep).includes(".git")
354 ) {
355 return undefined;
356 }
357 const stat = await NodeFSP.stat(resolved).catch(() => undefined);
358 if (stat?.isFile()) return "file";
359 if (!stat?.isDirectory()) return undefined;
360 const folders = await loadVisitedFolders();
361 return folders.some((folder) => isSameOrInside(resolved, folder))
362 ? undefined
363 : "directory";
364 };
365 // Bound filesystem work for directories such as pnpm node_modules.
366 const kinds: Array<ProjectEntry["kind"] | undefined> = [];
367 for (let offset = 0; offset < children.length; offset += SYMLINK_RESOLVE_BATCH_SIZE) {
368 kinds.push(
369 ...(await Promise.all(
370 children
371 .slice(offset, offset + SYMLINK_RESOLVE_BATCH_SIZE)
372 .map(async (child): Promise<ProjectEntry["kind"] | undefined> => {
373 if (child.name === ".git") return undefined;
374 if (child.isDirectory()) return "directory";
375 if (child.isFile()) return "file";
376 return child.isSymbolicLink() ? resolveSymlinkKind(child.name) : undefined;
377 }),
378 )),
379 );
380 }
381 const nestedGitRoots: Array<string> = [];
382 const segments = target.relativePath.split("/").filter(Boolean);
383 for (let index = 1; index <= segments.length; index += 1) {
384 const candidate = segments.slice(0, index).join("/");
385 const dotGit = await NodeFSP.lstat(path.join(normalizedCwd, candidate, ".git")).catch(
386 () => null,
387 );
388 if (dotGit) nestedGitRoots.push(candidate);
389 }
390 return {
391 nestedGitRoots,
392 entries: children.flatMap((child, index): ProjectEntry[] => {
393 const kind = kinds[index];
394 if (kind === undefined) return [];
395 return [
396 {
397 path: target.relativePath ? `${target.relativePath}/${child.name}` : child.name,
398 kind,
399 },
400 ];
401 }),
402 // Git refuses to classify paths beyond a symbolic link.
403 throughSymlink: relative !== target.relativePath.split("/").join(path.sep),
404 };
405 },
406 catch: toError,
407 });
408 let gitRoot = "";
409 let gitPrefix = "";
410 // stdin avoids argument limits; ignore classification is optional without git/repositories.
411 const checkIgnore = (paths: ReadonlyArray<string>) =>
412 vcsProcess
413 .run({
414 operation: "WorkspaceEntries.list",
415 command: "git",
416 args: ["-c", "core.fsmonitor=false", "check-ignore", "-z", "--stdin"],
417 cwd: path.join(normalizedCwd, gitRoot),
418 stdin: `${paths.map((entryPath) => entryPath.slice(gitPrefix.length)).join("\0")}\0`,
419 allowNonZeroExit: true,
420 timeoutMs: 10_000,
421 maxOutputBytes: 16 * 1024 * 1024,
422 })
423 .pipe(Effect.orElseSucceed(() => undefined));
424 // Git refuses paths inside a submodule (128) but still answers for nested clones.
425 for (const nestedGitRoot of nestedGitRoots) {
426 if ((yield* checkIgnore([`${nestedGitRoot}/.git`]))?.exitCode !== 128) continue;
427 gitRoot = nestedGitRoot;
428 gitPrefix = `${gitRoot}/`;
429 }
430 const directoryGitPath = target.relativePath.slice(gitPrefix.length);
431 // Check ignored folders once to avoid child index lookups; exit 0 guarantees no tracked descendants.
432 // Symlinks and pathspec magic still need per-child checks.
433 if (
434 entries.length > IGNORE_CHECK_CHUNK_SIZE &&
435 directoryGitPath !== "" &&
436 !throughSymlink &&
437 !/^:|[*?[\\]/.test(directoryGitPath) &&
438 (yield* checkIgnore([target.relativePath]))?.exitCode === 0
439 ) {
440 return {
441 entries: entries.map((entry) => ({ ...entry, ignored: true })),
442 truncated: false,
443 };
444 }
445 const ignored = new Set<string>();
446 for (let offset = 0; offset < entries.length; offset += IGNORE_CHECK_CHUNK_SIZE) {
447 const result = yield* checkIgnore(
448 entries.slice(offset, offset + IGNORE_CHECK_CHUNK_SIZE).map((entry) => entry.path),
449 );
450 if (!result || (result.exitCode !== 0 && result.exitCode !== 1)) break;
451 for (const ignoredPath of result.stdout.split("\0")) ignored.add(gitPrefix + ignoredPath);
452 }
453 return {
454 entries: entries.map((entry) =>
455 ignored.has(entry.path) ? { ...entry, ignored: true } : entry,
456 ),
457 truncated: false,
458 };
459 }
460 return yield* Effect.gen(function* () {
461 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
462 return yield* searchIndex.list();
463 }).pipe(
464 Effect.provide(
465 workspaceSearchIndexes.get(
466 WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, "paths"),
467 ),
468 ),
469 );
470 },
471 );
472​
473 const listIgnoredFiles: WorkspaceEntries["Service"]["listIgnoredFiles"] = Effect.fn(
474 "WorkspaceEntries.listIgnoredFiles",
475 )(function* (input) {
476 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
477 // `--directory` reports a folder holding nothing but ignored files as one
478 // `name/` entry, which is how `node_modules` and build output drop out.
479 const result = yield* vcsProcess
480 .run({
481 operation: "WorkspaceEntries.listIgnoredFiles",
482 command: "git",
483 args: [
484 "-c",
485 "core.fsmonitor=false",
486 "ls-files",
487 "--others",
488 "--ignored",
489 "--exclude-standard",
490 "--directory",
491 "--no-empty-directory",
492 "-z",
493 ],
494 cwd: normalizedCwd,
495 allowNonZeroExit: true,
496 timeoutMs: 10_000,
497 maxOutputBytes: 4 * 1024 * 1024,
498 })
499 .pipe(Effect.orElseSucceed(() => undefined));
500 if (!result || result.exitCode !== 0) return { files: [], truncated: false };
501 const paths = result.stdout
502 .split("\0")
503 .filter((entry) => entry.length > 0 && !entry.endsWith("/"))
504 .toSorted();
505 const files = yield* Effect.promise(() =>
506 Promise.all(
507 paths.slice(0, IGNORED_FILES_LIMIT).map(async (relativePath) => {
508 // lstat: a symlink usually points outside the workspace, where reads refuse to go.
509 const stat = await NodeFSP.lstat(path.join(normalizedCwd, relativePath)).catch(
510 () => null,
511 );
512 return stat?.isFile() ? { path: relativePath, byteLength: stat.size } : null;
513 }),
514 ),
515 );
516 return {
517 files: files.filter((file) => file !== null),
518 truncated: paths.length > IGNORED_FILES_LIMIT,
519 };
520 });
521​
522 return WorkspaceEntries.of({ browse, list, listIgnoredFiles, refresh, search, searchContents });
523});
524​
525export const layer = Layer.effect(WorkspaceEntries, make).pipe(
526 Layer.provide(WorkspaceSearchIndex.WorkspaceSearchIndexMap.layer),
527 Layer.provide(VcsProcess.layer),
528);