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[0]?.[0]).toBe(String.raw`(?-u)\bneedle\b`);
294 expect(grep.mock.calls[0]?.[1]?.mode).toBe("regex");
295 expect(grep.mock.calls[1]?.[1]?.cursor).toBe(nextCursor);
296 }),
297 ).pipe(Effect.provide(testLayer)),
298);
299
300it.live("answers content searches with git grep while a slow content index builds", () =>
301 Effect.gen(function* () {
302 const fileSystem = yield* FileSystem.FileSystem;
303 const path = yield* Path.Path;
304 const vcsProcess = yield* VcsProcess.VcsProcess;
305 const repoRoot = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-content-warmup-" });
306 yield* vcsProcess.run({
307 operation: "test.gitInit",
308 command: "git",
309 args: ["init"],
310 cwd: repoRoot,
311 });
312 // User git config must not change git grep's records or make it refuse --untracked.
313 for (const setting of ["grep.column", "grep.fullName", "submodule.recurse"]) {
314 yield* vcsProcess.run({
315 operation: "test.gitConfig",
316 command: "git",
317 args: ["config", setting, "true"],
318 cwd: repoRoot,
319 });
320 }
321 const cwd = path.join(repoRoot, "project");
322 yield* fileSystem.makeDirectory(cwd);
323 yield* fileSystem.writeFileString(path.join(cwd, ".gitignore"), "ignored.txt\n");
324 yield* fileSystem.makeDirectory(path.join(cwd, "src"));
325 yield* fileSystem.writeFileString(
326 path.join(cwd, "src/a.ts"),
327 "const Needle = 1;\r\nneedles(a.b);\nnone\n",
328 );
329 yield* fileSystem.writeFileString(path.join(cwd, "ignored.txt"), "needle\n");
330 // fff leaves out what `.ignore` excludes, so git results must leave it out too.
331 yield* fileSystem.writeFileString(path.join(cwd, ".ignore"), "out/\n");
332 yield* fileSystem.makeDirectory(path.join(cwd, "out/deep"), { recursive: true });
333 yield* fileSystem.writeFileString(path.join(cwd, "out/deep/g.txt"), "needle\n");
334
335 let isWarmupComplete = false;
336 const grep = vi.fn(async () => ({
337 ok: true as const,
338 value: {
339 items: [],
340 totalMatched: 0,
341 totalFilesSearched: 0,
342 totalFiles: 0,
343 filteredFileCount: 0,
344 nextCursor: null,
345 } satisfies GrepResult,
346 }));
347 const finder = {
348 destroy: vi.fn(),
349 waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: false })),
350 getScanProgressAsync: async () => ({
351 ok: true as const,
352 value: { isScanning: false, isWarmupComplete },
353 }),
354 watchAsync: async () => ({ ok: true as const, value: () => undefined }),
355 grepAsync: grep,
356 } as unknown as FileFinder;
357 const noPcreFinder = {
358 ...finder,
359 waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })),
360 } as unknown as FileFinder;
361 vi.spyOn(FileFinder, "create")
362 .mockReturnValueOnce({ ok: true, value: finder })
363 .mockReturnValueOnce({ ok: true, value: noPcreFinder })
364 .mockReturnValueOnce({ ok: true, value: noPcreFinder })
365 .mockReturnValueOnce({ ok: true, value: noPcreFinder });
366
367 const searchIndex = yield* WorkspaceSearchIndex.make(cwd, "content");
368 const search = (input: Partial<Parameters<typeof searchIndex.searchContents>[0]>) =>
369 searchIndex.searchContents({
370 query: "needle",
371 limit: 10,
372 caseSensitive: false,
373 wholeWord: false,
374 useRegex: false,
375 ...input,
376 });
377
378 expect(yield* search({})).toEqual({
379 matches: [
380 {
381 path: "src/a.ts",
382 lineNumber: 1,
383 lineContent: "const Needle = 1;",
384 matchRanges: [{ start: 6, end: 12 }],
385 },
386 {
387 path: "src/a.ts",
388 lineNumber: 2,
389 lineContent: "needles(a.b);",
390 matchRanges: [{ start: 0, end: 6 }],
391 },
392 ],
393 truncated: false,
394 });
395 expect((yield* search({ caseSensitive: true, wholeWord: true })).matches).toEqual([]);
396 expect((yield* search({ query: "a.b" })).matches.map((match) => match.matchRanges)).toEqual([
397 [{ start: 8, end: 11 }],
398 ]);
399 expect(
400 (yield* search({ query: "ne+dles?", useRegex: true })).matches.map(
401 (match) => match.matchRanges,
402 ),
403 ).toEqual([[{ start: 6, end: 12 }], [{ start: 0, end: 7 }]]);
404 expect(
405 (yield* search({ query: "[a-z]e", useRegex: true })).matches.map(
406 (match) => match.matchRanges,
407 ),
408 ).toEqual([
409 [{ start: 4, end: 6 }],
410 [
411 { start: 6, end: 8 },
412 { start: 10, end: 12 },
413 ],
414 [
415 { start: 0, end: 2 },
416 { start: 4, end: 6 },
417 ],
418 [{ start: 2, end: 4 }],
419 ]);
420 const invalid = yield* search({ query: "a.b(", useRegex: true });
421 expect(invalid.matches).toEqual([]);
422 expect(invalid.regexFallbackError).toBeDefined();
423 expect(yield* search({ limit: 1 })).toMatchObject({ truncated: true });
424 expect(grep).not.toHaveBeenCalled();
425
426 // When git cannot give regex results or their ranges, fff answers once ready instead.
427 const failingGitIndex = (
428 failingArgument: string,
429 stderr: string,
430 output: { readonly exitCode: number; readonly stdout: string } = {
431 exitCode: 128,
432 stdout: "",
433 },
434 ) =>
435 WorkspaceSearchIndex.make(cwd, "content").pipe(
436 Effect.provideService(
437 VcsProcess.VcsProcess,
438 VcsProcess.VcsProcess.of({
439 run: (input) =>
440 input.args.includes(failingArgument)
441 ? Effect.succeed({
442 exitCode: ChildProcessSpawner.ExitCode(output.exitCode),
443 stdout: output.stdout,
444 stderr,
445 stdoutTruncated: output.exitCode === 0,
446 stderrTruncated: false,
447 })
448 : vcsProcess.run(input),
449 }),
450 ),
451 );
452 const regexInput = {
453 query: "ne+dles?",
454 limit: 10,
455 caseSensitive: false,
456 wholeWord: true,
457 useRegex: true,
458 };
459 const noPcreIndex = yield* failingGitIndex(
460 "-P",
461 "fatal: cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE\n",
462 );
463 expect((yield* noPcreIndex.searchContents(regexInput)).regexFallbackError).toBeUndefined();
464 expect(grep).toHaveBeenCalledTimes(1);
465 const noRangesIndex = yield* failingGitIndex("-o", "fatal: unexpected failure\n");
466 yield* noRangesIndex.searchContents(regexInput);
467 expect(grep).toHaveBeenCalledTimes(2);
468 // Ranges output cut off after line 1: line 2 is left out and the result says so.
469 const cutRangesIndex = yield* failingGitIndex("-o", "", {
470 exitCode: 0,
471 stdout: "src/a.ts\u00001\u00007\u0000Needle\nsrc/a.ts\u00002",
472 });
473 expect(yield* cutRangesIndex.searchContents(regexInput)).toEqual({
474 matches: [
475 {
476 path: "src/a.ts",
477 lineNumber: 1,
478 lineContent: "const Needle = 1;",
479 matchRanges: [{ start: 6, end: 12 }],
480 },
481 ],
482 truncated: true,
483 });
484
485 isWarmupComplete = true;
486 yield* search({});
487 expect(grep).toHaveBeenCalledTimes(3);
488 expect(finder.destroy).not.toHaveBeenCalled();
489 }).pipe(Effect.scoped, Effect.provide(testLayer)),
490);
491
492function fakeSymlinkFinder(
493 directories: ReadonlyArray<string>,
494 options: {
495 readonly indexed?: ReadonlyArray<{
496 readonly path: string;
497 readonly kind: "file" | "directory";
498 }>;
499 readonly watchFailures?: number;
500 } = {},
501) {
502 const watchers: Array<(events: ReadonlyArray<WatchEvent>) => void> = [];
503 let watchFailures = options.watchFailures ?? 0;
504 // fff's pageIndex is an offset into the results, not a page number.
505 const directorySearch = vi.fn(
506 async (_query: string, searchOptions?: { pageIndex?: number; pageSize?: number }) => {
507 const offset = searchOptions?.pageIndex ?? 0;
508 const items = directories.slice(offset, offset + (searchOptions?.pageSize ?? 100));
509 return {
510 ok: true as const,
511 value: {
512 items: items.map((relativePath) => ({ relativePath })),
513 totalMatched: directories.length,
514 },
515 };
516 },
517 );
518 const indexedItems = (options.indexed ?? []).map((entry) => ({
519 type: entry.kind,
520 item: { relativePath: entry.path, fileName: entry.path.split("/").at(-1) },
521 }));
522 const finder = {
523 destroy: vi.fn(),
524 waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })),
525 // fff's isScanning waits on the picker lock on the JS thread.
526 isScanning: () => {
527 throw new Error("isScanning must not run on the JS thread");
528 },
529 getScanProgressAsync: async () => ({
530 ok: true as const,
531 value: { isScanning: false },
532 }),
533 // fff's watch waits on the picker lock on the JS thread.
534 watch: () => {
535 throw new Error("watch must not run on the JS thread");
536 },
537 watchAsync: async (callback: (events: ReadonlyArray<WatchEvent>) => void) => {
538 if (watchFailures > 0) {
539 watchFailures -= 1;
540 return { ok: false as const, error: "File system watcher is not ready" };
541 }
542 watchers.push(callback);
543 return { ok: true as const, value: () => undefined };
544 },
545 directorySearchAsync: directorySearch,
546 fileSearchAsync: async () => {
547 const items = indexedItems.flatMap((entry) => (entry.type === "file" ? [entry.item] : []));
548 return { ok: true as const, value: { items, scores: [], totalMatched: items.length } };
549 },
550 mixedSearchAsync: async () => ({
551 ok: true as const,
552 value: { items: indexedItems, totalMatched: indexedItems.length },
553 }),
554 } as unknown as FileFinder;
555 vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder });
556 return {
557 directorySearch,
558 notifyWatchers: (events: ReadonlyArray<WatchEvent>) =>
559 watchers.forEach((watcher) => watcher(events)),
560 };
561}
562
563const listedPaths = (searchIndex: WorkspaceSearchIndex.WorkspaceSearchIndex["Service"]) =>
564 searchIndex.list().pipe(Effect.map((result) => result.entries.map((entry) => entry.path)));
565
566it.effect("reads symlinks again after the watcher reports a change", () =>
567 Effect.scoped(
568 Effect.gen(function* () {
569 if ((yield* HostProcess.Platform) === "win32") return;
570 const fileSystem = yield* FileSystem.FileSystem;
571 const path = yield* Path.Path;
572 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-symlink-watch-" });
573 const outside = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-outside-" });
574 yield* fileSystem.writeFileString(path.join(cwd, "a.ts"), "");
575 yield* fileSystem.symlink("a.ts", path.join(cwd, "old-link.ts"));
576 const { directorySearch, notifyWatchers } = fakeSymlinkFinder([]);
577
578 const searchIndex = yield* WorkspaceSearchIndex.make(cwd);
579 const concurrent = yield* Effect.all(
580 Array.from({ length: 8 }, () => listedPaths(searchIndex)),
581 { concurrency: "unbounded" },
582 );
583 yield* fileSystem.remove(path.join(cwd, "old-link.ts"));
584 yield* fileSystem.symlink("a.ts", path.join(cwd, "new-link.ts"));
585 const beforeNotice = yield* listedPaths(searchIndex);
586 // Editing a file cannot move a link, so it does not cost a rescan.
587 notifyWatchers([{ kind: "modified", path: path.join(cwd, "a.ts") }]);
588 const afterEdit = yield* listedPaths(searchIndex);
589 notifyWatchers([{ kind: "created", path: path.join(cwd, "new-link.ts") }]);
590 const afterNotice = yield* listedPaths(searchIndex);
591 // fff reports a link replaced in place as modified.
592 yield* fileSystem.remove(path.join(cwd, "new-link.ts"));
593 yield* fileSystem.symlink(outside, path.join(cwd, "new-link.ts"));
594 notifyWatchers([{ kind: "modified", path: path.join(cwd, "new-link.ts") }]);
595 const afterReplace = yield* listedPaths(searchIndex);
596
597 expect(concurrent).toEqual(Array.from({ length: 8 }, () => ["old-link.ts"]));
598 expect(beforeNotice).toEqual(["old-link.ts"]);
599 expect(afterEdit).toEqual(["old-link.ts"]);
600 expect(afterNotice).toEqual(["new-link.ts"]);
601 expect(afterReplace).toEqual([]);
602 expect(directorySearch).toHaveBeenCalledTimes(3);
603 }),
604 ).pipe(Effect.provide(testLayer)),
605);
606
607it.effect("answers from the last symlink scan while a slow rescan runs", () =>
608 Effect.scoped(
609 Effect.gen(function* () {
610 if ((yield* HostProcess.Platform) === "win32") return;
611 const fileSystem = yield* FileSystem.FileSystem;
612 const path = yield* Path.Path;
613 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-symlink-stale-" });
614 yield* fileSystem.writeFileString(path.join(cwd, "a.ts"), "");
615 yield* fileSystem.symlink("a.ts", path.join(cwd, "old-link.ts"));
616 const { notifyWatchers } = fakeSymlinkFinder([]);
617 // Holding git's ignore check open keeps the rescan from finishing.
618 const gate = yield* Deferred.make<void>();
619 let holdIgnoreChecks = false;
620 const vcsProcess = yield* VcsProcess.VcsProcess;
621 const searchIndex = yield* WorkspaceSearchIndex.make(cwd).pipe(
622 Effect.provideService(VcsProcess.VcsProcess, {
623 ...vcsProcess,
624 run: (input) =>
625 holdIgnoreChecks && input.operation === "WorkspaceSearchIndex.listGitIgnored"
626 ? Deferred.await(gate).pipe(Effect.andThen(vcsProcess.run(input)))
627 : vcsProcess.run(input),
628 }),
629 );
630 expect(yield* listedPaths(searchIndex)).toEqual(["old-link.ts"]);
631
632 holdIgnoreChecks = true;
633 yield* fileSystem.symlink("a.ts", path.join(cwd, "new-link.ts"));
634 notifyWatchers([{ kind: "created", path: path.join(cwd, "new-link.ts") }]);
635 const duringRescan = yield* Effect.forkChild(listedPaths(searchIndex));
636 yield* TestClock.adjust("1 second");
637 expect(yield* Fiber.join(duringRescan)).toEqual(["old-link.ts"]);
638
639 yield* Deferred.succeed(gate, undefined);
640 expect(yield* listedPaths(searchIndex)).toEqual(["new-link.ts", "old-link.ts"]);
641 }),
642 ).pipe(Effect.provide(testLayer)),
643);
644
645it.effect("keeps symlinks once the watcher subscribes after starting late", () =>
646 Effect.scoped(
647 Effect.gen(function* () {
648 if ((yield* HostProcess.Platform) === "win32") return;
649 const fileSystem = yield* FileSystem.FileSystem;
650 const path = yield* Path.Path;
651 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-symlink-watch-" });
652 yield* fileSystem.writeFileString(path.join(cwd, "a.ts"), "");
653 yield* fileSystem.symlink("a.ts", path.join(cwd, "link.ts"));
654 const { directorySearch } = fakeSymlinkFinder([], { watchFailures: 2 });
655
656 const searchIndex = yield* WorkspaceSearchIndex.make(cwd);
657 const scansAfterRound: number[] = [];
658 for (let round = 0; round < 5; round += 1) {
659 expect(yield* listedPaths(searchIndex)).toEqual(["link.ts"]);
660 expect(yield* listedPaths(searchIndex)).toEqual(["link.ts"]);
661 scansAfterRound.push(directorySearch.mock.calls.length);
662 yield* TestClock.adjust("1 minute");
663 }
664
665 // An unwatched scan serves reads only briefly; the third has a watcher and is kept.
666 expect(scansAfterRound).toEqual([1, 2, 3, 3, 3]);
667 }),
668 ).pipe(Effect.provide(testLayer)),
669);
670
671it.effect(
672 "lists a symlink the watcher indexed once, with the link's kind, and drops rejected ones",
673 () =>
674 Effect.scoped(
675 Effect.gen(function* () {
676 if ((yield* HostProcess.Platform) === "win32") return;
677 const fileSystem = yield* FileSystem.FileSystem;
678 const path = yield* Path.Path;
679 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-symlink-dupe-" });
680 const outside = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-outside-" });
681 yield* fileSystem.makeDirectory(path.join(cwd, "src"));
682 yield* fileSystem.symlink("src", path.join(cwd, "src-link"));
683 // A link the scan rejects stays out even when the watcher indexed it.
684 yield* fileSystem.symlink(outside, path.join(cwd, "outside-link"));
685 fakeSymlinkFinder([], {
686 indexed: [
687 { path: "outside-link", kind: "file" },
688 { path: "src-link", kind: "file" },
689 { path: "link-file.ts", kind: "file" },
690 ],
691 });
692
693 const searchIndex = yield* WorkspaceSearchIndex.make(cwd);
694 const searched = yield* searchIndex.search("link", 10);
695 const files = yield* searchIndex.search("link", 1, "file");
696 const listed = yield* searchIndex.list();
697
698 expect(searched.entries).toEqual([
699 { path: "src-link", kind: "directory" },
700 { path: "link-file.ts", kind: "file" },
701 ]);
702 // The dropped link does not take the only slot.
703 expect(files).toEqual({
704 entries: [{ path: "link-file.ts", kind: "file" }],
705 truncated: false,
706 });
707 expect(listed.entries).toEqual([
708 { path: "link-file.ts", kind: "file" },
709 { path: "src-link", kind: "directory" },
710 ]);
711 }),
712 ).pipe(Effect.provide(testLayer)),
713);
714
715it.effect("finds symlinks in folders past the first page of the index", () =>
716 Effect.scoped(
717 Effect.gen(function* () {
718 if ((yield* HostProcess.Platform) === "win32") return;
719 const fileSystem = yield* FileSystem.FileSystem;
720 const path = yield* Path.Path;
721 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-symlink-pages-" });
722 yield* fileSystem.makeDirectory(path.join(cwd, "late"));
723 yield* fileSystem.writeFileString(path.join(cwd, "late/a.ts"), "");
724 yield* fileSystem.symlink("a.ts", path.join(cwd, "late/link.ts"));
725 // Folders fff lists but that are gone by the time they are read are skipped.
726 const firstPage = Array.from({ length: 1_000 }, (_, index) => `missing-${index}`);
727 const { directorySearch } = fakeSymlinkFinder([...firstPage, "late"]);
728
729 const searchIndex = yield* WorkspaceSearchIndex.make(cwd);
730
731 expect(yield* listedPaths(searchIndex)).toEqual(["late", "late/link.ts"]);
732 expect(directorySearch.mock.calls.map(([, options]) => options?.pageIndex)).toEqual([
733 0, 1_000,
734 ]);
735 }),
736 ).pipe(Effect.provide(testLayer)),
737);
738
739it.effect("keeps symlinks Git does not ignore when a link's name looks like a git pathspec", () =>
740 Effect.scoped(
741 Effect.gen(function* () {
742 if ((yield* HostProcess.Platform) === "win32") return;
743 const fileSystem = yield* FileSystem.FileSystem;
744 const path = yield* Path.Path;
745 const vcsProcess = yield* VcsProcess.VcsProcess;
746 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-symlink-pathspec-" });
747 yield* vcsProcess.run({ operation: "test.gitInit", command: "git", args: ["init"], cwd });
748 yield* fileSystem.writeFileString(path.join(cwd, ".gitignore"), "ignored-link\n");
749 yield* fileSystem.writeFileString(path.join(cwd, "a.ts"), "");
750 yield* fileSystem.symlink("a.ts", path.join(cwd, "docs-link"));
751 yield* fileSystem.symlink("a.ts", path.join(cwd, ":(link)"));
752 yield* fileSystem.symlink("a.ts", path.join(cwd, "ignored-link"));
753 // Stage so `ls-files --others` skips it and `listGitIgnored` must hide it.
754 yield* vcsProcess.run({
755 operation: "test.gitAdd",
756 command: "git",
757 args: ["add", "-f", "ignored-link"],
758 cwd,
759 });
760 fakeSymlinkFinder([]);
761
762 const searchIndex = yield* WorkspaceSearchIndex.make(cwd);
763
764 expect(yield* listedPaths(searchIndex)).toEqual([":(link)", "docs-link"]);
765 }),
766 ).pipe(Effect.provide(testLayer)),
767);
768
769// fff reads HOME on Linux and macOS but the user profile on Windows, so a temp HOME cannot stand in there.
770it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
771 "refuses to index a workspace rooted at the home directory",
772 () =>
773 Effect.scoped(
774 Effect.gen(function* () {
775 const fs = yield* FileSystem.FileSystem;
776 const path = yield* Path.Path;
777 const home = yield* fs.realPath(
778 yield* fs.makeTempDirectoryScoped({ prefix: "t3-search-home-" }),
779 );
780 yield* fs.makeDirectory(path.join(home, "OneDrive", "Remix"), { recursive: true });
781 yield* fs.writeFileString(path.join(home, "OneDrive", "Remix", "part.stl"), "solid part\n");
782 yield* Effect.acquireRelease(
783 Effect.sync(() => vi.stubEnv("HOME", home)),
784 () => Effect.sync(() => vi.unstubAllEnvs()),
785 );
786
787 const result = yield* WorkspaceSearchIndex.make(home).pipe(
788 Effect.flatMap((searchIndex) => searchIndex.search("stl", 50, undefined, false)),
789 Effect.map(({ entries }) => entries),
790 Effect.catchTags({
791 WorkspaceSearchIndexCreateFailed: (error) => Effect.succeed(error._tag),
792 }),
793 );
794
795 expect(result).toBe("WorkspaceSearchIndexCreateFailed");
796 }),
797 ).pipe(Effect.provide(testLayer)),
798);
799
800// ripgrep and fff let a matching `.ignore` decide ahead of `.gitignore`, so Git's list must not hide it.
801it.live("finds Git-ignored files that a root .ignore re-includes", () =>
802 Effect.gen(function* () {
803 const fileSystem = yield* FileSystem.FileSystem;
804 const path = yield* Path.Path;
805 const vcsProcess = yield* VcsProcess.VcsProcess;
806 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-search-reinclude-" });
807 yield* vcsProcess.run({ operation: "test.gitInit", command: "git", args: ["init"], cwd });
808 yield* fileSystem.writeFileString(path.join(cwd, ".gitignore"), "notes/\n");
809 yield* fileSystem.writeFileString(
810 path.join(cwd, ".ignore"),
811 "!notes/\nnotes/**/*\n!notes/**/\n!notes/**/*.md\n",
812 );
813 yield* fileSystem.makeDirectory(path.join(cwd, "notes", "daily"), { recursive: true });
814 yield* fileSystem.writeFileString(path.join(cwd, "notes", "daily", "standup.md"), "");
815 yield* fileSystem.writeFileString(path.join(cwd, "notes", "daily", "standup.txt"), "");
816
817 const searchIndex = yield* WorkspaceSearchIndex.make(cwd);
818 const result = yield* searchIndex.search("standup", 50, "file");
819
820 expect(result.entries).toEqual([{ kind: "file", path: "notes/daily/standup.md" }]);
821 }).pipe(Effect.scoped, Effect.provide(testLayer)),
822);
823
824// Real fff: the native whole-word pattern must return what the plain search and the JS word check did.
825it.live.each([
826 { query: "needle", caseSensitive: true, expected: ["notes.md:1:0-6", "words.ts:2:0-6,8-14"] },
827 { query: "NEEDLE", caseSensitive: false, expected: ["notes.md:1:0-6", "words.ts:2:0-6,8-14"] },
828 // fff reads `*.ts` as a file constraint, which a regex built around the whole query would lose.
829 { query: "*.ts needle", caseSensitive: true, expected: ["words.ts:2:0-6,8-14"] },
830 // Plain search folds ASCII case only: `ſ` is not an `s`, and the Kelvin sign is not a `k`.
831 { query: "s", caseSensitive: false, expected: ["fold.txt:2:0-1"] },
832 { query: "k", caseSensitive: false, expected: ["fold.txt:4:0-1"] },
833])("matches whole words in a real workspace for $query", ({ query, caseSensitive, expected }) =>
834 Effect.gen(function* () {
835 const fileSystem = yield* FileSystem.FileSystem;
836 const path = yield* Path.Path;
837 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-search-whole-word-" });
838 yield* fileSystem.writeFileString(
839 path.join(cwd, "words.ts"),
840 "needleSuffix\nneedle, needle.\n\u00e9needle\n",
841 );
842 yield* fileSystem.writeFileString(path.join(cwd, "notes.md"), "needle *.ts\n");
843 yield* fileSystem.writeFileString(path.join(cwd, "fold.txt"), "\u017f\ns\n\u212a\nk\n");
844
845 const searchIndex = yield* WorkspaceSearchIndex.make(cwd, "content");
846 const result = yield* searchIndex.searchContents({
847 query,
848 limit: 500,
849 caseSensitive,
850 wholeWord: true,
851 useRegex: false,
852 });
853
854 expect(
855 result.matches
856 .map(
857 (match) =>
858 `${match.path}:${match.lineNumber}:${match.matchRanges.map((range) => `${range.start}-${range.end}`).join(",")}`,
859 )
860 .toSorted(),
861 ).toEqual(expected);
862 }).pipe(Effect.scoped, Effect.provide(testLayer)),
863);