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 { PROJECT_FAVICON_EXTENSIONS, isProjectFaviconPath } from "@t3tools/shared/projectFavicon";
13import * as Deferred from "effect/Deferred";
14import * as Effect from "effect/Effect";
15import { ChildProcessSpawner } from "effect/process";
16import * as Fiber from "effect/Fiber";
17import * as FileSystem from "effect/FileSystem";
18import * as Layer from "effect/Layer";
19import * as Path from "effect/Path";
20import * as TestClock from "effect/testing/TestClock";
21import { vi } from "vite-plus/test";
22
23import * as VcsProcess from "../vcs/VcsProcess.ts";
24import * as WorkspaceSearchIndex from "./WorkspaceSearchIndex.ts";
25
26const testLayer = VcsProcess.layer.pipe(Layer.provideMerge(NodeServices.layer));
27
28afterEach(() => {
29 vi.restoreAllMocks();
30});
31
32function fileItem(relativePath: string): FileItem {
33 return {
34 relativePath,
35 fileName: relativePath.slice(relativePath.lastIndexOf("/") + 1),
36 size: 1,
37 modified: 0,
38 accessFrecencyScore: 0,
39 modificationFrecencyScore: 0,
40 totalFrecencyScore: 0,
41 gitStatus: "clean",
42 };
43}
44
45it.live("image searches match the image subset of a file search without fetching every file", () =>
46 Effect.gen(function* () {
47 const fileSystem = yield* FileSystem.FileSystem;
48 const path = yield* Path.Path;
49 const vcsProcess = yield* VcsProcess.VcsProcess;
50 const writeFiles = Effect.fn(function* (root: string, relativePaths: ReadonlyArray<string>) {
51 for (const relativePath of relativePaths) {
52 yield* fileSystem.makeDirectory(path.dirname(path.join(root, relativePath)), {
53 recursive: true,
54 });
55 yield* fileSystem.writeFileString(path.join(root, relativePath), "");
56 yield* fileSystem.utimes(path.join(root, relativePath), 0, 0);
57 }
58 });
59
60 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-image-search-" });
61 yield* vcsProcess.run({ operation: "test.gitInit", command: "git", args: ["init"], cwd });
62 yield* fileSystem.writeFileString(path.join(cwd, ".git/info/exclude"), "hidden/\n");
63 yield* writeFiles(cwd, [
64 ...Array.from({ length: 220 }, (_, index) => `assets/source-${index}.ts`),
65 ...PROJECT_FAVICON_EXTENSIONS.flatMap((extension) => [
66 `assets/logo${extension}`,
67 `other/logo${extension.toUpperCase()}`,
68 ]),
69 "assets/logo.ts",
70 "assets/logotype.png",
71 "assetss/logotype.png",
72 "assets/images/logo.PNG",
73 "assets/foo{bar}.png",
74 "assets/[id].png",
75 "hidden/logo.png",
76 ]);
77
78 const fileSearch = vi.spyOn(FileFinder.prototype, "fileSearchAsync");
79 const searchIndex = yield* WorkspaceSearchIndex.make(cwd);
80 yield* searchIndex.search("", 200, undefined, true);
81 const nativeResult = yield* Effect.promise(
82 (): ReturnType<FileFinder["fileSearchAsync"]> => fileSearch.mock.results[0]?.value,
83 );
84 if (!nativeResult.ok) return yield* Effect.die(nativeResult.error);
85 expect(nativeResult.value.items.length).toBeLessThanOrEqual(201);
86
87 // The image glob must not change fff's parse of fuzzy paths, globs, negations or locations.
88 for (const query of [
89 "",
90 "logo",
91 "lgo",
92 "*.png",
93 "!*.png",
94 "assets/**",
95 "!assets/",
96 "assets*/",
97 "/assets",
98 "assets/",
99 "logo:12",
100 "/assets/logotype.png",
101 "assets/images/",
102 "logo *.svg !other",
103 "foo{bar}.png",
104 "[id].png",
105 "*.{png,svg}",
106 "hidden/",
107 ]) {
108 const ordinary = yield* searchIndex.search(query, 1000, "file");
109 const expected = ordinary.entries.filter((entry) => isProjectFaviconPath(entry.path));
110 for (const limit of [1, 200]) {
111 const images = yield* searchIndex.search(query, limit, "directory", true);
112 expect(images, `query=${query} limit=${limit}`).toEqual({
113 entries: expected.slice(0, limit),
114 truncated: expected.length > limit,
115 });
116 }
117 }
118
119 // Past 15,000 matches fff drops its filename fallback, which the image glob would otherwise
120 // reorder: "x/logo/logo.png" must keep its place relative to "a/xxlogo.png".
121 const largeCwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-image-rank-" });
122 yield* writeFiles(largeCwd, [
123 ...Array.from({ length: 14_998 }, (_, index) => `b/logo-${index}.png`),
124 "x/logo/source.ts",
125 "a/xxlogo.png",
126 "x/logo/logo.png",
127 ]);
128 const largeIndex = yield* WorkspaceSearchIndex.make(largeCwd);
129 const pairPaths = ["a/xxlogo.png", "x/logo/logo.png"];
130 const ordinary = yield* largeIndex.search("logo", 20_000, "file");
131 const images = yield* largeIndex.search("logo", 20_000, "file", true);
132 expect(images.entries).toHaveLength(15_000);
133 expect(images.entries.filter((entry) => pairPaths.includes(entry.path))).toEqual(
134 ordinary.entries.filter((entry) => pairPaths.includes(entry.path)),
135 );
136 }).pipe(Effect.scoped, Effect.provide(testLayer)),
137);
138
139it.effect("fetches past a first page of Git-ignored results", () =>
140 Effect.scoped(
141 Effect.gen(function* () {
142 const fs = yield* FileSystem.FileSystem;
143 const path = yield* Path.Path;
144 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-search-ignored-" });
145 const vcsProcess = yield* VcsProcess.VcsProcess;
146 yield* vcsProcess.run({ operation: "test.gitInit", command: "git", args: ["init"], cwd });
147 yield* fs.writeFileString(path.join(cwd, ".git", "info", "exclude"), "hidden/\n");
148 yield* fs.makeDirectory(path.join(cwd, "hidden"));
149 yield* fs.writeFileString(path.join(cwd, "hidden", "a.ts"), "");
150
151 const items = [
152 fileItem("hidden/a.ts"),
153 fileItem("hidden/b.ts"),
154 fileItem("hidden/c.ts"),
155 fileItem("src/a.ts"),
156 ];
157 const fileSearch = vi.fn(async (_query: string, options?: { pageSize?: number }) => ({
158 ok: true as const,
159 value: {
160 items: items.slice(0, options?.pageSize),
161 scores: [],
162 totalMatched: items.length,
163 totalFiles: items.length,
164 },
165 }));
166 const finder = {
167 destroy: vi.fn(),
168 waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })),
169 getScanProgressAsync: async () => ({
170 ok: true as const,
171 value: { isScanning: false },
172 }),
173 watchAsync: async () => ({ ok: true as const, value: () => undefined }),
174 fileSearchAsync: fileSearch,
175 } as unknown as FileFinder;
176 vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder });
177
178 const searchIndex = yield* WorkspaceSearchIndex.make(cwd);
179 const result = yield* searchIndex.search("a", 1, "file", false);
180
181 expect(result).toEqual({ entries: [{ kind: "file", path: "src/a.ts" }], truncated: false });
182 }),
183 ).pipe(Effect.provide(testLayer)),
184);
185
186// A backslash is a file name character on Linux and macOS, so only Windows may treat it as a separator.
187it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
188 "keeps a backslash in a POSIX folder name as part of the search result path",
189 () =>
190 Effect.scoped(
191 Effect.gen(function* () {
192 const items = [fileItem("dir\\one/report.txt")];
193 const finder = {
194 destroy: vi.fn(),
195 waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })),
196 getScanProgressAsync: async () => ({
197 ok: true as const,
198 value: { isScanning: false },
199 }),
200 watchAsync: async () => ({ ok: true as const, value: () => undefined }),
201 fileSearchAsync: vi.fn(async () => ({
202 ok: true as const,
203 value: { items, scores: [], totalMatched: 1, totalFiles: 1 },
204 })),
205 } as unknown as FileFinder;
206 vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder });
207
208 const searchIndex = yield* WorkspaceSearchIndex.make("/workspace/project");
209 const result = yield* searchIndex.search("report", 50, "file");
210
211 expect(result.entries).toEqual([{ kind: "file", path: "dir\\one/report.txt" }]);
212 }),
213 ).pipe(Effect.provide(testLayer)),
214);
215
216it.effect("continues whole-word searches after a filtered grep page", () =>
217 Effect.scoped(
218 Effect.gen(function* () {
219 const nextCursor = {
220 __brand: "GrepCursor",
221 _offset: 1,
222 } as GrepCursor;
223 const grepResult = (
224 lineContent: string,
225 matchRanges: Array<[number, number]>,
226 cursor: GrepCursor | null,
227 ): GrepResult => ({
228 items: [
229 {
230 relativePath: "src/words.ts",
231 fileName: "words.ts",
232 gitStatus: "unmodified",
233 size: lineContent.length,
234 modified: 0,
235 isBinary: false,
236 totalFrecencyScore: 0,
237 accessFrecencyScore: 0,
238 modificationFrecencyScore: 0,
239 lineNumber: 1,
240 col: 0,
241 byteOffset: 0,
242 lineContent,
243 matchRanges,
244 },
245 ],
246 totalMatched: 1,
247 totalFilesSearched: 1,
248 totalFiles: 1,
249 filteredFileCount: 1,
250 nextCursor: cursor,
251 });
252 const grep = vi.fn(async (_query: string, options?: GrepOptions) =>
253 options?.cursor
254 ? { ok: true as const, value: grepResult("needle", [[0, 6]], null) }
255 : {
256 ok: true as const,
257 value: grepResult("needleSuffix", [[0, 6]], nextCursor),
258 },
259 );
260 const finder = {
261 destroy: vi.fn(),
262 waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })),
263 getScanProgressAsync: async () => ({
264 ok: true as const,
265 value: { isScanning: false },
266 }),
267 watchAsync: async () => ({ ok: true as const, value: () => undefined }),
268 grepAsync: grep,
269 } as unknown as FileFinder;
270 vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder });
271
272 const searchIndex = yield* WorkspaceSearchIndex.make("/workspace/project", "content");
273 const result = yield* searchIndex.searchContents({
274 query: "needle",
275 limit: 1,
276 caseSensitive: true,
277 wholeWord: true,
278 useRegex: false,
279 });
280
281 expect(result).toEqual({
282 matches: [
283 {
284 path: "src/words.ts",
285 lineNumber: 1,
286 lineContent: "needle",
287 matchRanges: [{ start: 0, end: 6 }],
288 },
289 ],
290 truncated: false,
291 });
292 expect(grep).toHaveBeenCalledTimes(2);
293 expect(grep.mock.calls[1]?.[1]?.cursor).toBe(nextCursor);
294 }),
295 ).pipe(Effect.provide(testLayer)),
296);
297
298it.live("answers content searches with git grep while a slow content index builds", () =>
299 Effect.gen(function* () {
300 const fileSystem = yield* FileSystem.FileSystem;
301 const path = yield* Path.Path;
302 const vcsProcess = yield* VcsProcess.VcsProcess;
303 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-content-warmup-" });
304 yield* vcsProcess.run({ operation: "test.gitInit", command: "git", args: ["init"], cwd });
305 yield* fileSystem.writeFileString(path.join(cwd, ".gitignore"), "ignored.txt\n");
306 yield* fileSystem.makeDirectory(path.join(cwd, "src"));
307 yield* fileSystem.writeFileString(
308 path.join(cwd, "src/a.ts"),
309 "const Needle = 1;\r\nneedles(a.b);\nnone\n",
310 );
311 yield* fileSystem.writeFileString(path.join(cwd, "ignored.txt"), "needle\n");
312 // fff leaves out what `.ignore` excludes, so git results must leave it out too.
313 yield* fileSystem.writeFileString(path.join(cwd, ".ignore"), "out/\n");
314 yield* fileSystem.makeDirectory(path.join(cwd, "out/deep"), { recursive: true });
315 yield* fileSystem.writeFileString(path.join(cwd, "out/deep/g.txt"), "needle\n");
316
317 let isWarmupComplete = false;
318 const grep = vi.fn(async () => ({
319 ok: true as const,
320 value: {
321 items: [],
322 totalMatched: 0,
323 totalFilesSearched: 0,
324 totalFiles: 0,
325 filteredFileCount: 0,
326 nextCursor: null,
327 } satisfies GrepResult,
328 }));
329 const finder = {
330 destroy: vi.fn(),
331 waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: false })),
332 getScanProgressAsync: async () => ({
333 ok: true as const,
334 value: { isScanning: false, isWarmupComplete },
335 }),
336 watchAsync: async () => ({ ok: true as const, value: () => undefined }),
337 grepAsync: grep,
338 } as unknown as FileFinder;
339 const noPcreFinder = {
340 ...finder,
341 waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })),
342 } as unknown as FileFinder;
343 vi.spyOn(FileFinder, "create")
344 .mockReturnValueOnce({ ok: true, value: finder })
345 .mockReturnValueOnce({ ok: true, value: noPcreFinder })
346 .mockReturnValueOnce({ ok: true, value: noPcreFinder })
347 .mockReturnValueOnce({ ok: true, value: noPcreFinder });
348
349 const searchIndex = yield* WorkspaceSearchIndex.make(cwd, "content");
350 const search = (input: Partial<Parameters<typeof searchIndex.searchContents>[0]>) =>
351 searchIndex.searchContents({
352 query: "needle",
353 limit: 10,
354 caseSensitive: false,
355 wholeWord: false,
356 useRegex: false,
357 ...input,
358 });
359
360 expect(yield* search({})).toEqual({
361 matches: [
362 {
363 path: "src/a.ts",
364 lineNumber: 1,
365 lineContent: "const Needle = 1;",
366 matchRanges: [{ start: 6, end: 12 }],
367 },
368 {
369 path: "src/a.ts",
370 lineNumber: 2,
371 lineContent: "needles(a.b);",
372 matchRanges: [{ start: 0, end: 6 }],
373 },
374 ],
375 truncated: false,
376 });
377 expect((yield* search({ caseSensitive: true, wholeWord: true })).matches).toEqual([]);
378 expect((yield* search({ query: "a.b" })).matches.map((match) => match.matchRanges)).toEqual([
379 [{ start: 8, end: 11 }],
380 ]);
381 expect(
382 (yield* search({ query: "ne+dles?", useRegex: true })).matches.map(
383 (match) => match.matchRanges,
384 ),
385 ).toEqual([[{ start: 6, end: 12 }], [{ start: 0, end: 7 }]]);
386 expect(
387 (yield* search({ query: "[a-z]e", useRegex: true })).matches.map(
388 (match) => match.matchRanges,
389 ),
390 ).toEqual([
391 [{ start: 4, end: 6 }],
392 [
393 { start: 6, end: 8 },
394 { start: 10, end: 12 },
395 ],
396 [
397 { start: 0, end: 2 },
398 { start: 4, end: 6 },
399 ],
400 [{ start: 2, end: 4 }],
401 ]);
402 const invalid = yield* search({ query: "a.b(", useRegex: true });
403 expect(invalid.matches).toEqual([]);
404 expect(invalid.regexFallbackError).toBeDefined();
405 expect(yield* search({ limit: 1 })).toMatchObject({ truncated: true });
406 expect(grep).not.toHaveBeenCalled();
407
408 // When git cannot give regex results or their ranges, fff answers once ready instead.
409 const failingGitIndex = (
410 failingArgument: string,
411 stderr: string,
412 output: { readonly exitCode: number; readonly stdout: string } = {
413 exitCode: 128,
414 stdout: "",
415 },
416 ) =>
417 WorkspaceSearchIndex.make(cwd, "content").pipe(
418 Effect.provideService(
419 VcsProcess.VcsProcess,
420 VcsProcess.VcsProcess.of({
421 run: (input) =>
422 input.args.includes(failingArgument)
423 ? Effect.succeed({
424 exitCode: ChildProcessSpawner.ExitCode(output.exitCode),
425 stdout: output.stdout,
426 stderr,
427 stdoutTruncated: output.exitCode === 0,
428 stderrTruncated: false,
429 })
430 : vcsProcess.run(input),
431 }),
432 ),
433 );
434 const regexInput = {
435 query: "ne+dles?",
436 limit: 10,
437 caseSensitive: false,
438 wholeWord: true,
439 useRegex: true,
440 };
441 const noPcreIndex = yield* failingGitIndex(
442 "-P",
443 "fatal: cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE\n",
444 );
445 expect((yield* noPcreIndex.searchContents(regexInput)).regexFallbackError).toBeUndefined();
446 expect(grep).toHaveBeenCalledTimes(1);
447 const noRangesIndex = yield* failingGitIndex("-o", "fatal: unexpected failure\n");
448 yield* noRangesIndex.searchContents(regexInput);
449 expect(grep).toHaveBeenCalledTimes(2);
450 // Ranges output cut off after line 1: line 2 is left out and the result says so.
451 const cutRangesIndex = yield* failingGitIndex("-o", "", {
452 exitCode: 0,
453 stdout: "src/a.ts\u00001\u00007\u0000Needle\nsrc/a.ts\u00002",
454 });
455 expect(yield* cutRangesIndex.searchContents(regexInput)).toEqual({
456 matches: [
457 {
458 path: "src/a.ts",
459 lineNumber: 1,
460 lineContent: "const Needle = 1;",
461 matchRanges: [{ start: 6, end: 12 }],
462 },
463 ],
464 truncated: true,
465 });
466
467 isWarmupComplete = true;
468 yield* search({});
469 expect(grep).toHaveBeenCalledTimes(3);
470 expect(finder.destroy).not.toHaveBeenCalled();
471 }).pipe(Effect.scoped, Effect.provide(testLayer)),
472);
473
474function fakeSymlinkFinder(
475 directories: ReadonlyArray<string>,
476 options: {
477 readonly indexed?: ReadonlyArray<{
478 readonly path: string;
479 readonly kind: "file" | "directory";
480 }>;
481 readonly watchFailures?: number;
482 } = {},
483) {
484 const watchers: Array<(events: ReadonlyArray<WatchEvent>) => void> = [];
485 let watchFailures = options.watchFailures ?? 0;
486 // fff's pageIndex is an offset into the results, not a page number.
487 const directorySearch = vi.fn(
488 async (_query: string, searchOptions?: { pageIndex?: number; pageSize?: number }) => {
489 const offset = searchOptions?.pageIndex ?? 0;
490 const items = directories.slice(offset, offset + (searchOptions?.pageSize ?? 100));
491 return {
492 ok: true as const,
493 value: {
494 items: items.map((relativePath) => ({ relativePath })),
495 totalMatched: directories.length,
496 },
497 };
498 },
499 );
500 const indexedItems = (options.indexed ?? []).map((entry) => ({
501 type: entry.kind,
502 item: { relativePath: entry.path, fileName: entry.path.split("/").at(-1) },
503 }));
504 const finder = {
505 destroy: vi.fn(),
506 waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })),
507 // fff's isScanning waits on the picker lock on the JS thread.
508 isScanning: () => {
509 throw new Error("isScanning must not run on the JS thread");
510 },
511 getScanProgressAsync: async () => ({
512 ok: true as const,
513 value: { isScanning: false },
514 }),
515 // fff's watch waits on the picker lock on the JS thread.
516 watch: () => {
517 throw new Error("watch must not run on the JS thread");
518 },
519 watchAsync: async (callback: (events: ReadonlyArray<WatchEvent>) => void) => {
520 if (watchFailures > 0) {
521 watchFailures -= 1;
522 return { ok: false as const, error: "File system watcher is not ready" };
523 }
524 watchers.push(callback);
525 return { ok: true as const, value: () => undefined };
526 },
527 directorySearchAsync: directorySearch,
528 fileSearchAsync: async () => {
529 const items = indexedItems.flatMap((entry) => (entry.type === "file" ? [entry.item] : []));
530 return { ok: true as const, value: { items, scores: [], totalMatched: items.length } };
531 },
532 mixedSearchAsync: async () => ({
533 ok: true as const,
534 value: { items: indexedItems, totalMatched: indexedItems.length },
535 }),
536 } as unknown as FileFinder;
537 vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder });
538 return {
539 directorySearch,
540 notifyWatchers: (events: ReadonlyArray<WatchEvent>) =>
541 watchers.forEach((watcher) => watcher(events)),
542 };
543}
544
545const listedPaths = (searchIndex: WorkspaceSearchIndex.WorkspaceSearchIndex["Service"]) =>
546 searchIndex.list().pipe(Effect.map((result) => result.entries.map((entry) => entry.path)));
547
548it.effect("reads symlinks again after the watcher reports a change", () =>
549 Effect.scoped(
550 Effect.gen(function* () {
551 if ((yield* HostProcess.Platform) === "win32") return;
552 const fileSystem = yield* FileSystem.FileSystem;
553 const path = yield* Path.Path;
554 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-symlink-watch-" });
555 const outside = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-outside-" });
556 yield* fileSystem.writeFileString(path.join(cwd, "a.ts"), "");
557 yield* fileSystem.symlink("a.ts", path.join(cwd, "old-link.ts"));
558 const { directorySearch, notifyWatchers } = fakeSymlinkFinder([]);
559
560 const searchIndex = yield* WorkspaceSearchIndex.make(cwd);
561 const concurrent = yield* Effect.all(
562 Array.from({ length: 8 }, () => listedPaths(searchIndex)),
563 { concurrency: "unbounded" },
564 );
565 yield* fileSystem.remove(path.join(cwd, "old-link.ts"));
566 yield* fileSystem.symlink("a.ts", path.join(cwd, "new-link.ts"));
567 const beforeNotice = yield* listedPaths(searchIndex);
568 // Editing a file cannot move a link, so it does not cost a rescan.
569 notifyWatchers([{ kind: "modified", path: path.join(cwd, "a.ts") }]);
570 const afterEdit = yield* listedPaths(searchIndex);
571 notifyWatchers([{ kind: "created", path: path.join(cwd, "new-link.ts") }]);
572 const afterNotice = yield* listedPaths(searchIndex);
573 // fff reports a link replaced in place as modified.
574 yield* fileSystem.remove(path.join(cwd, "new-link.ts"));
575 yield* fileSystem.symlink(outside, path.join(cwd, "new-link.ts"));
576 notifyWatchers([{ kind: "modified", path: path.join(cwd, "new-link.ts") }]);
577 const afterReplace = yield* listedPaths(searchIndex);
578
579 expect(concurrent).toEqual(Array.from({ length: 8 }, () => ["old-link.ts"]));
580 expect(beforeNotice).toEqual(["old-link.ts"]);
581 expect(afterEdit).toEqual(["old-link.ts"]);
582 expect(afterNotice).toEqual(["new-link.ts"]);
583 expect(afterReplace).toEqual([]);
584 expect(directorySearch).toHaveBeenCalledTimes(3);
585 }),
586 ).pipe(Effect.provide(testLayer)),
587);
588
589it.effect("answers from the last symlink scan while a slow rescan runs", () =>
590 Effect.scoped(
591 Effect.gen(function* () {
592 if ((yield* HostProcess.Platform) === "win32") return;
593 const fileSystem = yield* FileSystem.FileSystem;
594 const path = yield* Path.Path;
595 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-symlink-stale-" });
596 yield* fileSystem.writeFileString(path.join(cwd, "a.ts"), "");
597 yield* fileSystem.symlink("a.ts", path.join(cwd, "old-link.ts"));
598 const { notifyWatchers } = fakeSymlinkFinder([]);
599 // Holding git's ignore check open keeps the rescan from finishing.
600 const gate = yield* Deferred.make<void>();
601 let holdIgnoreChecks = false;
602 const vcsProcess = yield* VcsProcess.VcsProcess;
603 const searchIndex = yield* WorkspaceSearchIndex.make(cwd).pipe(
604 Effect.provideService(VcsProcess.VcsProcess, {
605 ...vcsProcess,
606 run: (input) =>
607 holdIgnoreChecks && input.operation === "WorkspaceSearchIndex.listGitIgnored"
608 ? Deferred.await(gate).pipe(Effect.andThen(vcsProcess.run(input)))
609 : vcsProcess.run(input),
610 }),
611 );
612 expect(yield* listedPaths(searchIndex)).toEqual(["old-link.ts"]);
613
614 holdIgnoreChecks = true;
615 yield* fileSystem.symlink("a.ts", path.join(cwd, "new-link.ts"));
616 notifyWatchers([{ kind: "created", path: path.join(cwd, "new-link.ts") }]);
617 const duringRescan = yield* Effect.forkChild(listedPaths(searchIndex));
618 yield* TestClock.adjust("1 second");
619 expect(yield* Fiber.join(duringRescan)).toEqual(["old-link.ts"]);
620
621 yield* Deferred.succeed(gate, undefined);
622 expect(yield* listedPaths(searchIndex)).toEqual(["new-link.ts", "old-link.ts"]);
623 }),
624 ).pipe(Effect.provide(testLayer)),
625);
626
627it.effect("keeps symlinks once the watcher subscribes after starting late", () =>
628 Effect.scoped(
629 Effect.gen(function* () {
630 if ((yield* HostProcess.Platform) === "win32") return;
631 const fileSystem = yield* FileSystem.FileSystem;
632 const path = yield* Path.Path;
633 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-symlink-watch-" });
634 yield* fileSystem.writeFileString(path.join(cwd, "a.ts"), "");
635 yield* fileSystem.symlink("a.ts", path.join(cwd, "link.ts"));
636 const { directorySearch } = fakeSymlinkFinder([], { watchFailures: 2 });
637
638 const searchIndex = yield* WorkspaceSearchIndex.make(cwd);
639 const scansAfterRound: number[] = [];
640 for (let round = 0; round < 5; round += 1) {
641 expect(yield* listedPaths(searchIndex)).toEqual(["link.ts"]);
642 expect(yield* listedPaths(searchIndex)).toEqual(["link.ts"]);
643 scansAfterRound.push(directorySearch.mock.calls.length);
644 yield* TestClock.adjust("1 minute");
645 }
646
647 // An unwatched scan serves reads only briefly; the third has a watcher and is kept.
648 expect(scansAfterRound).toEqual([1, 2, 3, 3, 3]);
649 }),
650 ).pipe(Effect.provide(testLayer)),
651);
652
653it.effect(
654 "lists a symlink the watcher indexed once, with the link's kind, and drops rejected ones",
655 () =>
656 Effect.scoped(
657 Effect.gen(function* () {
658 if ((yield* HostProcess.Platform) === "win32") return;
659 const fileSystem = yield* FileSystem.FileSystem;
660 const path = yield* Path.Path;
661 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-symlink-dupe-" });
662 const outside = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-outside-" });
663 yield* fileSystem.makeDirectory(path.join(cwd, "src"));
664 yield* fileSystem.symlink("src", path.join(cwd, "src-link"));
665 // A link the scan rejects stays out even when the watcher indexed it.
666 yield* fileSystem.symlink(outside, path.join(cwd, "outside-link"));
667 fakeSymlinkFinder([], {
668 indexed: [
669 { path: "outside-link", kind: "file" },
670 { path: "src-link", kind: "file" },
671 { path: "link-file.ts", kind: "file" },
672 ],
673 });
674
675 const searchIndex = yield* WorkspaceSearchIndex.make(cwd);
676 const searched = yield* searchIndex.search("link", 10);
677 const files = yield* searchIndex.search("link", 1, "file");
678 const listed = yield* searchIndex.list();
679
680 expect(searched.entries).toEqual([
681 { path: "src-link", kind: "directory" },
682 { path: "link-file.ts", kind: "file" },
683 ]);
684 // The dropped link does not take the only slot.
685 expect(files).toEqual({
686 entries: [{ path: "link-file.ts", kind: "file" }],
687 truncated: false,
688 });
689 expect(listed.entries).toEqual([
690 { path: "link-file.ts", kind: "file" },
691 { path: "src-link", kind: "directory" },
692 ]);
693 }),
694 ).pipe(Effect.provide(testLayer)),
695);
696
697it.effect("finds symlinks in folders past the first page of the index", () =>
698 Effect.scoped(
699 Effect.gen(function* () {
700 if ((yield* HostProcess.Platform) === "win32") return;
701 const fileSystem = yield* FileSystem.FileSystem;
702 const path = yield* Path.Path;
703 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-symlink-pages-" });
704 yield* fileSystem.makeDirectory(path.join(cwd, "late"));
705 yield* fileSystem.writeFileString(path.join(cwd, "late/a.ts"), "");
706 yield* fileSystem.symlink("a.ts", path.join(cwd, "late/link.ts"));
707 // Folders fff lists but that are gone by the time they are read are skipped.
708 const firstPage = Array.from({ length: 1_000 }, (_, index) => `missing-${index}`);
709 const { directorySearch } = fakeSymlinkFinder([...firstPage, "late"]);
710
711 const searchIndex = yield* WorkspaceSearchIndex.make(cwd);
712
713 expect(yield* listedPaths(searchIndex)).toEqual(["late", "late/link.ts"]);
714 expect(directorySearch.mock.calls.map(([, options]) => options?.pageIndex)).toEqual([
715 0, 1_000,
716 ]);
717 }),
718 ).pipe(Effect.provide(testLayer)),
719);
720
721// fff reads HOME on Linux and macOS but the user profile on Windows, so a temp HOME cannot stand in there.
722it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
723 "refuses to index a workspace rooted at the home directory",
724 () =>
725 Effect.scoped(
726 Effect.gen(function* () {
727 const fs = yield* FileSystem.FileSystem;
728 const path = yield* Path.Path;
729 const home = yield* fs.realPath(
730 yield* fs.makeTempDirectoryScoped({ prefix: "t3-search-home-" }),
731 );
732 yield* fs.makeDirectory(path.join(home, "OneDrive", "Remix"), { recursive: true });
733 yield* fs.writeFileString(path.join(home, "OneDrive", "Remix", "part.stl"), "solid part\n");
734 yield* Effect.acquireRelease(
735 Effect.sync(() => vi.stubEnv("HOME", home)),
736 () => Effect.sync(() => vi.unstubAllEnvs()),
737 );
738
739 const result = yield* WorkspaceSearchIndex.make(home).pipe(
740 Effect.flatMap((searchIndex) => searchIndex.search("stl", 50, undefined, false)),
741 Effect.map(({ entries }) => entries),
742 Effect.catchTags({
743 WorkspaceSearchIndexCreateFailed: (error) => Effect.succeed(error._tag),
744 }),
745 );
746
747 expect(result).toBe("WorkspaceSearchIndexCreateFailed");
748 }),
749 ).pipe(Effect.provide(testLayer)),
750);