Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeFSP from "node:fs/promises";
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import { FileFinder } from "@ff-labs/fff-node";
5import { it, afterEach, describe, expect } from "@effect/vitest";
6import * as Effect from "effect/Effect";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as Path from "effect/Path";
10import * as PlatformError from "effect/PlatformError";
11import { vi } from "vite-plus/test";
12
13import * as ServerConfig from "../config.ts";
14import * as HostProcess from "@t3tools/shared/HostProcess";
15import * as VcsProcess from "../vcs/VcsProcess.ts";
16import * as WorkspaceEntries from "./WorkspaceEntries.ts";
17import * as WorkspacePaths from "./WorkspacePaths.ts";
18
19vi.mock("node:fs/promises", async (importOriginal) => {
20 const actual = await importOriginal<typeof import("node:fs/promises")>();
21 return { ...actual, readdir: vi.fn(actual.readdir) };
22});
23
24const layerTest = Layer.empty.pipe(
25 Layer.provideMerge(WorkspaceEntries.layer.pipe(Layer.provide(WorkspacePaths.layer))),
26 Layer.provideMerge(WorkspacePaths.layer),
27 Layer.provideMerge(VcsProcess.layer),
28 Layer.provide(
29 ServerConfig.ServerConfig.layerTest(process.cwd(), {
30 prefix: "t3-workspace-entries-test-",
31 }),
32 ),
33 Layer.provideMerge(NodeServices.layer),
34);
35
36const makeTempDir = Effect.fn(function* (opts?: { prefix?: string; git?: boolean }) {
37 const fileSystem = yield* FileSystem.FileSystem;
38 const dir = yield* fileSystem.makeTempDirectoryScoped({
39 prefix: opts?.prefix ?? "t3code-workspace-entries-",
40 });
41 if (opts?.git) {
42 yield* git(dir, ["init"]);
43 }
44 return dir;
45});
46
47function writeTextFile(
48 cwd: string,
49 relativePath: string,
50 contents = "",
51): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem | Path.Path> {
52 return Effect.gen(function* () {
53 const fileSystem = yield* FileSystem.FileSystem;
54 const path = yield* Path.Path;
55 const absolutePath = path.join(cwd, relativePath);
56 yield* fileSystem.makeDirectory(path.dirname(absolutePath), { recursive: true });
57 yield* fileSystem.writeFileString(absolutePath, contents);
58 });
59}
60
61const git = (cwd: string, args: ReadonlyArray<string>, env?: NodeJS.ProcessEnv) =>
62 Effect.gen(function* () {
63 const process = yield* VcsProcess.VcsProcess;
64 const result = yield* process.run({
65 operation: "WorkspaceEntries.test.git",
66 command: "git",
67 cwd,
68 args,
69 ...(env ? { env } : {}),
70 timeoutMs: 10_000,
71 });
72 return result.stdout.trim();
73 });
74
75const searchWorkspaceEntries = (input: {
76 cwd: string;
77 query: string;
78 limit: number;
79 kind?: "file" | "directory";
80}) =>
81 Effect.gen(function* () {
82 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
83 return yield* workspaceEntries.search(input);
84 });
85
86const appendSeparator = (input: string) =>
87 Effect.map(HostProcess.Platform, (platform) =>
88 input.endsWith("/") || input.endsWith("\\")
89 ? input
90 : `${input}${platform === "win32" ? "\\" : "/"}`,
91 );
92
93it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => {
94 afterEach(() => {
95 vi.restoreAllMocks();
96 });
97
98 describe("list", () => {
99 it.effect("lists immediate children including ignored and empty directories", () =>
100 Effect.gen(function* () {
101 const cwd = yield* makeTempDir({ git: true });
102 const fileSystem = yield* FileSystem.FileSystem;
103 const path = yield* Path.Path;
104 yield* writeTextFile(cwd, "tracked.txt");
105 yield* git(cwd, ["add", "tracked.txt"]);
106 yield* writeTextFile(cwd, ".gitignore", "node_modules/\n.env\ntracked.txt\n");
107 yield* writeTextFile(cwd, ".env", "secret=value");
108 yield* writeTextFile(cwd, "node_modules/pkg/index.js");
109 yield* writeTextFile(cwd, "src/index.ts");
110 yield* fileSystem.makeDirectory(path.join(cwd, "empty"));
111
112 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
113 const root = yield* workspaceEntries.list({ cwd, directoryPath: "" });
114 expect(root.entries).toEqual(
115 expect.arrayContaining([
116 { path: ".env", kind: "file", ignored: true },
117 { path: "node_modules", kind: "directory", ignored: true },
118 { path: "src", kind: "directory" },
119 { path: "empty", kind: "directory" },
120 { path: "tracked.txt", kind: "file" },
121 ]),
122 );
123 expect(root.entries.some((entry) => entry.path.includes("/"))).toBe(false);
124 expect(root.entries.some((entry) => entry.path === ".git")).toBe(false);
125 expect(root.truncated).toBe(false);
126 expect(yield* workspaceEntries.list({ cwd, directoryPath: "node_modules/pkg" })).toEqual({
127 entries: [{ path: "node_modules/pkg/index.js", kind: "file", ignored: true }],
128 truncated: false,
129 });
130 expect(yield* workspaceEntries.list({ cwd, directoryPath: "empty" })).toEqual({
131 entries: [],
132 truncated: false,
133 });
134 }),
135 );
136
137 it.effect("lists symlinks as what they point to, hiding ones that cannot be opened", () =>
138 Effect.gen(function* () {
139 const platform = yield* HostProcess.Platform;
140 if (platform === "win32") return;
141 const cwd = yield* makeTempDir({ git: true });
142 const outside = yield* makeTempDir();
143 const fileSystem = yield* FileSystem.FileSystem;
144 const path = yield* Path.Path;
145 yield* writeTextFile(cwd, "real.txt");
146 yield* writeTextFile(cwd, "realdir/nested.txt");
147 yield* writeTextFile(outside, "outside.txt");
148 yield* fileSystem.symlink("real.txt", path.join(cwd, "link.txt"));
149 yield* fileSystem.symlink("realdir", path.join(cwd, "linkdir"));
150 yield* fileSystem.symlink(outside, path.join(cwd, "outside-link"));
151 yield* fileSystem.symlink(".git", path.join(cwd, "git-link"));
152 yield* fileSystem.symlink("missing", path.join(cwd, "dangling"));
153
154 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
155 const root = yield* workspaceEntries.list({ cwd, directoryPath: "" });
156 expect(root.entries.toSorted((a, b) => a.path.localeCompare(b.path))).toEqual([
157 { path: "link.txt", kind: "file" },
158 { path: "linkdir", kind: "directory" },
159 { path: "real.txt", kind: "file" },
160 { path: "realdir", kind: "directory" },
161 ]);
162 expect(yield* workspaceEntries.list({ cwd, directoryPath: "linkdir" })).toEqual({
163 entries: [{ path: "linkdir/nested.txt", kind: "file" }],
164 truncated: false,
165 });
166 }),
167 );
168
169 it.effect("hides folder links that lead back to a folder on the listed path", () =>
170 // "Expand all folders" loads every folder it expands, so a link that loops would
171 // keep nesting the same entries without end.
172 Effect.gen(function* () {
173 const platform = yield* HostProcess.Platform;
174 if (platform === "win32") return;
175 const cwd = yield* makeTempDir();
176 const fileSystem = yield* FileSystem.FileSystem;
177 const path = yield* Path.Path;
178 yield* writeTextFile(cwd, "a/file.txt");
179 yield* writeTextFile(cwd, "b/file.txt");
180 yield* fileSystem.symlink(".", path.join(cwd, "self"));
181 yield* fileSystem.symlink("..", path.join(cwd, "a/up"));
182 yield* fileSystem.symlink("../b", path.join(cwd, "a/to-b"));
183 yield* fileSystem.symlink("../a", path.join(cwd, "b/to-a"));
184
185 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
186 const paths = (directoryPath: string) =>
187 workspaceEntries
188 .list({ cwd, directoryPath })
189 .pipe(Effect.map(({ entries }) => entries.map((entry) => entry.path).toSorted()));
190 expect(yield* paths("")).toEqual(["a", "b"]);
191 // A link into a sibling folder is fine on its own...
192 expect(yield* paths("a")).toEqual(["a/file.txt", "a/to-b"]);
193 // ...but once followed, the sibling's link back is hidden.
194 expect(yield* paths("a/to-b")).toEqual(["a/to-b/file.txt"]);
195 }),
196 );
197
198 it.effect("resolves a folder of many symlinks in bounded batches", () =>
199 Effect.gen(function* () {
200 const platform = yield* HostProcess.Platform;
201 if (platform === "win32") return;
202 const cwd = yield* makeTempDir();
203 const fileSystem = yield* FileSystem.FileSystem;
204 const path = yield* Path.Path;
205 // Shaped like a pnpm `node_modules`: one link per package into `.pnpm`.
206 const directoryPath = [...Array.from({ length: 80 }, () => "nested"), "node_modules"].join(
207 "/",
208 );
209 const packages = Array.from({ length: 200 }, (_, index) => `pkg-${index}`);
210 yield* Effect.forEach(
211 packages,
212 (name) =>
213 Effect.gen(function* () {
214 yield* writeTextFile(cwd, `${directoryPath}/.pnpm/${name}/index.js`);
215 yield* fileSystem.symlink(`.pnpm/${name}`, path.join(cwd, directoryPath, name));
216 }),
217 { concurrency: 32, discard: true },
218 );
219 const realpath = NodeFSP.realpath;
220 let inFlight = 0;
221 let maxInFlight = 0;
222 vi.spyOn(NodeFSP, "realpath").mockImplementation((async (target: string) => {
223 maxInFlight = Math.max(maxInFlight, ++inFlight);
224 try {
225 return await realpath(target);
226 } finally {
227 inFlight--;
228 }
229 }) as typeof NodeFSP.realpath);
230
231 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
232 const { entries } = yield* workspaceEntries.list({ cwd, directoryPath });
233 expect(entries.map((entry) => entry.path).toSorted()).toEqual(
234 [
235 `${directoryPath}/.pnpm`,
236 ...packages.map((name) => `${directoryPath}/${name}`),
237 ].toSorted(),
238 );
239 expect(entries.every((entry) => entry.kind === "directory")).toBe(true);
240 expect(maxInFlight).toBeLessThanOrEqual(64);
241 }),
242 );
243
244 it.effect("labels the children of wide folders exactly as git does for each child", () =>
245 Effect.gen(function* () {
246 // Above 1,000 children, listing first asks whether the whole folder is ignored.
247 const cwd = yield* makeTempDir({ git: true });
248 const fileSystem = yield* FileSystem.FileSystem;
249 const path = yield* Path.Path;
250 const platform = yield* HostProcess.Platform;
251 yield* writeTextFile(
252 cwd,
253 ".gitignore",
254 "node_modules/\ndist/\n\\[id\\]/\n*.map\nfoo\n!foo/\n",
255 );
256 yield* Effect.forEach(
257 [
258 "node_modules",
259 "dist",
260 "[id]",
261 "src",
262 ...(platform !== "win32" ? [":foo"] : []),
263 ].flatMap((directory) =>
264 Array.from({ length: 1001 }, (_, index) => `${directory}/pkg-${index}.js`),
265 ),
266 (relativePath) => writeTextFile(cwd, relativePath),
267 { concurrency: 32, discard: true },
268 );
269 for (const relativePath of [
270 "dist/kept.js",
271 "dist/vendored/index.js",
272 "i/page.tsx",
273 "[id]/page.tsx",
274 "src/bundle.map",
275 ]) {
276 yield* writeTextFile(cwd, relativePath);
277 }
278 yield* git(cwd, ["add", "-f", "dist/kept.js", "dist/vendored/index.js", "i/page.tsx"]);
279 if (platform !== "win32") {
280 yield* fileSystem.symlink(path.join(cwd, "src"), path.join(cwd, "node_modules/link"));
281 }
282
283 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
284 for (const { directoryPath, ignored, except } of [
285 { directoryPath: "node_modules", ignored: true, except: [] },
286 { directoryPath: "dist", ignored: true, except: ["dist/kept.js", "dist/vendored"] },
287 // git reads `[id]/page.tsx` as a pathspec, which matches the tracked `i/page.tsx`.
288 { directoryPath: "[id]", ignored: true, except: ["[id]/page.tsx"] },
289 { directoryPath: "src", ignored: false, except: ["src/bundle.map"] },
290 ...(platform !== "win32"
291 ? [
292 // git refuses to classify paths beyond a symlink, so nothing there is labelled.
293 { directoryPath: "node_modules/link", ignored: false, except: [] },
294 // Leading : is pathspec magic; Git sees foo/pkg-0.js, unignored by !foo/.
295 { directoryPath: ":foo", ignored: false, except: [] },
296 ]
297 : []),
298 ]) {
299 const { entries } = yield* workspaceEntries.list({ cwd, directoryPath });
300 expect(entries.length, directoryPath).toBeGreaterThan(1000);
301 expect(
302 entries
303 .filter((entry) => (entry.ignored === true) !== ignored)
304 .map((entry) => entry.path)
305 .toSorted(),
306 directoryPath,
307 ).toEqual(except);
308 }
309 }),
310 );
311
312 it.effect("lists a host folder and its parent, each from its own root", () =>
313 Effect.gen(function* () {
314 const parent = yield* makeTempDir();
315 const path = yield* Path.Path;
316 yield* writeTextFile(parent, "linked/notes.md");
317 yield* writeTextFile(parent, "sibling/readme.md");
318 const linked = path.join(parent, "linked");
319
320 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
321 expect(yield* workspaceEntries.list({ cwd: linked, directoryPath: "" })).toEqual({
322 entries: [{ path: "notes.md", kind: "file" }],
323 truncated: false,
324 });
325 const up = yield* workspaceEntries.list({ cwd: parent, directoryPath: "" });
326 expect(up.entries.map((entry) => entry.path).toSorted()).toEqual(["linked", "sibling"]);
327 const escape = yield* workspaceEntries
328 .list({ cwd: linked, directoryPath: "../sibling" })
329 .pipe(Effect.flip);
330 expect(escape._tag).toBe("WorkspaceEntriesReadDirectoryError");
331 }),
332 );
333
334 it.effect(
335 "rejects directory traversal, git internals, and symlinks outside the workspace",
336 () =>
337 Effect.gen(function* () {
338 const cwd = yield* makeTempDir();
339 const outside = yield* makeTempDir();
340 const fileSystem = yield* FileSystem.FileSystem;
341 const path = yield* Path.Path;
342 yield* writeTextFile(cwd, ".git/HEAD");
343 const platform = yield* HostProcess.Platform;
344 if (platform !== "win32") yield* fileSystem.symlink(outside, path.join(cwd, "external"));
345 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
346 for (const directoryPath of [
347 "../",
348 outside,
349 ".git",
350 "missing",
351 ...(platform !== "win32" ? ["external"] : []),
352 ]) {
353 const error = yield* workspaceEntries.list({ cwd, directoryPath }).pipe(Effect.flip);
354 expect(error._tag).toBe("WorkspaceEntriesReadDirectoryError");
355 }
356 }),
357 );
358
359 it.effect("includes images and other binary files in non-git workspace indexes", () =>
360 Effect.gen(function* () {
361 const cwd = yield* makeTempDir();
362 const imagePaths = ["photo.png", "photo.jpg", "photo.jpeg"];
363 const binaryPaths = [...imagePaths, "document.pdf", "archive.zip", "data.bin"];
364 for (const filePath of binaryPaths) {
365 yield* writeTextFile(cwd, filePath, "\0binary contents\n");
366 }
367 yield* writeTextFile(cwd, "notes.txt", "plain text\n");
368
369 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
370 const expectedPaths = [...binaryPaths, "notes.txt"].toSorted();
371 const listed = yield* workspaceEntries.list({ cwd });
372 expect(listed.entries.map((entry) => entry.path).toSorted()).toEqual(expectedPaths);
373 expect(listed.truncated).toBe(false);
374
375 const searched = yield* workspaceEntries.search({
376 cwd,
377 query: "",
378 limit: 100,
379 kind: "file",
380 });
381 expect(searched.entries.map((entry) => entry.path).toSorted()).toEqual(expectedPaths);
382 expect(searched.truncated).toBe(false);
383
384 const images = yield* workspaceEntries.search({
385 cwd,
386 query: "",
387 limit: 100,
388 imageOnly: true,
389 });
390 expect(images.entries.map((entry) => entry.path).toSorted()).toEqual(imagePaths.toSorted());
391 expect(images.truncated).toBe(false);
392 }),
393 );
394 });
395
396 describe("listIgnoredFiles", () => {
397 it.effect("lists ignored files with sizes and skips wholly ignored folders", () =>
398 Effect.gen(function* () {
399 const cwd = yield* makeTempDir({ git: true });
400 yield* writeTextFile(cwd, ".gitignore", "node_modules/\n.env*\n");
401 yield* writeTextFile(cwd, ".env", "A=1");
402 yield* writeTextFile(cwd, "apps/web/index.ts", "y");
403 yield* git(cwd, ["add", "apps/web/index.ts"]);
404 yield* writeTextFile(cwd, "apps/web/.env.local", "B=22");
405 yield* writeTextFile(cwd, "node_modules/pkg/index.js", "x");
406
407 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
408 expect(yield* workspaceEntries.listIgnoredFiles({ cwd })).toEqual({
409 files: [
410 { path: ".env", byteLength: 3 },
411 { path: "apps/web/.env.local", byteLength: 4 },
412 ],
413 truncated: false,
414 });
415 }),
416 );
417 });
418
419 describe("search", () => {
420 it.effect("applies the file filter before limiting search results", () =>
421 Effect.gen(function* () {
422 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-file-limit-" });
423 yield* writeTextFile(cwd, "src/index.ts");
424 yield* writeTextFile(cwd, "src/internal.ts");
425
426 const result = yield* searchWorkspaceEntries({
427 cwd,
428 query: "src",
429 limit: 1,
430 kind: "file",
431 });
432
433 // Native ranking can put either matching file first.
434 expect(result.entries).toHaveLength(1);
435 expect(result.entries[0]?.kind).toBe("file");
436 expect(["src/index.ts", "src/internal.ts"]).toContain(result.entries[0]?.path);
437 expect(result.truncated).toBe(true);
438 }),
439 );
440
441 it.effect("excludes gitignored paths for git repositories", () =>
442 Effect.gen(function* () {
443 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-gitignore-", git: true });
444 yield* writeTextFile(cwd, ".gitignore", ".convex/\nconvex/\nignored.txt\n");
445 yield* writeTextFile(cwd, "src/keep.ts", "export {};");
446 yield* writeTextFile(cwd, "ignored.txt", "ignore me");
447 yield* writeTextFile(cwd, ".convex/local-storage/data.json", "{}");
448 yield* writeTextFile(cwd, "convex/UOoS-l/convex_local_storage/modules/data.json", "{}");
449
450 const result = yield* searchWorkspaceEntries({ cwd, query: "", limit: 100 });
451 const paths = result.entries.map((entry) => entry.path);
452
453 expect(paths).toContain("src");
454 expect(paths).toContain("src/keep.ts");
455 expect(paths).not.toContain("ignored.txt");
456 expect(paths.some((entryPath) => entryPath.startsWith(".convex/"))).toBe(false);
457 expect(paths.some((entryPath) => entryPath.startsWith("convex/"))).toBe(false);
458 }),
459 );
460
461 it.effect("excludes tracked paths that match ignore rules", () =>
462 Effect.gen(function* () {
463 const cwd = yield* makeTempDir({
464 prefix: "t3code-workspace-tracked-gitignore-",
465 git: true,
466 });
467 yield* writeTextFile(cwd, ".convex/local-storage/data.json", "{}");
468 yield* writeTextFile(cwd, "src/keep.ts", "export {};");
469 yield* git(cwd, ["add", ".convex/local-storage/data.json", "src/keep.ts"]);
470 yield* writeTextFile(cwd, ".gitignore", ".convex/\n");
471
472 const result = yield* searchWorkspaceEntries({ cwd, query: "", limit: 100 });
473 const paths = result.entries.map((entry) => entry.path);
474
475 expect(paths).toContain("src");
476 expect(paths).toContain("src/keep.ts");
477 expect(paths.some((entryPath) => entryPath.startsWith(".convex/"))).toBe(false);
478 }),
479 );
480 });
481
482 describe("searchContents", () => {
483 it.effect("returns content matches with file paths, line numbers, and ranges", () =>
484 Effect.gen(function* () {
485 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-search-" });
486 yield* writeTextFile(
487 cwd,
488 "src/shapes.ts",
489 "export const square = 4;\nexport const Square = 16;\nexport const squareSize = 8;\n",
490 );
491 yield* writeTextFile(cwd, "src/other.ts", "const circle = true;\n");
492
493 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
494 const result = yield* workspaceEntries.searchContents({
495 cwd,
496 query: "Square",
497 limit: 100,
498 caseSensitive: false,
499 wholeWord: true,
500 useRegex: false,
501 });
502
503 expect(result.matches.map((match) => [match.path, match.lineNumber])).toEqual([
504 ["src/shapes.ts", 1],
505 ["src/shapes.ts", 2],
506 ]);
507 expect(result.matches[0]?.matchRanges).toEqual([{ start: 13, end: 19 }]);
508 expect(result.truncated).toBe(false);
509 }),
510 );
511
512 it.effect("honors case sensitivity and gitignore rules", () =>
513 Effect.gen(function* () {
514 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-ignore-", git: true });
515 yield* writeTextFile(cwd, ".gitignore", "ignored.txt\n");
516 yield* writeTextFile(cwd, "src/keep.ts", "square\nSquare\n");
517 yield* writeTextFile(cwd, "ignored.txt", "Square\n");
518
519 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
520 const result = yield* workspaceEntries.searchContents({
521 cwd,
522 query: "Square",
523 limit: 100,
524 caseSensitive: true,
525 wholeWord: false,
526 useRegex: false,
527 });
528
529 expect(result.matches).toHaveLength(1);
530 expect(result.matches[0]).toMatchObject({ path: "src/keep.ts", lineNumber: 2 });
531 }),
532 );
533
534 it.effect("finds later whole-word matches in a file after rejected raw matches", () =>
535 Effect.gen(function* () {
536 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-late-whole-word-" });
537 yield* writeTextFile(cwd, "src/words.ts", `${"afoo\n".repeat(10)}foo\n`);
538
539 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
540 const result = yield* workspaceEntries.searchContents({
541 cwd,
542 query: "foo",
543 limit: 1,
544 caseSensitive: true,
545 wholeWord: true,
546 useRegex: false,
547 });
548
549 expect(result.matches).toEqual([
550 expect.objectContaining({
551 path: "src/words.ts",
552 lineNumber: 11,
553 matchRanges: [{ start: 0, end: 3 }],
554 }),
555 ]);
556 }),
557 );
558
559 it.effect("treats astral-plane letters as whole word characters", () =>
560 Effect.gen(function* () {
561 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-astral-word-" });
562 yield* writeTextFile(cwd, "src/words.ts", "𐐀foo foo foo𐐀\n");
563
564 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
565 const result = yield* workspaceEntries.searchContents({
566 cwd,
567 query: "foo",
568 limit: 100,
569 caseSensitive: true,
570 wholeWord: true,
571 useRegex: false,
572 });
573
574 expect(result.matches).toEqual([
575 expect.objectContaining({
576 path: "src/words.ts",
577 lineNumber: 1,
578 matchRanges: [{ start: 6, end: 9 }],
579 }),
580 ]);
581 }),
582 );
583
584 it.effect("matches punctuation-edged whole-word queries including adjacent occurrences", () =>
585 Effect.gen(function* () {
586 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-punctuation-" });
587 yield* writeTextFile(cwd, "src/words.ts", "-foo- -foo- -foo-\n");
588
589 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
590 const result = yield* workspaceEntries.searchContents({
591 cwd,
592 query: "-foo-",
593 limit: 100,
594 caseSensitive: true,
595 wholeWord: true,
596 useRegex: false,
597 });
598
599 expect(result.matches).toHaveLength(1);
600 expect(result.matches[0]).toMatchObject({
601 path: "src/words.ts",
602 lineNumber: 1,
603 matchRanges: [
604 { start: 0, end: 5 },
605 { start: 6, end: 11 },
606 { start: 12, end: 17 },
607 ],
608 });
609 }),
610 );
611
612 it.effect("caps matches per file so one dense file cannot fill the page", () =>
613 Effect.gen(function* () {
614 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-per-file-cap-" });
615 yield* writeTextFile(cwd, "src/dense.ts", "needle\n".repeat(300));
616 yield* writeTextFile(cwd, "src/other.ts", "needle\n");
617
618 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
619 const result = yield* workspaceEntries.searchContents({
620 cwd,
621 query: "needle",
622 limit: 500,
623 caseSensitive: true,
624 wholeWord: false,
625 useRegex: false,
626 });
627
628 const byPath = new Map<string, number>();
629 for (const match of result.matches) {
630 byPath.set(match.path, (byPath.get(match.path) ?? 0) + 1);
631 }
632 expect(byPath.get("src/dense.ts")).toBe(100);
633 expect(byPath.get("src/other.ts")).toBe(1);
634 }),
635 );
636
637 it.effect("preserves regex escapes during case-insensitive searches", () =>
638 Effect.gen(function* () {
639 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-regex-" });
640 yield* writeTextFile(cwd, "src/shapes.ts", "Square\nsquare\n");
641
642 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
643 const result = yield* workspaceEntries.searchContents({
644 cwd,
645 query: "\\SQUARE",
646 limit: 100,
647 caseSensitive: false,
648 wholeWord: false,
649 useRegex: true,
650 });
651
652 expect(result.matches.map((match) => match.lineNumber)).toEqual([1, 2]);
653 }),
654 );
655
656 it.effect("maps multi-byte lines to string-indexed ranges", () =>
657 Effect.gen(function* () {
658 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-multibyte-" });
659 yield* writeTextFile(cwd, "src/notes.ts", 'const label = "héllo wörld";\n');
660
661 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
662 const result = yield* workspaceEntries.searchContents({
663 cwd,
664 query: "wörld",
665 limit: 100,
666 caseSensitive: true,
667 wholeWord: false,
668 useRegex: false,
669 });
670
671 expect(result.matches).toHaveLength(1);
672 const match = result.matches[0]!;
673 const range = match.matchRanges[0]!;
674 expect(match.lineContent.slice(range.start, range.end)).toBe("wörld");
675 }),
676 );
677
678 it.effect("keeps answering from the live index when a refresh outlasts the scan wait", () =>
679 Effect.gen(function* () {
680 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-refresh-" });
681 yield* writeTextFile(cwd, "src/notes.ts", "const needle = 1;\n");
682 let scansOutlastWait = false;
683 let finders = 0;
684 let rescans = 0;
685 const createFinder = FileFinder.create.bind(FileFinder);
686 vi.spyOn(FileFinder, "create").mockImplementation((options) => {
687 const created = createFinder(options);
688 if (created.ok) {
689 const finder = created.value;
690 finders += 1;
691 const scanFiles = finder.scanFiles.bind(finder);
692 finder.scanFiles = () => {
693 rescans += 1;
694 return scanFiles();
695 };
696 const waitForIndexReady = finder.waitForIndexReady.bind(finder);
697 finder.waitForIndexReady = (timeoutMs) =>
698 scansOutlastWait
699 ? Promise.resolve({ ok: true, value: false })
700 : waitForIndexReady(timeoutMs);
701 }
702 return created;
703 });
704 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
705 const searchNeedle = workspaceEntries.searchContents({
706 cwd,
707 query: "needle",
708 limit: 100,
709 caseSensitive: true,
710 wholeWord: false,
711 useRegex: false,
712 });
713 yield* searchNeedle;
714
715 scansOutlastWait = true;
716 yield* workspaceEntries.refresh(cwd);
717 const result = yield* searchNeedle;
718
719 expect(result.matches.map((match) => match.path)).toEqual(["src/notes.ts"]);
720 // The second search ran on the rescanned live finder, not a rebuild.
721 expect({ finders, rescans }).toEqual({ finders: 1, rescans: 1 });
722 }),
723 );
724 });
725
726 describe("browse", () => {
727 it.effect("shows dot directories in directory mode and hidden-prefix mode", () =>
728 Effect.gen(function* () {
729 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
730 const path = yield* Path.Path;
731 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-browse-hidden-" });
732 yield* writeTextFile(cwd, ".config/settings.json", "{}");
733 yield* writeTextFile(cwd, "config/settings.json", "{}");
734 const cwdWithSeparator = yield* appendSeparator(cwd);
735
736 const directoryResult = yield* workspaceEntries.browse({
737 partialPath: cwdWithSeparator,
738 });
739 const hiddenPrefixResult = yield* workspaceEntries.browse({
740 partialPath: `${cwdWithSeparator}.c`,
741 });
742
743 expect(directoryResult.entries.map((entry) => entry.name)).toEqual([".config", "config"]);
744 expect(hiddenPrefixResult).toEqual({
745 parentPath: cwd,
746 entries: [{ name: ".config", fullPath: path.join(cwd, ".config") }],
747 });
748 }),
749 );
750 });
751});