Open History to see the last commit
1import {
2 FileFinder,
3 type FileItem,
4 type GrepCursor,
5 type GrepOptions,
6 type GrepResult,
7 type WatchEvent,
8} from "@ff-labs/fff-node";
9import * as NodeServices from "@effect/platform-node/NodeServices";
10import { afterEach, expect, it } from "@effect/vitest";
11import * as HostProcess from "@t3tools/shared/HostProcess";
12import * as Deferred from "effect/Deferred";
13import * as Effect from "effect/Effect";
14import * as Fiber from "effect/Fiber";
15import * as FileSystem from "effect/FileSystem";
16import * as Layer from "effect/Layer";
17import * as Path from "effect/Path";
18import * as TestClock from "effect/testing/TestClock";
19import { vi } from "vite-plus/test";
20
21import * as VcsProcess from "../vcs/VcsProcess.ts";
22import * as WorkspaceSearchIndex from "./WorkspaceSearchIndex.ts";
23
24const testLayer = VcsProcess.layer.pipe(Layer.provideMerge(NodeServices.layer));
25
26afterEach(() => {
27 vi.restoreAllMocks();
28});
29
30function fileItem(relativePath: string): FileItem {
31 return {
32 relativePath,
33 fileName: relativePath.slice(relativePath.lastIndexOf("/") + 1),
34 size: 1,
35 modified: 0,
36 accessFrecencyScore: 0,
37 modificationFrecencyScore: 0,
38 totalFrecencyScore: 0,
39 gitStatus: "clean",
40 };
41}
42
43it.effect("filters image searches before applying the result limit", () =>
44 Effect.scoped(
45 Effect.gen(function* () {
46 const items = [
47 ...Array.from({ length: 200 }, (_, index) => fileItem(`src/file-${index}.ts`)),
48 fileItem("public/icon.svg"),
49 ];
50 const fileSearch = vi.fn(async () => ({
51 ok: true as const,
52 value: {
53 items,
54 scores: [],
55 totalMatched: items.length,
56 totalFiles: items.length,
57 },
58 }));
59 const finder = {
60 destroy: vi.fn(),
61 waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })),
62 getScanProgressAsync: async () => ({
63 ok: true as const,
64 value: { isScanning: false },
65 }),
66 watch: () => ({ ok: true as const, value: () => undefined }),
67 fileSearchAsync: fileSearch,
68 } as unknown as FileFinder;
69 vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder });
70
71 const searchIndex = yield* WorkspaceSearchIndex.make("/workspace/project");
72 const resultWithoutKind = yield* searchIndex.search("", 200, undefined, true);
73 const resultWithDirectoryKind = yield* searchIndex.search("", 200, "directory", true);
74
75 expect(resultWithoutKind.entries).toEqual([{ kind: "file", path: "public/icon.svg" }]);
76 expect(resultWithDirectoryKind.entries).toEqual([{ kind: "file", path: "public/icon.svg" }]);
77 expect(fileSearch).toHaveBeenCalledTimes(2);
78 expect(fileSearch).toHaveBeenCalledWith("", { pageSize: 25_002 });
79 }),
80 ).pipe(Effect.provide(testLayer)),
81);
82
83it.effect("fetches past a first page of Git-ignored results", () =>
84 Effect.scoped(
85 Effect.gen(function* () {
86 const fs = yield* FileSystem.FileSystem;
87 const path = yield* Path.Path;
88 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-search-ignored-" });
89 const vcsProcess = yield* VcsProcess.VcsProcess;
90 yield* vcsProcess.run({ operation: "test.gitInit", command: "git", args: ["init"], cwd });
91 yield* fs.writeFileString(path.join(cwd, ".git", "info", "exclude"), "hidden/\n");
92 yield* fs.makeDirectory(path.join(cwd, "hidden"));
93 yield* fs.writeFileString(path.join(cwd, "hidden", "a.ts"), "");
94
95 const items = [
96 fileItem("hidden/a.ts"),
97 fileItem("hidden/b.ts"),
98 fileItem("hidden/c.ts"),
99 fileItem("src/a.ts"),
100 ];
101 const fileSearch = vi.fn(async (_query: string, options?: { pageSize?: number }) => ({
102 ok: true as const,
103 value: {
104 items: items.slice(0, options?.pageSize),
105 scores: [],
106 totalMatched: items.length,
107 totalFiles: items.length,
108 },
109 }));
110 const finder = {
111 destroy: vi.fn(),
112 waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })),
113 getScanProgressAsync: async () => ({
114 ok: true as const,
115 value: { isScanning: false },
116 }),
117 watch: () => ({ ok: true as const, value: () => undefined }),
118 fileSearchAsync: fileSearch,
119 } as unknown as FileFinder;
120 vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder });
121
122 const searchIndex = yield* WorkspaceSearchIndex.make(cwd);
123 const result = yield* searchIndex.search("a", 1, "file", false);
124
125 expect(result).toEqual({ entries: [{ kind: "file", path: "src/a.ts" }], truncated: false });
126 }),
127 ).pipe(Effect.provide(testLayer)),
128);
129
130// A backslash is a file name character on Linux and macOS, so only Windows may treat it as a separator.
131it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
132 "keeps a backslash in a POSIX folder name as part of the search result path",
133 () =>
134 Effect.scoped(
135 Effect.gen(function* () {
136 const items = [fileItem("dir\\one/report.txt")];
137 const finder = {
138 destroy: vi.fn(),
139 waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })),
140 getScanProgressAsync: async () => ({
141 ok: true as const,
142 value: { isScanning: false },
143 }),
144 watch: () => ({ ok: true as const, value: () => undefined }),
145 fileSearchAsync: vi.fn(async () => ({
146 ok: true as const,
147 value: { items, scores: [], totalMatched: 1, totalFiles: 1 },
148 })),
149 } as unknown as FileFinder;
150 vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder });
151
152 const searchIndex = yield* WorkspaceSearchIndex.make("/workspace/project");
153 const result = yield* searchIndex.search("report", 50, "file");
154
155 expect(result.entries).toEqual([{ kind: "file", path: "dir\\one/report.txt" }]);
156 }),
157 ).pipe(Effect.provide(testLayer)),
158);
159
160it.effect("continues whole-word searches after a filtered grep page", () =>
161 Effect.scoped(
162 Effect.gen(function* () {
163 const nextCursor = {
164 __brand: "GrepCursor",
165 _offset: 1,
166 } as GrepCursor;
167 const grepResult = (
168 lineContent: string,
169 matchRanges: Array<[number, number]>,
170 cursor: GrepCursor | null,
171 ): GrepResult => ({
172 items: [
173 {
174 relativePath: "src/words.ts",
175 fileName: "words.ts",
176 gitStatus: "unmodified",
177 size: lineContent.length,
178 modified: 0,
179 isBinary: false,
180 totalFrecencyScore: 0,
181 accessFrecencyScore: 0,
182 modificationFrecencyScore: 0,
183 lineNumber: 1,
184 col: 0,
185 byteOffset: 0,
186 lineContent,
187 matchRanges,
188 },
189 ],
190 totalMatched: 1,
191 totalFilesSearched: 1,
192 totalFiles: 1,
193 filteredFileCount: 1,
194 nextCursor: cursor,
195 });
196 const grep = vi.fn(async (_query: string, options?: GrepOptions) =>
197 options?.cursor
198 ? { ok: true as const, value: grepResult("needle", [[0, 6]], null) }
199 : {
200 ok: true as const,
201 value: grepResult("needleSuffix", [[0, 6]], nextCursor),
202 },
203 );
204 const finder = {
205 destroy: vi.fn(),
206 waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })),
207 getScanProgressAsync: async () => ({
208 ok: true as const,
209 value: { isScanning: false },
210 }),
211 watch: () => ({ ok: true as const, value: () => undefined }),
212 grepAsync: grep,
213 } as unknown as FileFinder;
214 vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder });
215
216 const searchIndex = yield* WorkspaceSearchIndex.make("/workspace/project", "content");
217 const result = yield* searchIndex.searchContents({
218 query: "needle",
219 limit: 1,
220 caseSensitive: true,
221 wholeWord: true,
222 useRegex: false,
223 });
224
225 expect(result).toEqual({
226 matches: [
227 {
228 path: "src/words.ts",
229 lineNumber: 1,
230 lineContent: "needle",
231 matchRanges: [{ start: 0, end: 6 }],
232 },
233 ],
234 truncated: false,
235 });
236 expect(grep).toHaveBeenCalledTimes(2);
237 expect(grep.mock.calls[1]?.[1]?.cursor).toBe(nextCursor);
238 }),
239 ).pipe(Effect.provide(testLayer)),
240);
241
242function fakeSymlinkFinder(
243 directories: ReadonlyArray<string>,
244 options: {
245 readonly indexed?: ReadonlyArray<{
246 readonly path: string;
247 readonly kind: "file" | "directory";
248 }>;
249 readonly watchFailures?: number;
250 } = {},
251) {
252 const watchers: Array<(events: ReadonlyArray<WatchEvent>) => void> = [];
253 let watchFailures = options.watchFailures ?? 0;
254 // fff's pageIndex is an offset into the results, not a page number.
255 const directorySearch = vi.fn(
256 async (_query: string, searchOptions?: { pageIndex?: number; pageSize?: number }) => {
257 const offset = searchOptions?.pageIndex ?? 0;
258 const items = directories.slice(offset, offset + (searchOptions?.pageSize ?? 100));
259 return {
260 ok: true as const,
261 value: {
262 items: items.map((relativePath) => ({ relativePath })),
263 totalMatched: directories.length,
264 },
265 };
266 },
267 );
268 const indexedItems = (options.indexed ?? []).map((entry) => ({
269 type: entry.kind,
270 item: { relativePath: entry.path, fileName: entry.path.split("/").at(-1) },
271 }));
272 const finder = {
273 destroy: vi.fn(),
274 waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })),
275 // fff's isScanning waits on the picker lock on the JS thread.
276 isScanning: () => {
277 throw new Error("isScanning must not run on the JS thread");
278 },
279 getScanProgressAsync: async () => ({
280 ok: true as const,
281 value: { isScanning: false },
282 }),
283 watch: (callback: (events: ReadonlyArray<WatchEvent>) => void) => {
284 if (watchFailures > 0) {
285 watchFailures -= 1;
286 throw new Error("File system watcher is not ready");
287 }
288 watchers.push(callback);
289 return { ok: true as const, value: () => undefined };
290 },
291 directorySearchAsync: directorySearch,
292 fileSearchAsync: async () => {
293 const items = indexedItems.flatMap((entry) => (entry.type === "file" ? [entry.item] : []));
294 return { ok: true as const, value: { items, scores: [], totalMatched: items.length } };
295 },
296 mixedSearchAsync: async () => ({
297 ok: true as const,
298 value: { items: indexedItems, totalMatched: indexedItems.length },
299 }),
300 } as unknown as FileFinder;
301 vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder });
302 return {
303 directorySearch,
304 notifyWatchers: (events: ReadonlyArray<WatchEvent>) =>
305 watchers.forEach((watcher) => watcher(events)),
306 };
307}
308
309const listedPaths = (searchIndex: WorkspaceSearchIndex.WorkspaceSearchIndex["Service"]) =>
310 searchIndex.list().pipe(Effect.map((result) => result.entries.map((entry) => entry.path)));
311
312it.effect("reads symlinks again after the watcher reports a change", () =>
313 Effect.scoped(
314 Effect.gen(function* () {
315 if ((yield* HostProcess.Platform) === "win32") return;
316 const fileSystem = yield* FileSystem.FileSystem;
317 const path = yield* Path.Path;
318 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-symlink-watch-" });
319 const outside = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-outside-" });
320 yield* fileSystem.writeFileString(path.join(cwd, "a.ts"), "");
321 yield* fileSystem.symlink("a.ts", path.join(cwd, "old-link.ts"));
322 const { directorySearch, notifyWatchers } = fakeSymlinkFinder([]);
323
324 const searchIndex = yield* WorkspaceSearchIndex.make(cwd);
325 const concurrent = yield* Effect.all(
326 Array.from({ length: 8 }, () => listedPaths(searchIndex)),
327 { concurrency: "unbounded" },
328 );
329 yield* fileSystem.remove(path.join(cwd, "old-link.ts"));
330 yield* fileSystem.symlink("a.ts", path.join(cwd, "new-link.ts"));
331 const beforeNotice = yield* listedPaths(searchIndex);
332 // Editing a file cannot move a link, so it does not cost a rescan.
333 notifyWatchers([{ kind: "modified", path: path.join(cwd, "a.ts") }]);
334 const afterEdit = yield* listedPaths(searchIndex);
335 notifyWatchers([{ kind: "created", path: path.join(cwd, "new-link.ts") }]);
336 const afterNotice = yield* listedPaths(searchIndex);
337 // fff reports a link replaced in place as modified.
338 yield* fileSystem.remove(path.join(cwd, "new-link.ts"));
339 yield* fileSystem.symlink(outside, path.join(cwd, "new-link.ts"));
340 notifyWatchers([{ kind: "modified", path: path.join(cwd, "new-link.ts") }]);
341 const afterReplace = yield* listedPaths(searchIndex);
342
343 expect(concurrent).toEqual(Array.from({ length: 8 }, () => ["old-link.ts"]));
344 expect(beforeNotice).toEqual(["old-link.ts"]);
345 expect(afterEdit).toEqual(["old-link.ts"]);
346 expect(afterNotice).toEqual(["new-link.ts"]);
347 expect(afterReplace).toEqual([]);
348 expect(directorySearch).toHaveBeenCalledTimes(3);
349 }),
350 ).pipe(Effect.provide(testLayer)),
351);
352
353it.effect("answers from the last symlink scan while a slow rescan runs", () =>
354 Effect.scoped(
355 Effect.gen(function* () {
356 if ((yield* HostProcess.Platform) === "win32") return;
357 const fileSystem = yield* FileSystem.FileSystem;
358 const path = yield* Path.Path;
359 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-symlink-stale-" });
360 yield* fileSystem.writeFileString(path.join(cwd, "a.ts"), "");
361 yield* fileSystem.symlink("a.ts", path.join(cwd, "old-link.ts"));
362 const { notifyWatchers } = fakeSymlinkFinder([]);
363 // Holding git's ignore check open keeps the rescan from finishing.
364 const gate = yield* Deferred.make<void>();
365 let holdIgnoreChecks = false;
366 const vcsProcess = yield* VcsProcess.VcsProcess;
367 const searchIndex = yield* WorkspaceSearchIndex.make(cwd).pipe(
368 Effect.provideService(VcsProcess.VcsProcess, {
369 ...vcsProcess,
370 run: (input) =>
371 holdIgnoreChecks && input.operation === "WorkspaceSearchIndex.listGitIgnored"
372 ? Deferred.await(gate).pipe(Effect.andThen(vcsProcess.run(input)))
373 : vcsProcess.run(input),
374 }),
375 );
376 expect(yield* listedPaths(searchIndex)).toEqual(["old-link.ts"]);
377
378 holdIgnoreChecks = true;
379 yield* fileSystem.symlink("a.ts", path.join(cwd, "new-link.ts"));
380 notifyWatchers([{ kind: "created", path: path.join(cwd, "new-link.ts") }]);
381 const duringRescan = yield* Effect.forkChild(listedPaths(searchIndex));
382 yield* TestClock.adjust("1 second");
383 expect(yield* Fiber.join(duringRescan)).toEqual(["old-link.ts"]);
384
385 yield* Deferred.succeed(gate, undefined);
386 expect(yield* listedPaths(searchIndex)).toEqual(["new-link.ts", "old-link.ts"]);
387 }),
388 ).pipe(Effect.provide(testLayer)),
389);
390
391it.effect("keeps symlinks once the watcher subscribes after starting late", () =>
392 Effect.scoped(
393 Effect.gen(function* () {
394 if ((yield* HostProcess.Platform) === "win32") return;
395 const fileSystem = yield* FileSystem.FileSystem;
396 const path = yield* Path.Path;
397 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-symlink-watch-" });
398 yield* fileSystem.writeFileString(path.join(cwd, "a.ts"), "");
399 yield* fileSystem.symlink("a.ts", path.join(cwd, "link.ts"));
400 const { directorySearch } = fakeSymlinkFinder([], { watchFailures: 2 });
401
402 const searchIndex = yield* WorkspaceSearchIndex.make(cwd);
403 const scansAfterRound: number[] = [];
404 for (let round = 0; round < 5; round += 1) {
405 expect(yield* listedPaths(searchIndex)).toEqual(["link.ts"]);
406 expect(yield* listedPaths(searchIndex)).toEqual(["link.ts"]);
407 scansAfterRound.push(directorySearch.mock.calls.length);
408 yield* TestClock.adjust("1 minute");
409 }
410
411 // An unwatched scan serves reads only briefly; the third has a watcher and is kept.
412 expect(scansAfterRound).toEqual([1, 2, 3, 3, 3]);
413 }),
414 ).pipe(Effect.provide(testLayer)),
415);
416
417it.effect(
418 "lists a symlink the watcher indexed once, with the link's kind, and drops rejected ones",
419 () =>
420 Effect.scoped(
421 Effect.gen(function* () {
422 if ((yield* HostProcess.Platform) === "win32") return;
423 const fileSystem = yield* FileSystem.FileSystem;
424 const path = yield* Path.Path;
425 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-symlink-dupe-" });
426 const outside = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-outside-" });
427 yield* fileSystem.makeDirectory(path.join(cwd, "src"));
428 yield* fileSystem.symlink("src", path.join(cwd, "src-link"));
429 // A link the scan rejects stays out even when the watcher indexed it.
430 yield* fileSystem.symlink(outside, path.join(cwd, "outside-link"));
431 fakeSymlinkFinder([], {
432 indexed: [
433 { path: "outside-link", kind: "file" },
434 { path: "src-link", kind: "file" },
435 { path: "link-file.ts", kind: "file" },
436 ],
437 });
438
439 const searchIndex = yield* WorkspaceSearchIndex.make(cwd);
440 const searched = yield* searchIndex.search("link", 10);
441 const files = yield* searchIndex.search("link", 1, "file");
442 const listed = yield* searchIndex.list();
443
444 expect(searched.entries).toEqual([
445 { path: "src-link", kind: "directory" },
446 { path: "link-file.ts", kind: "file" },
447 ]);
448 // The dropped link does not take the only slot.
449 expect(files).toEqual({
450 entries: [{ path: "link-file.ts", kind: "file" }],
451 truncated: false,
452 });
453 expect(listed.entries).toEqual([
454 { path: "link-file.ts", kind: "file" },
455 { path: "src-link", kind: "directory" },
456 ]);
457 }),
458 ).pipe(Effect.provide(testLayer)),
459);
460
461it.effect("finds symlinks in folders past the first page of the index", () =>
462 Effect.scoped(
463 Effect.gen(function* () {
464 if ((yield* HostProcess.Platform) === "win32") return;
465 const fileSystem = yield* FileSystem.FileSystem;
466 const path = yield* Path.Path;
467 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-symlink-pages-" });
468 yield* fileSystem.makeDirectory(path.join(cwd, "late"));
469 yield* fileSystem.writeFileString(path.join(cwd, "late/a.ts"), "");
470 yield* fileSystem.symlink("a.ts", path.join(cwd, "late/link.ts"));
471 // Folders fff lists but that are gone by the time they are read are skipped.
472 const firstPage = Array.from({ length: 1_000 }, (_, index) => `missing-${index}`);
473 const { directorySearch } = fakeSymlinkFinder([...firstPage, "late"]);
474
475 const searchIndex = yield* WorkspaceSearchIndex.make(cwd);
476
477 expect(yield* listedPaths(searchIndex)).toEqual(["late", "late/link.ts"]);
478 expect(directorySearch.mock.calls.map(([, options]) => options?.pageIndex)).toEqual([
479 0, 1_000,
480 ]);
481 }),
482 ).pipe(Effect.provide(testLayer)),
483);
484
485// fff reads HOME on Linux and macOS but the user profile on Windows, so a temp HOME cannot stand in there.
486it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
487 "refuses to index a workspace rooted at the home directory",
488 () =>
489 Effect.scoped(
490 Effect.gen(function* () {
491 const fs = yield* FileSystem.FileSystem;
492 const path = yield* Path.Path;
493 const home = yield* fs.realPath(
494 yield* fs.makeTempDirectoryScoped({ prefix: "t3-search-home-" }),
495 );
496 yield* fs.makeDirectory(path.join(home, "OneDrive", "Remix"), { recursive: true });
497 yield* fs.writeFileString(path.join(home, "OneDrive", "Remix", "part.stl"), "solid part\n");
498 yield* Effect.acquireRelease(
499 Effect.sync(() => vi.stubEnv("HOME", home)),
500 () => Effect.sync(() => vi.unstubAllEnvs()),
501 );
502
503 const result = yield* WorkspaceSearchIndex.make(home).pipe(
504 Effect.flatMap((searchIndex) => searchIndex.search("stl", 50, undefined, false)),
505 Effect.map(({ entries }) => entries),
506 Effect.catchTags({
507 WorkspaceSearchIndexCreateFailed: (error) => Effect.succeed(error._tag),
508 }),
509 );
510
511 expect(result).toBe("WorkspaceSearchIndexCreateFailed");
512 }),
513 ).pipe(Effect.provide(testLayer)),
514);