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

WorkspaceSearchIndex.test.ts

176 lines5.7 KB

1import {
2 FileFinder,
3 type FileItem,
4 type GrepCursor,
5 type GrepOptions,
6 type GrepResult,
7} from "@ff-labs/fff-node";
8import * as NodeServices from "@effect/platform-node/NodeServices";
9import { afterEach, expect, it } from "@effect/vitest";
10import * as HostProcess from "@t3tools/shared/HostProcess";
11import * as Effect from "effect/Effect";
12import * as FileSystem from "effect/FileSystem";
13import * as Path from "effect/Path";
14import { vi } from "vite-plus/test";
15​
16import * as WorkspaceSearchIndex from "./WorkspaceSearchIndex.ts";
17​
18afterEach(() => {
19 vi.restoreAllMocks();
20});
21​
22function fileItem(relativePath: string): FileItem {
23 return {
24 relativePath,
25 fileName: relativePath.slice(relativePath.lastIndexOf("/") + 1),
26 size: 1,
27 modified: 0,
28 accessFrecencyScore: 0,
29 modificationFrecencyScore: 0,
30 totalFrecencyScore: 0,
31 gitStatus: "clean",
32 };
34​
35it.effect("filters image searches before applying the result limit", () =>
36 Effect.scoped(
37 Effect.gen(function* () {
38 const items = [
39 ...Array.from({ length: 200 }, (_, index) => fileItem(`src/file-${index}.ts`)),
40 fileItem("public/icon.svg"),
41 ];
42 const fileSearch = vi.fn(() => ({
43 ok: true as const,
44 value: {
45 items,
46 scores: [],
47 totalMatched: items.length,
48 totalFiles: items.length,
49 },
50 }));
51 const finder = {
52 destroy: vi.fn(),
53 waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })),
54 fileSearch,
55 } as unknown as FileFinder;
56 vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder });
57​
58 const searchIndex = yield* WorkspaceSearchIndex.make("/workspace/project");
59 const resultWithoutKind = yield* searchIndex.search("", 200, undefined, true);
60 const resultWithDirectoryKind = yield* searchIndex.search("", 200, "directory", true);
61​
62 expect(resultWithoutKind.entries).toEqual([{ kind: "file", path: "public/icon.svg" }]);
63 expect(resultWithDirectoryKind.entries).toEqual([{ kind: "file", path: "public/icon.svg" }]);
64 expect(fileSearch).toHaveBeenCalledTimes(2);
65 expect(fileSearch).toHaveBeenCalledWith("", { pageSize: 25_002 });
66 }),
67 ),
68);
69​
70it.effect("continues whole-word searches after a filtered grep page", () =>
71 Effect.scoped(
72 Effect.gen(function* () {
73 const nextCursor = {
74 __brand: "GrepCursor",
75 _offset: 1,
76 } as GrepCursor;
77 const grepResult = (
78 lineContent: string,
79 matchRanges: Array<[number, number]>,
80 cursor: GrepCursor | null,
81 ): GrepResult => ({
82 items: [
83 {
84 relativePath: "src/words.ts",
85 fileName: "words.ts",
86 gitStatus: "unmodified",
87 size: lineContent.length,
88 modified: 0,
89 isBinary: false,
90 totalFrecencyScore: 0,
91 accessFrecencyScore: 0,
92 modificationFrecencyScore: 0,
93 lineNumber: 1,
94 col: 0,
95 byteOffset: 0,
96 lineContent,
97 matchRanges,
98 },
99 ],
100 totalMatched: 1,
101 totalFilesSearched: 1,
102 totalFiles: 1,
103 filteredFileCount: 1,
104 nextCursor: cursor,
105 });
106 const grep = vi.fn((_query: string, options?: GrepOptions) =>
107 options?.cursor
108 ? { ok: true as const, value: grepResult("needle", [[0, 6]], null) }
109 : {
110 ok: true as const,
111 value: grepResult("needleSuffix", [[0, 6]], nextCursor),
112 },
113 );
114 const finder = {
115 destroy: vi.fn(),
116 waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })),
117 grep,
118 } as unknown as FileFinder;
119 vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder });
120​
121 const searchIndex = yield* WorkspaceSearchIndex.make("/workspace/project", "content");
122 const result = yield* searchIndex.searchContents({
123 query: "needle",
124 limit: 1,
125 caseSensitive: true,
126 wholeWord: true,
127 useRegex: false,
128 });
129​
130 expect(result).toEqual({
131 matches: [
132 {
133 path: "src/words.ts",
134 lineNumber: 1,
135 lineContent: "needle",
136 matchRanges: [{ start: 0, end: 6 }],
137 },
138 ],
139 truncated: false,
140 });
141 expect(grep).toHaveBeenCalledTimes(2);
142 expect(grep.mock.calls[1]?.[1]?.cursor).toBe(nextCursor);
143 }),
144 ),
145);
146​
147// fff reads HOME on Linux and macOS but the user profile on Windows, so a temp HOME cannot stand in there.
148it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
149 "refuses to index a workspace rooted at the home directory",
150 () =>
151 Effect.scoped(
152 Effect.gen(function* () {
153 const fs = yield* FileSystem.FileSystem;
154 const path = yield* Path.Path;
155 const home = yield* fs.realPath(
156 yield* fs.makeTempDirectoryScoped({ prefix: "t3-search-home-" }),
157 );
158 yield* fs.makeDirectory(path.join(home, "OneDrive", "Remix"), { recursive: true });
159 yield* fs.writeFileString(path.join(home, "OneDrive", "Remix", "part.stl"), "solid part\n");
160 yield* Effect.acquireRelease(
161 Effect.sync(() => vi.stubEnv("HOME", home)),
162 () => Effect.sync(() => vi.unstubAllEnvs()),
163 );
164​
165 const result = yield* WorkspaceSearchIndex.make(home).pipe(
166 Effect.flatMap((searchIndex) => searchIndex.search("stl", 50, undefined, false)),
167 Effect.map(({ entries }) => entries),
168 Effect.catchTags({
169 WorkspaceSearchIndexCreateFailed: (error) => Effect.succeed(error._tag),
170 }),
171 );
172​
173 expect(result).toBe("WorkspaceSearchIndexCreateFailed");
174 }),
175 ).pipe(Effect.provide(NodeServices.layer)),
176);