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

WorkspaceEntries.ts

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