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

WorkspaceSearchIndex.test.ts

1,030 lines40.3 KB

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 };
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 .mockReturnValueOnce({ ok: true, value: noPcreFinder });
367​
368 const searchIndex = yield* WorkspaceSearchIndex.make(cwd, "content");
369 const search = (input: Partial<Parameters<typeof searchIndex.searchContents>[0]>) =>
370 searchIndex.searchContents({
371 query: "needle",
372 limit: 10,
373 caseSensitive: false,
374 wholeWord: false,
375 useRegex: false,
376 ...input,
377 });
378​
379 expect(yield* search({})).toEqual({
380 matches: [
381 {
382 path: "src/a.ts",
383 lineNumber: 1,
384 lineContent: "const Needle = 1;",
385 matchRanges: [{ start: 6, end: 12 }],
386 },
387 {
388 path: "src/a.ts",
389 lineNumber: 2,
390 lineContent: "needles(a.b);",
391 matchRanges: [{ start: 0, end: 6 }],
392 },
393 ],
394 truncated: false,
395 });
396 expect((yield* search({ caseSensitive: true, wholeWord: true })).matches).toEqual([]);
397 expect((yield* search({ query: "a.b" })).matches.map((match) => match.matchRanges)).toEqual([
398 [{ start: 8, end: 11 }],
399 ]);
400 expect(
401 (yield* search({ query: "ne+dles?", useRegex: true })).matches.map(
402 (match) => match.matchRanges,
403 ),
404 ).toEqual([[{ start: 6, end: 12 }], [{ start: 0, end: 7 }]]);
405 // Git's match text can end on the `\r` of a CRLF line.
406 expect(
407 (yield* search({ query: "needle|1;.*", useRegex: true })).matches.map(
408 (match) => match.matchRanges,
409 ),
410 ).toEqual([
411 [
412 { start: 6, end: 12 },
413 { start: 15, end: 17 },
414 ],
415 [{ start: 0, end: 6 }],
416 ]);
417 expect(
418 (yield* search({ query: "\\r", useRegex: true })).matches.map((match) => match.matchRanges),
419 ).toEqual([[]]);
420 expect(
421 (yield* search({ query: "[a-z]e", useRegex: true })).matches.map(
422 (match) => match.matchRanges,
423 ),
424 ).toEqual([
425 [{ start: 4, end: 6 }],
426 [
427 { start: 6, end: 8 },
428 { start: 10, end: 12 },
429 ],
430 [
431 { start: 0, end: 2 },
432 { start: 4, end: 6 },
433 ],
434 [{ start: 2, end: 4 }],
435 ]);
436 const invalid = yield* search({ query: "a.b(", useRegex: true });
437 expect(invalid.matches).toEqual([]);
438 expect(invalid.regexFallbackError).toBeDefined();
439 expect(yield* search({ limit: 1 })).toMatchObject({ truncated: true });
440 expect(grep).not.toHaveBeenCalled();
441​
442 // When git cannot give regex results or their ranges, fff answers once ready instead.
443 const failingGitIndex = (
444 failingArgument: string,
445 stderr: string,
446 output: { readonly exitCode: number; readonly stdout: string } = {
447 exitCode: 128,
448 stdout: "",
449 },
450 ) =>
451 WorkspaceSearchIndex.make(cwd, "content").pipe(
452 Effect.provideService(
453 VcsProcess.VcsProcess,
454 VcsProcess.VcsProcess.of({
455 run: (input) =>
456 input.args.includes(failingArgument)
457 ? Effect.succeed({
458 exitCode: ChildProcessSpawner.ExitCode(output.exitCode),
459 stdout: output.stdout,
460 stderr,
461 stdoutTruncated: output.exitCode === 0,
462 stderrTruncated: false,
463 })
464 : vcsProcess.run(input),
465 }),
466 ),
467 );
468 const regexInput = {
469 query: "ne+dles?",
470 limit: 10,
471 caseSensitive: false,
472 wholeWord: true,
473 useRegex: true,
474 };
475 const noPcreIndex = yield* failingGitIndex(
476 "-P",
477 "fatal: cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE\n",
478 );
479 expect((yield* noPcreIndex.searchContents(regexInput)).regexFallbackError).toBeUndefined();
480 expect(grep).toHaveBeenCalledTimes(1);
481 const noRangesIndex = yield* failingGitIndex("-o", "fatal: unexpected failure\n");
482 yield* noRangesIndex.searchContents(regexInput);
483 expect(grep).toHaveBeenCalledTimes(2);
484 // Ranges output cut off after line 1: line 2 is left out and the result says so.
485 const cutRangesIndex = yield* failingGitIndex("-o", "", {
486 exitCode: 0,
487 stdout: "src/a.ts\u00001\u00007\u0000Needle\nsrc/a.ts\u00002",
488 });
489 expect(yield* cutRangesIndex.searchContents(regexInput)).toEqual({
490 matches: [
491 {
492 path: "src/a.ts",
493 lineNumber: 1,
494 lineContent: "const Needle = 1;",
495 matchRanges: [{ start: 6, end: 12 }],
496 },
497 ],
498 truncated: true,
499 });
500 // A column that does not point at its text (a file edited between the two runs, or invalid
501 // UTF-8 before the match) still lands on that text, never on other text.
502 const staleRangesIndex = yield* failingGitIndex("-o", "", {
503 exitCode: 0,
504 stdout: "src/a.ts\u00001\u00001\u0000Needle\n",
505 });
506 expect(
507 (yield* staleRangesIndex.searchContents(regexInput)).matches.map(
508 (match) => match.matchRanges,
509 ),
510 ).toEqual([[{ start: 6, end: 12 }]]);
511 yield* fileSystem.writeFile(
512 path.join(cwd, "src/latin1.ts"),
513 new Uint8Array([...Buffer.from("caf"), 0xe9, ...Buffer.from(" needle needle\n")]),
514 );
515 expect(
516 (yield* search({ query: "needle", wholeWord: true, useRegex: true })).matches.map((match) => [
517 match.path,
518 match.matchRanges,
519 ]),
520 ).toEqual([
521 ["src/a.ts", [{ start: 6, end: 12 }]],
522 [
523 "src/latin1.ts",
524 [
525 { start: 5, end: 11 },
526 { start: 12, end: 18 },
527 ],
528 ],
529 ]);
530 yield* fileSystem.remove(path.join(cwd, "src/latin1.ts"));
531 // Outside a UTF-8 locale, git's `.` matches one byte of `中`.
532 yield* fileSystem.writeFileString(path.join(cwd, "src/cjk.ts"), "x中 y\n");
533 vi.stubEnv("LC_ALL", "C");
534 const partialCharacter = yield* search({ query: "x.", wholeWord: true, useRegex: true }).pipe(
535 Effect.ensuring(Effect.sync(() => vi.unstubAllEnvs())),
536 );
537 expect(partialCharacter.matches.map((match) => [match.path, match.matchRanges])).toEqual([
538 ["src/cjk.ts", [{ start: 0, end: 2 }]],
539 ]);
540 yield* fileSystem.remove(path.join(cwd, "src/cjk.ts"));
541​
542 // Lines longer than the 512-character cap are matched whole, then show only ranges that fit.
543 yield* fileSystem.writeFileString(
544 path.join(cwd, "src/long.ts"),
545 [
546 `${" ".repeat(600)}token`,
547 `${" ".repeat(507)}tokenized`,
548 `é token ${"d".repeat(600)} token`,
549 `é tokenized${" ".repeat(600)}token`,
550 // The cap falls inside the emoji, so the shown line drops it whole.
551 `token ${"a".repeat(505)}😀`,
552 ].join("\n"),
553 );
554 const longLines = (input: Partial<Parameters<typeof searchIndex.searchContents>[0]>) =>
555 search({ query: "token", ...input }).pipe(
556 Effect.map((result) =>
557 result.matches.map((match) => [
558 match.lineNumber,
559 match.lineContent.length,
560 match.matchRanges,
561 ]),
562 ),
563 );
564 const wholeWordLines = [
565 [1, 512, []],
566 [3, 512, [{ start: 2, end: 7 }]],
567 [4, 512, []],
568 [5, 511, [{ start: 0, end: 5 }]],
569 ];
570 expect(yield* longLines({ wholeWord: true })).toEqual(wholeWordLines);
571 expect(yield* longLines({ query: "tok+en", wholeWord: true, useRegex: true })).toEqual(
572 wholeWordLines,
573 );
574 expect(yield* longLines({ query: "tok+en\\w*", useRegex: true })).toEqual([
575 [1, 512, []],
576 [2, 512, []],
577 [3, 512, [{ start: 2, end: 7 }]],
578 [4, 512, [{ start: 2, end: 11 }]],
579 [5, 511, [{ start: 0, end: 5 }]],
580 ]);
581​
582 // Windows cannot name a file with a newline.
583 if (HostProcess.Platform.defaultValue() !== "win32") {
584 const newlinePath = "src/one\ntwo.txt";
585 yield* fileSystem.writeFileString(path.join(cwd, newlinePath), "unique_lf_needle\n");
586 for (const input of [
587 { query: "unique_lf_needle" },
588 { query: "unique_lf_n.+", useRegex: true },
589 ]) {
590 expect((yield* search({ ...input, caseSensitive: true })).matches).toEqual([
591 {
592 path: newlinePath,
593 lineNumber: 1,
594 lineContent: "unique_lf_needle",
595 matchRanges: [{ start: 0, end: 16 }],
596 },
597 ]);
598 }
599 yield* fileSystem.remove(path.join(cwd, newlinePath));
600 }
601​
602 isWarmupComplete = true;
603 yield* search({});
604 expect(grep).toHaveBeenCalledTimes(3);
605 expect(finder.destroy).not.toHaveBeenCalled();
606 }).pipe(Effect.scoped, Effect.provide(testLayer)),
607);
608​
609// Git stops at 100 lines per file, so lines that only contain the word must not use them up.
610it.live(
611 "finds a whole word past many longer words in one file while the content index builds",
612 () =>
613 Effect.gen(function* () {
614 const fileSystem = yield* FileSystem.FileSystem;
615 const path = yield* Path.Path;
616 const vcsProcess = yield* VcsProcess.VcsProcess;
617 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-content-warmup-word-" });
618 yield* vcsProcess.run({ operation: "test.gitInit", command: "git", args: ["init"], cwd });
619 yield* fileSystem.writeFileString(
620 path.join(cwd, "a.ts"),
621 `${Array.from({ length: 150 }, (_, index) => `const needleSuffix${index} = 1;`).join("\n")}\nneedle();\n`,
622 );
623 const grep = vi.fn();
624 vi.spyOn(FileFinder, "create").mockReturnValueOnce({
625 ok: true,
626 value: {
627 destroy: vi.fn(),
628 waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: false })),
629 getScanProgressAsync: async () => ({
630 ok: true as const,
631 value: { isScanning: true, isWarmupComplete: false },
632 }),
633 watchAsync: async () => ({ ok: true as const, value: () => undefined }),
634 grepAsync: grep,
635 } as unknown as FileFinder,
636 });
637​
638 const searchIndex = yield* WorkspaceSearchIndex.make(cwd, "content");
639 const result = yield* searchIndex.searchContents({
640 query: "needle",
641 limit: 10,
642 caseSensitive: false,
643 wholeWord: true,
644 useRegex: false,
645 });
646​
647 expect(result.matches).toEqual([
648 {
649 path: "a.ts",
650 lineNumber: 151,
651 lineContent: "needle();",
652 matchRanges: [{ start: 0, end: 6 }],
653 },
654 ]);
655 expect(grep).not.toHaveBeenCalled();
656 }).pipe(Effect.scoped, Effect.provide(testLayer)),
657);
658​
659function fakeSymlinkFinder(
660 directories: ReadonlyArray<string>,
661 options: {
662 readonly indexed?: ReadonlyArray<{
663 readonly path: string;
664 readonly kind: "file" | "directory";
665 }>;
666 readonly watchFailures?: number;
667 } = {},
668) {
669 const watchers: Array<(events: ReadonlyArray<WatchEvent>) => void> = [];
670 let watchFailures = options.watchFailures ?? 0;
671 // fff's pageIndex is an offset into the results, not a page number.
672 const directorySearch = vi.fn(
673 async (_query: string, searchOptions?: { pageIndex?: number; pageSize?: number }) => {
674 const offset = searchOptions?.pageIndex ?? 0;
675 const items = directories.slice(offset, offset + (searchOptions?.pageSize ?? 100));
676 return {
677 ok: true as const,
678 value: {
679 items: items.map((relativePath) => ({ relativePath })),
680 totalMatched: directories.length,
681 },
682 };
683 },
684 );
685 const indexedItems = (options.indexed ?? []).map((entry) => ({
686 type: entry.kind,
687 item: { relativePath: entry.path, fileName: entry.path.split("/").at(-1) },
688 }));
689 const finder = {
690 destroy: vi.fn(),
691 waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })),
692 // fff's isScanning waits on the picker lock on the JS thread.
693 isScanning: () => {
694 throw new Error("isScanning must not run on the JS thread");
695 },
696 getScanProgressAsync: async () => ({
697 ok: true as const,
698 value: { isScanning: false },
699 }),
700 // fff's watch waits on the picker lock on the JS thread.
701 watch: () => {
702 throw new Error("watch must not run on the JS thread");
703 },
704 watchAsync: async (callback: (events: ReadonlyArray<WatchEvent>) => void) => {
705 if (watchFailures > 0) {
706 watchFailures -= 1;
707 return { ok: false as const, error: "File system watcher is not ready" };
708 }
709 watchers.push(callback);
710 return { ok: true as const, value: () => undefined };
711 },
712 directorySearchAsync: directorySearch,
713 fileSearchAsync: async () => {
714 const items = indexedItems.flatMap((entry) => (entry.type === "file" ? [entry.item] : []));
715 return { ok: true as const, value: { items, scores: [], totalMatched: items.length } };
716 },
717 mixedSearchAsync: async () => ({
718 ok: true as const,
719 value: { items: indexedItems, totalMatched: indexedItems.length },
720 }),
721 } as unknown as FileFinder;
722 vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder });
723 return {
724 directorySearch,
725 notifyWatchers: (events: ReadonlyArray<WatchEvent>) =>
726 watchers.forEach((watcher) => watcher(events)),
727 };
729​
730const listedPaths = (searchIndex: WorkspaceSearchIndex.WorkspaceSearchIndex["Service"]) =>
731 searchIndex.list().pipe(Effect.map((result) => result.entries.map((entry) => entry.path)));
732​
733it.effect("reads symlinks again after the watcher reports a change", () =>
734 Effect.scoped(
735 Effect.gen(function* () {
736 if ((yield* HostProcess.Platform) === "win32") return;
737 const fileSystem = yield* FileSystem.FileSystem;
738 const path = yield* Path.Path;
739 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-symlink-watch-" });
740 const outside = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-outside-" });
741 yield* fileSystem.writeFileString(path.join(cwd, "a.ts"), "");
742 yield* fileSystem.symlink("a.ts", path.join(cwd, "old-link.ts"));
743 const { directorySearch, notifyWatchers } = fakeSymlinkFinder([]);
744​
745 const searchIndex = yield* WorkspaceSearchIndex.make(cwd);
746 const concurrent = yield* Effect.all(
747 Array.from({ length: 8 }, () => listedPaths(searchIndex)),
748 { concurrency: "unbounded" },
749 );
750 yield* fileSystem.remove(path.join(cwd, "old-link.ts"));
751 yield* fileSystem.symlink("a.ts", path.join(cwd, "new-link.ts"));
752 const beforeNotice = yield* listedPaths(searchIndex);
753 // Editing a file cannot move a link, so it does not cost a rescan.
754 notifyWatchers([{ kind: "modified", path: path.join(cwd, "a.ts") }]);
755 const afterEdit = yield* listedPaths(searchIndex);
756 notifyWatchers([{ kind: "created", path: path.join(cwd, "new-link.ts") }]);
757 const afterNotice = yield* listedPaths(searchIndex);
758 // fff reports a link replaced in place as modified.
759 yield* fileSystem.remove(path.join(cwd, "new-link.ts"));
760 yield* fileSystem.symlink(outside, path.join(cwd, "new-link.ts"));
761 notifyWatchers([{ kind: "modified", path: path.join(cwd, "new-link.ts") }]);
762 const afterReplace = yield* listedPaths(searchIndex);
763​
764 expect(concurrent).toEqual(Array.from({ length: 8 }, () => ["old-link.ts"]));
765 expect(beforeNotice).toEqual(["old-link.ts"]);
766 expect(afterEdit).toEqual(["old-link.ts"]);
767 expect(afterNotice).toEqual(["new-link.ts"]);
768 expect(afterReplace).toEqual([]);
769 expect(directorySearch).toHaveBeenCalledTimes(3);
770 }),
771 ).pipe(Effect.provide(testLayer)),
772);
773​
774it.effect("answers from the last symlink scan while a slow rescan runs", () =>
775 Effect.scoped(
776 Effect.gen(function* () {
777 if ((yield* HostProcess.Platform) === "win32") return;
778 const fileSystem = yield* FileSystem.FileSystem;
779 const path = yield* Path.Path;
780 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-symlink-stale-" });
781 yield* fileSystem.writeFileString(path.join(cwd, "a.ts"), "");
782 yield* fileSystem.symlink("a.ts", path.join(cwd, "old-link.ts"));
783 const { notifyWatchers } = fakeSymlinkFinder([]);
784 // Holding git's ignore check open keeps the rescan from finishing.
785 const gate = yield* Deferred.make<void>();
786 let holdIgnoreChecks = false;
787 const vcsProcess = yield* VcsProcess.VcsProcess;
788 const searchIndex = yield* WorkspaceSearchIndex.make(cwd).pipe(
789 Effect.provideService(VcsProcess.VcsProcess, {
790 ...vcsProcess,
791 run: (input) =>
792 holdIgnoreChecks && input.operation === "WorkspaceSearchIndex.listGitIgnored"
793 ? Deferred.await(gate).pipe(Effect.andThen(vcsProcess.run(input)))
794 : vcsProcess.run(input),
795 }),
796 );
797 expect(yield* listedPaths(searchIndex)).toEqual(["old-link.ts"]);
798​
799 holdIgnoreChecks = true;
800 yield* fileSystem.symlink("a.ts", path.join(cwd, "new-link.ts"));
801 notifyWatchers([{ kind: "created", path: path.join(cwd, "new-link.ts") }]);
802 const duringRescan = yield* Effect.forkChild(listedPaths(searchIndex));
803 yield* TestClock.adjust("1 second");
804 expect(yield* Fiber.join(duringRescan)).toEqual(["old-link.ts"]);
805​
806 yield* Deferred.succeed(gate, undefined);
807 expect(yield* listedPaths(searchIndex)).toEqual(["new-link.ts", "old-link.ts"]);
808 }),
809 ).pipe(Effect.provide(testLayer)),
810);
811​
812it.effect("keeps symlinks once the watcher subscribes after starting late", () =>
813 Effect.scoped(
814 Effect.gen(function* () {
815 if ((yield* HostProcess.Platform) === "win32") return;
816 const fileSystem = yield* FileSystem.FileSystem;
817 const path = yield* Path.Path;
818 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-symlink-watch-" });
819 yield* fileSystem.writeFileString(path.join(cwd, "a.ts"), "");
820 yield* fileSystem.symlink("a.ts", path.join(cwd, "link.ts"));
821 const { directorySearch } = fakeSymlinkFinder([], { watchFailures: 2 });
822​
823 const searchIndex = yield* WorkspaceSearchIndex.make(cwd);
824 const scansAfterRound: number[] = [];
825 for (let round = 0; round < 5; round += 1) {
826 expect(yield* listedPaths(searchIndex)).toEqual(["link.ts"]);
827 expect(yield* listedPaths(searchIndex)).toEqual(["link.ts"]);
828 scansAfterRound.push(directorySearch.mock.calls.length);
829 yield* TestClock.adjust("1 minute");
830 }
831​
832 // An unwatched scan serves reads only briefly; the third has a watcher and is kept.
833 expect(scansAfterRound).toEqual([1, 2, 3, 3, 3]);
834 }),
835 ).pipe(Effect.provide(testLayer)),
836);
837​
838it.effect(
839 "lists a symlink the watcher indexed once, with the link's kind, and drops rejected ones",
840 () =>
841 Effect.scoped(
842 Effect.gen(function* () {
843 if ((yield* HostProcess.Platform) === "win32") return;
844 const fileSystem = yield* FileSystem.FileSystem;
845 const path = yield* Path.Path;
846 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-symlink-dupe-" });
847 const outside = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-outside-" });
848 yield* fileSystem.makeDirectory(path.join(cwd, "src"));
849 yield* fileSystem.symlink("src", path.join(cwd, "src-link"));
850 // A link the scan rejects stays out even when the watcher indexed it.
851 yield* fileSystem.symlink(outside, path.join(cwd, "outside-link"));
852 fakeSymlinkFinder([], {
853 indexed: [
854 { path: "outside-link", kind: "file" },
855 { path: "src-link", kind: "file" },
856 { path: "link-file.ts", kind: "file" },
857 ],
858 });
859​
860 const searchIndex = yield* WorkspaceSearchIndex.make(cwd);
861 const searched = yield* searchIndex.search("link", 10);
862 const files = yield* searchIndex.search("link", 1, "file");
863 const listed = yield* searchIndex.list();
864​
865 expect(searched.entries).toEqual([
866 { path: "src-link", kind: "directory" },
867 { path: "link-file.ts", kind: "file" },
868 ]);
869 // The dropped link does not take the only slot.
870 expect(files).toEqual({
871 entries: [{ path: "link-file.ts", kind: "file" }],
872 truncated: false,
873 });
874 expect(listed.entries).toEqual([
875 { path: "link-file.ts", kind: "file" },
876 { path: "src-link", kind: "directory" },
877 ]);
878 }),
879 ).pipe(Effect.provide(testLayer)),
880);
881​
882it.effect("finds symlinks in folders past the first page of the index", () =>
883 Effect.scoped(
884 Effect.gen(function* () {
885 if ((yield* HostProcess.Platform) === "win32") return;
886 const fileSystem = yield* FileSystem.FileSystem;
887 const path = yield* Path.Path;
888 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-symlink-pages-" });
889 yield* fileSystem.makeDirectory(path.join(cwd, "late"));
890 yield* fileSystem.writeFileString(path.join(cwd, "late/a.ts"), "");
891 yield* fileSystem.symlink("a.ts", path.join(cwd, "late/link.ts"));
892 // Folders fff lists but that are gone by the time they are read are skipped.
893 const firstPage = Array.from({ length: 1_000 }, (_, index) => `missing-${index}`);
894 const { directorySearch } = fakeSymlinkFinder([...firstPage, "late"]);
895​
896 const searchIndex = yield* WorkspaceSearchIndex.make(cwd);
897​
898 expect(yield* listedPaths(searchIndex)).toEqual(["late", "late/link.ts"]);
899 expect(directorySearch.mock.calls.map(([, options]) => options?.pageIndex)).toEqual([
900 0, 1_000,
901 ]);
902 }),
903 ).pipe(Effect.provide(testLayer)),
904);
905​
906it.effect("keeps symlinks Git does not ignore when a link's name looks like a git pathspec", () =>
907 Effect.scoped(
908 Effect.gen(function* () {
909 if ((yield* HostProcess.Platform) === "win32") return;
910 const fileSystem = yield* FileSystem.FileSystem;
911 const path = yield* Path.Path;
912 const vcsProcess = yield* VcsProcess.VcsProcess;
913 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-symlink-pathspec-" });
914 yield* vcsProcess.run({ operation: "test.gitInit", command: "git", args: ["init"], cwd });
915 yield* fileSystem.writeFileString(path.join(cwd, ".gitignore"), "ignored-link\n");
916 yield* fileSystem.writeFileString(path.join(cwd, "a.ts"), "");
917 yield* fileSystem.symlink("a.ts", path.join(cwd, "docs-link"));
918 yield* fileSystem.symlink("a.ts", path.join(cwd, ":(link)"));
919 yield* fileSystem.symlink("a.ts", path.join(cwd, "ignored-link"));
920 // Stage so `ls-files --others` skips it and `listGitIgnored` must hide it.
921 yield* vcsProcess.run({
922 operation: "test.gitAdd",
923 command: "git",
924 args: ["add", "-f", "ignored-link"],
925 cwd,
926 });
927 fakeSymlinkFinder([]);
928​
929 const searchIndex = yield* WorkspaceSearchIndex.make(cwd);
930​
931 expect(yield* listedPaths(searchIndex)).toEqual([":(link)", "docs-link"]);
932 }),
933 ).pipe(Effect.provide(testLayer)),
934);
935​
936// fff reads HOME on Linux and macOS but the user profile on Windows, so a temp HOME cannot stand in there.
937it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
938 "refuses to index a workspace rooted at the home directory",
939 () =>
940 Effect.scoped(
941 Effect.gen(function* () {
942 const fs = yield* FileSystem.FileSystem;
943 const path = yield* Path.Path;
944 const home = yield* fs.realPath(
945 yield* fs.makeTempDirectoryScoped({ prefix: "t3-search-home-" }),
946 );
947 yield* fs.makeDirectory(path.join(home, "OneDrive", "Remix"), { recursive: true });
948 yield* fs.writeFileString(path.join(home, "OneDrive", "Remix", "part.stl"), "solid part\n");
949 yield* Effect.acquireRelease(
950 Effect.sync(() => vi.stubEnv("HOME", home)),
951 () => Effect.sync(() => vi.unstubAllEnvs()),
952 );
953​
954 const result = yield* WorkspaceSearchIndex.make(home).pipe(
955 Effect.flatMap((searchIndex) => searchIndex.search("stl", 50, undefined, false)),
956 Effect.map(({ entries }) => entries),
957 Effect.catchTags({
958 WorkspaceSearchIndexCreateFailed: (error) => Effect.succeed(error._tag),
959 }),
960 );
961​
962 expect(result).toBe("WorkspaceSearchIndexCreateFailed");
963 }),
964 ).pipe(Effect.provide(testLayer)),
965);
966​
967// ripgrep and fff let a matching `.ignore` decide ahead of `.gitignore`, so Git's list must not hide it.
968it.live("finds Git-ignored files that a root .ignore re-includes", () =>
969 Effect.gen(function* () {
970 const fileSystem = yield* FileSystem.FileSystem;
971 const path = yield* Path.Path;
972 const vcsProcess = yield* VcsProcess.VcsProcess;
973 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-search-reinclude-" });
974 yield* vcsProcess.run({ operation: "test.gitInit", command: "git", args: ["init"], cwd });
975 yield* fileSystem.writeFileString(path.join(cwd, ".gitignore"), "notes/\n");
976 yield* fileSystem.writeFileString(
977 path.join(cwd, ".ignore"),
978 "!notes/\nnotes/**/*\n!notes/**/\n!notes/**/*.md\n",
979 );
980 yield* fileSystem.makeDirectory(path.join(cwd, "notes", "daily"), { recursive: true });
981 yield* fileSystem.writeFileString(path.join(cwd, "notes", "daily", "standup.md"), "");
982 yield* fileSystem.writeFileString(path.join(cwd, "notes", "daily", "standup.txt"), "");
983​
984 const searchIndex = yield* WorkspaceSearchIndex.make(cwd);
985 const result = yield* searchIndex.search("standup", 50, "file");
986​
987 expect(result.entries).toEqual([{ kind: "file", path: "notes/daily/standup.md" }]);
988 }).pipe(Effect.scoped, Effect.provide(testLayer)),
989);
990​
991// Real fff: the native whole-word pattern must return what the plain search and the JS word check did.
992it.live.each([
993 { query: "needle", caseSensitive: true, expected: ["notes.md:1:0-6", "words.ts:2:0-6,8-14"] },
994 { query: "NEEDLE", caseSensitive: false, expected: ["notes.md:1:0-6", "words.ts:2:0-6,8-14"] },
995 // fff reads `*.ts` as a file constraint, which a regex built around the whole query would lose.
996 { query: "*.ts needle", caseSensitive: true, expected: ["words.ts:2:0-6,8-14"] },
997 // Plain search folds ASCII case only: `ſ` is not an `s`, and the Kelvin sign is not a `k`.
998 { query: "s", caseSensitive: false, expected: ["fold.txt:2:0-1"] },
999 { query: "k", caseSensitive: false, expected: ["fold.txt:4:0-1"] },
1000])("matches whole words in a real workspace for $query", ({ query, caseSensitive, expected }) =>
1001 Effect.gen(function* () {
1002 const fileSystem = yield* FileSystem.FileSystem;
1003 const path = yield* Path.Path;
1004 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-search-whole-word-" });
1005 yield* fileSystem.writeFileString(
1006 path.join(cwd, "words.ts"),
1007 "needleSuffix\nneedle, needle.\n\u00e9needle\n",
1008 );
1009 yield* fileSystem.writeFileString(path.join(cwd, "notes.md"), "needle *.ts\n");
1010 yield* fileSystem.writeFileString(path.join(cwd, "fold.txt"), "\u017f\ns\n\u212a\nk\n");
1011​
1012 const searchIndex = yield* WorkspaceSearchIndex.make(cwd, "content");
1013 const result = yield* searchIndex.searchContents({
1014 query,
1015 limit: 500,
1016 caseSensitive,
1017 wholeWord: true,
1018 useRegex: false,
1019 });
1020​
1021 expect(
1022 result.matches
1023 .map(
1024 (match) =>
1025 `${match.path}:${match.lineNumber}:${match.matchRanges.map((range) => `${range.start}-${range.end}`).join(",")}`,
1027 .toSorted(),
1028 ).toEqual(expected);
1029 }).pipe(Effect.scoped, Effect.provide(testLayer)),