Open History to see the last commit
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 ProjectSearchContentsInput,
18 ProjectSearchContentsResult,
19 ProjectSearchEntriesInput,
20 ProjectSearchEntriesResult,
21} from "@t3tools/contracts";
22import * as HostProcess from "@t3tools/shared/HostProcess";
23import { isExplicitRelativePath, isWindowsAbsolutePath } from "@t3tools/shared/path";
24import { normalizeSearchQuery } from "@t3tools/shared/searchRanking";
25
26import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
27import * as VcsProcess from "../vcs/VcsProcess.ts";
28import * as WorkspacePaths from "./WorkspacePaths.ts";
29import * as WorkspaceSearchIndex from "./WorkspaceSearchIndex.ts";
30
31export class WorkspaceEntriesWindowsPathUnsupportedError extends Schema.TaggedError<WorkspaceEntriesWindowsPathUnsupportedError>()(
32 "WorkspaceEntriesWindowsPathUnsupportedError",
33 {
34 cwd: Schema.optional(Schema.String),
35 partialPath: Schema.String,
36 platform: Schema.String,
37 },
38) {
39 override get message(): string {
40 const cwd = this.cwd ? ` from '${this.cwd}'` : "";
41 return `Windows-style workspace path '${this.partialPath}' is not supported on '${this.platform}'${cwd}.`;
42 }
43}
44
45export class WorkspaceEntriesCurrentProjectRequiredError extends Schema.TaggedError<WorkspaceEntriesCurrentProjectRequiredError>()(
46 "WorkspaceEntriesCurrentProjectRequiredError",
47 {
48 partialPath: Schema.String,
49 },
50) {
51 override get message(): string {
52 return `A current project is required to browse relative workspace path '${this.partialPath}'.`;
53 }
54}
55
56export class WorkspaceEntriesReadDirectoryError extends Schema.TaggedError<WorkspaceEntriesReadDirectoryError>()(
57 "WorkspaceEntriesReadDirectoryError",
58 {
59 cwd: Schema.optional(Schema.String),
60 partialPath: Schema.String,
61 parentPath: Schema.String,
62 cause: Schema.Defect(),
63 },
64) {
65 override get message(): string {
66 const cwd = this.cwd ? ` from '${this.cwd}'` : "";
67 return `Failed to read workspace directory '${this.parentPath}' while browsing '${this.partialPath}'${cwd}.`;
68 }
69}
70
71export const WorkspaceEntriesBrowseError = Schema.Union([
72 WorkspaceEntriesWindowsPathUnsupportedError,
73 WorkspaceEntriesCurrentProjectRequiredError,
74 WorkspaceEntriesReadDirectoryError,
75]);
76export type WorkspaceEntriesBrowseError = typeof WorkspaceEntriesBrowseError.Type;
77
78export const WorkspaceEntriesError = Schema.Union([
79 WorkspaceEntriesReadDirectoryError,
80 WorkspacePaths.WorkspaceRootNotExistsError,
81 WorkspacePaths.WorkspaceRootCreateFailedError,
82 WorkspacePaths.WorkspaceRootStatFailedError,
83 WorkspacePaths.WorkspaceRootNotDirectoryError,
84 WorkspaceSearchIndex.WorkspaceSearchIndexCreateFailed,
85 WorkspaceSearchIndex.WorkspaceSearchIndexScanTimedOut,
86 WorkspaceSearchIndex.WorkspaceSearchIndexSearchFailed,
87]);
88export type WorkspaceEntriesError = typeof WorkspaceEntriesError.Type;
89
90export class WorkspaceEntries extends Context.Service<
91 WorkspaceEntries,
92 {
93 readonly browse: (
94 input: FilesystemBrowseInput,
95 ) => Effect.Effect<FilesystemBrowseResult, WorkspaceEntriesBrowseError>;
96 readonly list: (
97 input: ProjectListEntriesInput,
98 ) => Effect.Effect<ProjectListEntriesResult, WorkspaceEntriesError>;
99 readonly search: (
100 input: ProjectSearchEntriesInput,
101 ) => Effect.Effect<ProjectSearchEntriesResult, WorkspaceEntriesError>;
102 readonly searchContents: (
103 input: ProjectSearchContentsInput,
104 ) => Effect.Effect<ProjectSearchContentsResult, WorkspaceEntriesError>;
105 readonly refresh: (cwd: string) => Effect.Effect<void>;
106 }
107>()("t3/workspace/WorkspaceEntries") {}
108
109/** Paths sent to one `git check-ignore` call when labelling a folder's children. */
110const IGNORE_CHECK_CHUNK_SIZE = 1000;
111
112const resolveBrowseTarget = Effect.fn("WorkspaceEntries.resolveBrowseTarget")(function* (
113 input: FilesystemBrowseInput,
114 path: Path.Path,
115): Effect.fn.Return<string, WorkspaceEntriesBrowseError> {
116 const platform = yield* HostProcess.Platform;
117 if (platform !== "win32" && isWindowsAbsolutePath(input.partialPath)) {
118 return yield* new WorkspaceEntriesWindowsPathUnsupportedError({
119 cwd: input.cwd,
120 partialPath: input.partialPath,
121 platform,
122 });
123 }
124
125 if (!isExplicitRelativePath(input.partialPath)) {
126 return path.resolve(expandHomePath(input.partialPath, yield* HostProcess.HomeDirectory));
127 }
128
129 if (!input.cwd) {
130 return yield* new WorkspaceEntriesCurrentProjectRequiredError({
131 partialPath: input.partialPath,
132 });
133 }
134 return path.resolve(
135 expandHomePath(input.cwd, yield* HostProcess.HomeDirectory),
136 input.partialPath,
137 );
138});
139
140/** @public Service construction is part of the canonical Effect module API. */
141export const make = Effect.gen(function* () {
142 const path = yield* Path.Path;
143 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
144 const workspaceSearchIndexes = yield* WorkspaceSearchIndex.WorkspaceSearchIndexMap;
145 const vcsProcess = yield* VcsProcess.VcsProcess;
146
147 const normalizeWorkspaceRoot = Effect.fn("WorkspaceEntries.normalizeWorkspaceRoot")(function* (
148 cwd: string,
149 ): Effect.fn.Return<string, WorkspaceEntriesError> {
150 return yield* workspacePaths.normalizeWorkspaceRoot(cwd);
151 });
152
153 const refresh: WorkspaceEntries["Service"]["refresh"] = Effect.fn("WorkspaceEntries.refresh")(
154 function* (cwd) {
155 const normalizedCwd = yield* normalizeWorkspaceRoot(cwd).pipe(
156 Effect.orElseSucceed(() => cwd),
157 );
158 for (const variant of WorkspaceSearchIndex.WORKSPACE_SEARCH_INDEX_VARIANTS) {
159 const indexKey = WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, variant);
160 if (!(yield* RcMap.has(workspaceSearchIndexes.rcMap, indexKey))) {
161 continue;
162 }
163 const recoverRefreshFailure = Effect.fn("WorkspaceEntries.recoverRefreshFailure")(
164 function* (
165 cause:
166 | WorkspaceSearchIndex.WorkspaceSearchIndexCreateFailed
167 | WorkspaceSearchIndex.WorkspaceSearchIndexScanTimedOut
168 | WorkspaceSearchIndex.WorkspaceSearchIndexRefreshFailed,
169 ) {
170 yield* Effect.logWarning("Failed to refresh workspace search index", {
171 cwd,
172 variant,
173 cause,
174 });
175 yield* workspaceSearchIndexes.invalidate(indexKey);
176 },
177 );
178 yield* Effect.gen(function* () {
179 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
180 yield* searchIndex.refresh();
181 }).pipe(
182 Effect.provide(workspaceSearchIndexes.get(indexKey)),
183 Effect.catchTags({
184 WorkspaceSearchIndexCreateFailed: recoverRefreshFailure,
185 WorkspaceSearchIndexScanTimedOut: recoverRefreshFailure,
186 WorkspaceSearchIndexRefreshFailed: recoverRefreshFailure,
187 }),
188 );
189 }
190 },
191 );
192
193 const browse: WorkspaceEntries["Service"]["browse"] = Effect.fn("WorkspaceEntries.browse")(
194 function* (input) {
195 const resolvedInputPath = yield* resolveBrowseTarget(input, path);
196 const endsWithSeparator = /[\\/]$/.test(input.partialPath) || input.partialPath === "~";
197 const parentPath = endsWithSeparator ? resolvedInputPath : path.dirname(resolvedInputPath);
198 const prefix = endsWithSeparator ? "" : path.basename(resolvedInputPath);
199
200 const dirents = yield* Effect.tryPromise({
201 try: () => NodeFSP.readdir(parentPath, { withFileTypes: true }),
202 catch: (cause) =>
203 new WorkspaceEntriesReadDirectoryError({
204 cwd: input.cwd,
205 partialPath: input.partialPath,
206 parentPath,
207 cause,
208 }),
209 }).pipe(
210 Effect.catchIf(
211 (error) => {
212 const code = (error.cause as NodeJS.ErrnoException | undefined)?.code;
213 return code === "EACCES" || code === "EPERM";
214 },
215 () => Effect.succeed([]),
216 ),
217 );
218
219 const showHidden = endsWithSeparator || prefix.startsWith(".");
220 const lowerPrefix = prefix.toLowerCase();
221 const entries: Array<{ readonly name: string; readonly fullPath: string }> = [];
222 for (const dirent of dirents) {
223 if (
224 dirent.isDirectory() &&
225 dirent.name.toLowerCase().startsWith(lowerPrefix) &&
226 (showHidden || !dirent.name.startsWith("."))
227 ) {
228 entries.push({
229 name: dirent.name,
230 fullPath: path.join(parentPath, dirent.name),
231 });
232 }
233 }
234
235 return {
236 parentPath,
237 entries: entries.toSorted((left, right) => left.name.localeCompare(right.name)),
238 };
239 },
240 );
241
242 const search: WorkspaceEntries["Service"]["search"] = Effect.fn("WorkspaceEntries.search")(
243 function* (input) {
244 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
245 const normalizedQuery = normalizeSearchQuery(input.query, {
246 trimLeadingPattern: /^[@./]+/,
247 });
248 return yield* Effect.gen(function* () {
249 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
250 return yield* searchIndex.search(normalizedQuery, input.limit, input.kind, input.imageOnly);
251 }).pipe(
252 Effect.provide(
253 workspaceSearchIndexes.get(
254 WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, "paths"),
255 ),
256 ),
257 );
258 },
259 );
260
261 const searchContents: WorkspaceEntries["Service"]["searchContents"] = Effect.fn(
262 "WorkspaceEntries.searchContents",
263 )(function* (input) {
264 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
265 return yield* Effect.gen(function* () {
266 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
267 return yield* searchIndex.searchContents(input);
268 }).pipe(
269 Effect.provide(
270 workspaceSearchIndexes.get(
271 WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, "content"),
272 ),
273 ),
274 );
275 });
276
277 const list: WorkspaceEntries["Service"]["list"] = Effect.fn("WorkspaceEntries.list")(
278 function* (input) {
279 const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
280 if (input.directoryPath !== undefined) {
281 const directoryPath = input.directoryPath;
282 const toError = (cause: unknown) =>
283 new WorkspaceEntriesReadDirectoryError({
284 cwd: normalizedCwd,
285 partialPath: directoryPath,
286 parentPath: path.resolve(normalizedCwd, directoryPath),
287 cause,
288 });
289 const target =
290 directoryPath === ""
291 ? { absolutePath: normalizedCwd, relativePath: "" }
292 : yield* workspacePaths
293 .resolveRelativePathWithinRoot({
294 workspaceRoot: normalizedCwd,
295 relativePath: directoryPath,
296 })
297 .pipe(Effect.mapError(toError));
298 const { entries, throughSymlink } = yield* Effect.tryPromise({
299 try: async () => {
300 const root = await NodeFSP.realpath(normalizedCwd);
301 const directory = await NodeFSP.realpath(target.absolutePath);
302 const relative = path.relative(root, directory);
303 if (
304 relative === ".." ||
305 relative.startsWith(`..${path.sep}`) ||
306 path.isAbsolute(relative) ||
307 relative.split(path.sep).includes(".git") ||
308 target.relativePath.split("/").includes(".git")
309 ) {
310 throw new Error("Directory must be inside the workspace and outside .git.");
311 }
312 const children = await NodeFSP.readdir(directory, { withFileTypes: true });
313 return {
314 entries: children.flatMap((child): ProjectEntry[] => {
315 if (child.name === ".git" || (!child.isDirectory() && !child.isFile())) return [];
316 return [
317 {
318 path: target.relativePath ? `${target.relativePath}/${child.name}` : child.name,
319 kind: child.isDirectory() ? "directory" : "file",
320 },
321 ];
322 }),
323 // Git refuses to classify paths beyond a symbolic link.
324 throughSymlink: relative !== target.relativePath.split("/").join(path.sep),
325 };
326 },
327 catch: toError,
328 });
329 // Use stdin so large directories cannot exceed the command-line argument limit.
330 // Ignore classification is optional in non-git workspaces or when git is unavailable.
331 const checkIgnore = (paths: ReadonlyArray<string>) =>
332 vcsProcess
333 .run({
334 operation: "WorkspaceEntries.list",
335 command: "git",
336 args: ["-c", "core.fsmonitor=false", "check-ignore", "-z", "--stdin"],
337 cwd: normalizedCwd,
338 stdin: `${paths.join("\0")}\0`,
339 allowNonZeroExit: true,
340 timeoutMs: 10_000,
341 maxOutputBytes: 16 * 1024 * 1024,
342 })
343 .pipe(Effect.orElseSucceed(() => undefined));
344 // Git consults the index for every path it classifies, which costs hundreds of
345 // milliseconds for a `node_modules`-sized folder. Asking about the folder itself answers
346 // for every child: `check-ignore` exits 0 only when the folder is ignored and nothing
347 // under it is tracked, and an ignored folder hides all of its children. Git reads paths as
348 // pathspecs, so a folder whose path has magic (`:foo`) or glob (`[id]`) characters, or
349 // one reached through a symlink, can get a different answer per child and still asks git
350 // about each.
351 if (
352 entries.length > IGNORE_CHECK_CHUNK_SIZE &&
353 target.relativePath !== "" &&
354 !throughSymlink &&
355 !/^:|[*?[\\]/.test(target.relativePath) &&
356 (yield* checkIgnore([target.relativePath]))?.exitCode === 0
357 ) {
358 return {
359 entries: entries.map((entry) => ({ ...entry, ignored: true })),
360 truncated: false,
361 };
362 }
363 const ignored = new Set<string>();
364 for (let offset = 0; offset < entries.length; offset += IGNORE_CHECK_CHUNK_SIZE) {
365 const result = yield* checkIgnore(
366 entries.slice(offset, offset + IGNORE_CHECK_CHUNK_SIZE).map((entry) => entry.path),
367 );
368 if (!result || (result.exitCode !== 0 && result.exitCode !== 1)) break;
369 for (const ignoredPath of result.stdout.split("\0")) ignored.add(ignoredPath);
370 }
371 return {
372 entries: entries.map((entry) =>
373 ignored.has(entry.path) ? { ...entry, ignored: true } : entry,
374 ),
375 truncated: false,
376 };
377 }
378 return yield* Effect.gen(function* () {
379 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
380 return yield* searchIndex.list();
381 }).pipe(
382 Effect.provide(
383 workspaceSearchIndexes.get(
384 WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, "paths"),
385 ),
386 ),
387 );
388 },
389 );
390
391 return WorkspaceEntries.of({ browse, list, refresh, search, searchContents });
392});
393
394export const layer = Layer.effect(WorkspaceEntries, make).pipe(
395 Layer.provide(WorkspaceSearchIndex.WorkspaceSearchIndexMap.layer),
396 Layer.provide(VcsProcess.layer),
397);