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

WorkspaceEntries.ts

452 lines17.1 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​
124const resolveBrowseTarget = Effect.fn("WorkspaceEntries.resolveBrowseTarget")(function* (
125 input: FilesystemBrowseInput,
126 path: Path.Path,
127): Effect.fn.Return<string, WorkspaceEntriesBrowseError> {
128 const platform = yield* HostProcess.Platform;
129 if (platform !== "win32" && isWindowsAbsolutePath(input.partialPath)) {
130 return yield* new WorkspaceEntriesWindowsPathUnsupportedError({
131 cwd: input.cwd,
132 partialPath: input.partialPath,
133 platform,
134 });
135 }
136​
137 if (!isExplicitRelativePath(input.partialPath)) {
138 return path.resolve(expandHomePath(input.partialPath, yield* HostProcess.HomeDirectory));
139 }
140​
141 if (!input.cwd) {
142 return yield* new WorkspaceEntriesCurrentProjectRequiredError({
143 partialPath: input.partialPath,
144 });
145 }
146 return path.resolve(
147 expandHomePath(input.cwd, yield* HostProcess.HomeDirectory),
148 input.partialPath,
149 );
150});
151​
152/** @public */
153export const make = Effect.gen(function* () {
154 const path = yield* Path.Path;
155 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
156 const workspaceSearchIndexes = yield* WorkspaceSearchIndex.WorkspaceSearchIndexMap;
157 const vcsProcess = yield* VcsProcess.VcsProcess;
158​
159 const normalizeWorkspaceRoot = Effect.fn("WorkspaceEntries.normalizeWorkspaceRoot")(function* (
160 cwd: string,
161 ): Effect.fn.Return<string, WorkspaceEntriesError> {
162 return yield* workspacePaths.normalizeWorkspaceRoot(cwd);
163 });
164​
165 const refresh: WorkspaceEntries["Service"]["refresh"] = Effect.fn("WorkspaceEntries.refresh")(
166 function* (cwd) {
167 const normalizedCwd = yield* normalizeWorkspaceRoot(cwd).pipe(
168 Effect.orElseSucceed(() => cwd),
169 );
170 for (const variant of WorkspaceSearchIndex.WORKSPACE_SEARCH_INDEX_VARIANTS) {
171 const indexKey = WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, variant);
172 if (!(yield* RcMap.has(workspaceSearchIndexes.rcMap, indexKey))) {
173 continue;
174 }
175 const recoverRefreshFailure = Effect.fn("WorkspaceEntries.recoverRefreshFailure")(
176 function* (
177 cause:
178 | WorkspaceSearchIndex.WorkspaceSearchIndexCreateFailed
179 | WorkspaceSearchIndex.WorkspaceSearchIndexScanTimedOut
180 | WorkspaceSearchIndex.WorkspaceSearchIndexRefreshFailed,
181 ) {
182 yield* Effect.logWarning("Failed to refresh workspace search index", {
183 cwd,
184 variant,
185 cause,
186 });
187 yield* workspaceSearchIndexes.invalidate(indexKey);
188 },
189 );
190 yield* Effect.gen(function* () {
191 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
192 yield* searchIndex.refresh();
193 }).pipe(
194 Effect.provide(workspaceSearchIndexes.get(indexKey)),
195 Effect.catchTags({
196 WorkspaceSearchIndexCreateFailed: recoverRefreshFailure,
197 WorkspaceSearchIndexScanTimedOut: recoverRefreshFailure,
198 WorkspaceSearchIndexRefreshFailed: recoverRefreshFailure,
199 }),
200 );
201 }
202 },
203 );
204​
205 const browse: WorkspaceEntries["Service"]["browse"] = Effect.fn("WorkspaceEntries.browse")(
206 function* (input) {
207 const resolvedInputPath = yield* resolveBrowseTarget(input, path);
208 const endsWithSeparator = /[\\/]$/.test(input.partialPath) || input.partialPath === "~";
209 const parentPath = endsWithSeparator ? resolvedInputPath : path.dirname(resolvedInputPath);
210 const prefix = endsWithSeparator ? "" : path.basename(resolvedInputPath);
211​
212 const dirents = yield* Effect.tryPromise({
213 try: () => NodeFSP.readdir(parentPath, { withFileTypes: true }),
214 catch: (cause) =>
215 new WorkspaceEntriesReadDirectoryError({
216 cwd: input.cwd,
217 partialPath: input.partialPath,
218 parentPath,
219 cause,
220 }),
221 }).pipe(
222 Effect.catchIf(
223 (error) => {
224 const code = (error.cause as NodeJS.ErrnoException | undefined)?.code;
225 return code === "EACCES" || code === "EPERM";
226 },
227 () => Effect.succeed([]),
228 ),
229 );
230​
231 const showHidden = endsWithSeparator || prefix.startsWith(".");
232 const lowerPrefix = prefix.toLowerCase();
233 const entries: Array<{ readonly name: string; readonly fullPath: string }> = [];
234 for (const dirent of dirents) {
235 if (
236 dirent.isDirectory() &&
237 dirent.name.toLowerCase().startsWith(lowerPrefix) &&
238 (showHidden || !dirent.name.startsWith("."))
239 ) {
240 entries.push({
241 name: dirent.name,
242 fullPath: path.join(parentPath, dirent.name),
243 });
244 }
245 }
246​
247 return {
248 parentPath,
249 entries: entries.toSorted((left, right) => left.name.localeCompare(right.name)),
250 };
251 },
252 );
253​
254 const search: WorkspaceEntries["Service"]["search"] = Effect.fn("WorkspaceEntries.search")(
255 function* (input) {
256 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
257 const normalizedQuery = normalizeSearchQuery(input.query, {
258 trimLeadingPattern: /^[@./]+/,
259 });
260 return yield* Effect.gen(function* () {
261 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
262 return yield* searchIndex.search(normalizedQuery, input.limit, input.kind, input.imageOnly);
263 }).pipe(
264 Effect.provide(
265 workspaceSearchIndexes.get(
266 WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, "paths"),
267 ),
268 ),
269 );
270 },
271 );
272​
273 const searchContents: WorkspaceEntries["Service"]["searchContents"] = Effect.fn(
274 "WorkspaceEntries.searchContents",
275 )(function* (input) {
276 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
277 return yield* Effect.gen(function* () {
278 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
279 return yield* searchIndex.searchContents(input);
280 }).pipe(
281 Effect.provide(
282 workspaceSearchIndexes.get(
283 WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, "content"),
284 ),
285 ),
286 );
287 });
288​
289 const list: WorkspaceEntries["Service"]["list"] = Effect.fn("WorkspaceEntries.list")(
290 function* (input) {
291 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
292 if (input.directoryPath !== undefined) {
293 const directoryPath = input.directoryPath;
294 const toError = (cause: unknown) =>
295 new WorkspaceEntriesReadDirectoryError({
296 cwd: normalizedCwd,
297 partialPath: directoryPath,
298 parentPath: path.resolve(normalizedCwd, directoryPath),
299 cause,
300 });
301 const target =
302 directoryPath === ""
303 ? { absolutePath: normalizedCwd, relativePath: "" }
304 : yield* workspacePaths
305 .resolveRelativePathWithinRoot({
306 workspaceRoot: normalizedCwd,
307 relativePath: directoryPath,
308 })
309 .pipe(Effect.mapError(toError));
310 const { entries, throughSymlink } = yield* Effect.tryPromise({
311 try: async () => {
312 const root = await NodeFSP.realpath(normalizedCwd);
313 const directory = await NodeFSP.realpath(target.absolutePath);
314 const relative = path.relative(root, directory);
315 if (
316 relative === ".." ||
317 relative.startsWith(`..${path.sep}`) ||
318 path.isAbsolute(relative) ||
319 relative.split(path.sep).includes(".git") ||
320 target.relativePath.split("/").includes(".git")
321 ) {
322 throw new Error("Directory must be inside the workspace and outside .git.");
323 }
324 const children = await NodeFSP.readdir(directory, { withFileTypes: true });
325 return {
326 entries: children.flatMap((child): ProjectEntry[] => {
327 if (child.name === ".git" || (!child.isDirectory() && !child.isFile())) return [];
328 return [
329 {
330 path: target.relativePath ? `${target.relativePath}/${child.name}` : child.name,
331 kind: child.isDirectory() ? "directory" : "file",
332 },
333 ];
334 }),
335 // Git refuses to classify paths beyond a symbolic link.
336 throughSymlink: relative !== target.relativePath.split("/").join(path.sep),
337 };
338 },
339 catch: toError,
340 });
341 // stdin avoids argument limits; ignore classification is optional without git/repositories.
342 const checkIgnore = (paths: ReadonlyArray<string>) =>
343 vcsProcess
344 .run({
345 operation: "WorkspaceEntries.list",
346 command: "git",
347 args: ["-c", "core.fsmonitor=false", "check-ignore", "-z", "--stdin"],
348 cwd: normalizedCwd,
349 stdin: `${paths.join("\0")}\0`,
350 allowNonZeroExit: true,
351 timeoutMs: 10_000,
352 maxOutputBytes: 16 * 1024 * 1024,
353 })
354 .pipe(Effect.orElseSucceed(() => undefined));
355 // Check ignored folders once to avoid child index lookups; exit 0 guarantees no tracked descendants.
356 // Symlinks and pathspec magic still need per-child checks.
357 if (
358 entries.length > IGNORE_CHECK_CHUNK_SIZE &&
359 target.relativePath !== "" &&
360 !throughSymlink &&
361 !/^:|[*?[\\]/.test(target.relativePath) &&
362 (yield* checkIgnore([target.relativePath]))?.exitCode === 0
363 ) {
364 return {
365 entries: entries.map((entry) => ({ ...entry, ignored: true })),
366 truncated: false,
367 };
368 }
369 const ignored = new Set<string>();
370 for (let offset = 0; offset < entries.length; offset += IGNORE_CHECK_CHUNK_SIZE) {
371 const result = yield* checkIgnore(
372 entries.slice(offset, offset + IGNORE_CHECK_CHUNK_SIZE).map((entry) => entry.path),
373 );
374 if (!result || (result.exitCode !== 0 && result.exitCode !== 1)) break;
375 for (const ignoredPath of result.stdout.split("\0")) ignored.add(ignoredPath);
376 }
377 return {
378 entries: entries.map((entry) =>
379 ignored.has(entry.path) ? { ...entry, ignored: true } : entry,
380 ),
381 truncated: false,
382 };
383 }
384 return yield* Effect.gen(function* () {
385 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
386 return yield* searchIndex.list();
387 }).pipe(
388 Effect.provide(
389 workspaceSearchIndexes.get(
390 WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, "paths"),
391 ),
392 ),
393 );
394 },
395 );
396​
397 const listIgnoredFiles: WorkspaceEntries["Service"]["listIgnoredFiles"] = Effect.fn(
398 "WorkspaceEntries.listIgnoredFiles",
399 )(function* (input) {
400 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
401 // `--directory` reports a folder holding nothing but ignored files as one
402 // `name/` entry, which is how `node_modules` and build output drop out.
403 const result = yield* vcsProcess
404 .run({
405 operation: "WorkspaceEntries.listIgnoredFiles",
406 command: "git",
407 args: [
408 "-c",
409 "core.fsmonitor=false",
410 "ls-files",
411 "--others",
412 "--ignored",
413 "--exclude-standard",
414 "--directory",
415 "--no-empty-directory",
416 "-z",
417 ],
418 cwd: normalizedCwd,
419 allowNonZeroExit: true,
420 timeoutMs: 10_000,
421 maxOutputBytes: 4 * 1024 * 1024,
422 })
423 .pipe(Effect.orElseSucceed(() => undefined));
424 if (!result || result.exitCode !== 0) return { files: [], truncated: false };
425 const paths = result.stdout
426 .split("\0")
427 .filter((entry) => entry.length > 0 && !entry.endsWith("/"))
428 .toSorted();
429 const files = yield* Effect.promise(() =>
430 Promise.all(
431 paths.slice(0, IGNORED_FILES_LIMIT).map(async (relativePath) => {
432 // lstat: a symlink usually points outside the workspace, where reads refuse to go.
433 const stat = await NodeFSP.lstat(path.join(normalizedCwd, relativePath)).catch(
434 () => null,
435 );
436 return stat?.isFile() ? { path: relativePath, byteLength: stat.size } : null;
437 }),
438 ),
439 );
440 return {
441 files: files.filter((file) => file !== null),
442 truncated: paths.length > IGNORED_FILES_LIMIT,
443 };
444 });
445​
446 return WorkspaceEntries.of({ browse, list, listIgnoredFiles, refresh, search, searchContents });
447});
448​
449export const layer = Layer.effect(WorkspaceEntries, make).pipe(
450 Layer.provide(WorkspaceSearchIndex.WorkspaceSearchIndexMap.layer),
451 Layer.provide(VcsProcess.layer),
452);