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

WorkspaceEntries.test.ts

844 lines33.2 KB

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 });
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 yield* git(cwd, ["init", "sub"]);
112 yield* writeTextFile(cwd, "sub/.gitignore", "dist/\n");
113 yield* writeTextFile(cwd, "sub/dist/out.js");
114 const gitlink = yield* git(cwd, ["hash-object", "tracked.txt"]);
115 yield* git(cwd, ["update-index", "--add", "--cacheinfo", `160000,${gitlink},sub`]);
116 // A nested clone that isn't a submodule keeps the outer repository's ignore rules.
117 yield* git(cwd, ["init", "node_modules/pkg"]);
118 yield* git(cwd, ["init", "sub/dist"]);
119​
120 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
121 const root = yield* workspaceEntries.list({ cwd, directoryPath: "" });
122 expect(root.entries).toEqual(
123 expect.arrayContaining([
124 { path: ".env", kind: "file", ignored: true },
125 { path: "node_modules", kind: "directory", ignored: true },
126 { path: "src", kind: "directory" },
127 { path: "empty", kind: "directory" },
128 { path: "tracked.txt", kind: "file" },
129 ]),
130 );
131 expect(root.entries.some((entry) => entry.path.includes("/"))).toBe(false);
132 expect(root.entries.some((entry) => entry.path === ".git")).toBe(false);
133 expect(root.truncated).toBe(false);
134 expect(yield* workspaceEntries.list({ cwd, directoryPath: "node_modules/pkg" })).toEqual({
135 entries: [{ path: "node_modules/pkg/index.js", kind: "file", ignored: true }],
136 truncated: false,
137 });
138 // Git refuses pathspecs inside a submodule from the outer repository.
139 expect((yield* workspaceEntries.list({ cwd, directoryPath: "sub" })).entries).toEqual(
140 expect.arrayContaining([
141 { path: "sub/.gitignore", kind: "file" },
142 { path: "sub/dist", kind: "directory", ignored: true },
143 ]),
144 );
145 expect(yield* workspaceEntries.list({ cwd, directoryPath: "sub/dist" })).toEqual({
146 entries: [{ path: "sub/dist/out.js", kind: "file", ignored: true }],
147 truncated: false,
148 });
149 expect(yield* workspaceEntries.list({ cwd, directoryPath: "empty" })).toEqual({
150 entries: [],
151 truncated: false,
152 });
153 }),
154 );
155​
156 it.effect("lists symlinks as what they point to, hiding ones that cannot be opened", () =>
157 Effect.gen(function* () {
158 const platform = yield* HostProcess.Platform;
159 if (platform === "win32") return;
160 const cwd = yield* makeTempDir({ git: true });
161 const outside = yield* makeTempDir();
162 const fileSystem = yield* FileSystem.FileSystem;
163 const path = yield* Path.Path;
164 yield* writeTextFile(cwd, "real.txt");
165 yield* writeTextFile(cwd, "realdir/nested.txt");
166 yield* writeTextFile(outside, "outside.txt");
167 yield* fileSystem.symlink("real.txt", path.join(cwd, "link.txt"));
168 yield* fileSystem.symlink("realdir", path.join(cwd, "linkdir"));
169 yield* fileSystem.symlink(outside, path.join(cwd, "outside-link"));
170 yield* fileSystem.symlink(".git", path.join(cwd, "git-link"));
171 yield* fileSystem.symlink("missing", path.join(cwd, "dangling"));
172​
173 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
174 const root = yield* workspaceEntries.list({ cwd, directoryPath: "" });
175 expect(root.entries.toSorted((a, b) => a.path.localeCompare(b.path))).toEqual([
176 { path: "link.txt", kind: "file" },
177 { path: "linkdir", kind: "directory" },
178 { path: "real.txt", kind: "file" },
179 { path: "realdir", kind: "directory" },
180 ]);
181 expect(yield* workspaceEntries.list({ cwd, directoryPath: "linkdir" })).toEqual({
182 entries: [{ path: "linkdir/nested.txt", kind: "file" }],
183 truncated: false,
184 });
185 }),
186 );
187​
188 it.effect("hides folder links that lead back to a folder on the listed path", () =>
189 // "Expand all folders" loads every folder it expands, so a link that loops would
190 // keep nesting the same entries without end.
191 Effect.gen(function* () {
192 const platform = yield* HostProcess.Platform;
193 if (platform === "win32") return;
194 const cwd = yield* makeTempDir();
195 const fileSystem = yield* FileSystem.FileSystem;
196 const path = yield* Path.Path;
197 yield* writeTextFile(cwd, "a/file.txt");
198 yield* writeTextFile(cwd, "b/file.txt");
199 yield* fileSystem.symlink(".", path.join(cwd, "self"));
200 yield* fileSystem.symlink("..", path.join(cwd, "a/up"));
201 yield* fileSystem.symlink("../b", path.join(cwd, "a/to-b"));
202 yield* fileSystem.symlink("../a", path.join(cwd, "b/to-a"));
203​
204 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
205 const paths = (directoryPath: string) =>
206 workspaceEntries
207 .list({ cwd, directoryPath })
208 .pipe(Effect.map(({ entries }) => entries.map((entry) => entry.path).toSorted()));
209 expect(yield* paths("")).toEqual(["a", "b"]);
210 // A link into a sibling folder is fine on its own...
211 expect(yield* paths("a")).toEqual(["a/file.txt", "a/to-b"]);
212 // ...but once followed, the sibling's link back is hidden.
213 expect(yield* paths("a/to-b")).toEqual(["a/to-b/file.txt"]);
214 }),
215 );
216​
217 it.effect("resolves a folder of many symlinks in bounded batches", () =>
218 Effect.gen(function* () {
219 const platform = yield* HostProcess.Platform;
220 if (platform === "win32") return;
221 const cwd = yield* makeTempDir();
222 const fileSystem = yield* FileSystem.FileSystem;
223 const path = yield* Path.Path;
224 // Shaped like a pnpm `node_modules`: one link per package into `.pnpm`.
225 const directoryPath = [...Array.from({ length: 80 }, () => "nested"), "node_modules"].join(
226 "/",
227 );
228 const packages = Array.from({ length: 200 }, (_, index) => `pkg-${index}`);
229 yield* Effect.forEach(
230 packages,
231 (name) =>
232 Effect.gen(function* () {
233 yield* writeTextFile(cwd, `${directoryPath}/.pnpm/${name}/index.js`);
234 yield* fileSystem.symlink(`.pnpm/${name}`, path.join(cwd, directoryPath, name));
235 }),
236 { concurrency: 32, discard: true },
237 );
238 const realpath = NodeFSP.realpath;
239 let inFlight = 0;
240 let maxInFlight = 0;
241 vi.spyOn(NodeFSP, "realpath").mockImplementation((async (target: string) => {
242 maxInFlight = Math.max(maxInFlight, ++inFlight);
243 try {
244 return await realpath(target);
245 } finally {
246 inFlight--;
247 }
248 }) as typeof NodeFSP.realpath);
249​
250 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
251 const { entries } = yield* workspaceEntries.list({ cwd, directoryPath });
252 expect(entries.map((entry) => entry.path).toSorted()).toEqual(
253 [
254 `${directoryPath}/.pnpm`,
255 ...packages.map((name) => `${directoryPath}/${name}`),
256 ].toSorted(),
257 );
258 expect(entries.every((entry) => entry.kind === "directory")).toBe(true);
259 expect(maxInFlight).toBeLessThanOrEqual(64);
260 }),
261 );
262​
263 it.effect("labels the children of wide folders exactly as git does for each child", () =>
264 Effect.gen(function* () {
265 // Above 1,000 children, listing first asks whether the whole folder is ignored.
266 const cwd = yield* makeTempDir({ git: true });
267 const fileSystem = yield* FileSystem.FileSystem;
268 const path = yield* Path.Path;
269 const platform = yield* HostProcess.Platform;
270 yield* writeTextFile(
271 cwd,
272 ".gitignore",
273 "node_modules/\ndist/\n\\[id\\]/\n*.map\nfoo\n!foo/\n",
274 );
275 yield* Effect.forEach(
276 [
277 "node_modules",
278 "dist",
279 "[id]",
280 "src",
281 ...(platform !== "win32" ? [":foo"] : []),
282 ].flatMap((directory) =>
283 Array.from({ length: 1001 }, (_, index) => `${directory}/pkg-${index}.js`),
284 ),
285 (relativePath) => writeTextFile(cwd, relativePath),
286 { concurrency: 32, discard: true },
287 );
288 for (const relativePath of [
289 "dist/kept.js",
290 "dist/vendored/index.js",
291 "i/page.tsx",
292 "[id]/page.tsx",
293 "src/bundle.map",
294 ]) {
295 yield* writeTextFile(cwd, relativePath);
296 }
297 yield* git(cwd, ["add", "-f", "dist/kept.js", "dist/vendored/index.js", "i/page.tsx"]);
298 if (platform !== "win32") {
299 yield* fileSystem.symlink(path.join(cwd, "src"), path.join(cwd, "node_modules/link"));
300 }
301​
302 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
303 for (const { directoryPath, ignored, except } of [
304 { directoryPath: "node_modules", ignored: true, except: [] },
305 { directoryPath: "dist", ignored: true, except: ["dist/kept.js", "dist/vendored"] },
306 // git reads `[id]/page.tsx` as a pathspec, which matches the tracked `i/page.tsx`.
307 { directoryPath: "[id]", ignored: true, except: ["[id]/page.tsx"] },
308 { directoryPath: "src", ignored: false, except: ["src/bundle.map"] },
309 ...(platform !== "win32"
310 ? [
311 // git refuses to classify paths beyond a symlink, so nothing there is labelled.
312 { directoryPath: "node_modules/link", ignored: false, except: [] },
313 // Leading : is pathspec magic; Git sees foo/pkg-0.js, unignored by !foo/.
314 { directoryPath: ":foo", ignored: false, except: [] },
315 ]
316 : []),
317 ]) {
318 const { entries } = yield* workspaceEntries.list({ cwd, directoryPath });
319 expect(entries.length, directoryPath).toBeGreaterThan(1000);
320 expect(
321 entries
322 .filter((entry) => (entry.ignored === true) !== ignored)
323 .map((entry) => entry.path)
324 .toSorted(),
325 directoryPath,
326 ).toEqual(except);
327 }
328 }),
329 );
330​
331 it.effect("lists a host folder and its parent, each from its own root", () =>
332 Effect.gen(function* () {
333 const parent = yield* makeTempDir();
334 const path = yield* Path.Path;
335 yield* writeTextFile(parent, "linked/notes.md");
336 yield* writeTextFile(parent, "sibling/readme.md");
337 const linked = path.join(parent, "linked");
338​
339 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
340 expect(yield* workspaceEntries.list({ cwd: linked, directoryPath: "" })).toEqual({
341 entries: [{ path: "notes.md", kind: "file" }],
342 truncated: false,
343 });
344 const up = yield* workspaceEntries.list({ cwd: parent, directoryPath: "" });
345 expect(up.entries.map((entry) => entry.path).toSorted()).toEqual(["linked", "sibling"]);
346 const escape = yield* workspaceEntries
347 .list({ cwd: linked, directoryPath: "../sibling" })
348 .pipe(Effect.flip);
349 expect(escape._tag).toBe("WorkspaceEntriesReadDirectoryError");
350 }),
351 );
352​
353 it.effect(
354 "rejects directory traversal, git internals, and symlinks outside the workspace",
355 () =>
356 Effect.gen(function* () {
357 const cwd = yield* makeTempDir();
358 const outside = yield* makeTempDir();
359 const fileSystem = yield* FileSystem.FileSystem;
360 const path = yield* Path.Path;
361 yield* writeTextFile(cwd, ".git/HEAD");
362 const platform = yield* HostProcess.Platform;
363 if (platform !== "win32") yield* fileSystem.symlink(outside, path.join(cwd, "external"));
364 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
365 for (const directoryPath of [
366 "../",
367 outside,
368 ".git",
369 "missing",
370 ...(platform !== "win32" ? ["external"] : []),
371 ]) {
372 const error = yield* workspaceEntries.list({ cwd, directoryPath }).pipe(Effect.flip);
373 expect(error._tag).toBe("WorkspaceEntriesReadDirectoryError");
374 }
375 }),
376 );
377​
378 it.effect("includes images and other binary files in non-git workspace indexes", () =>
379 Effect.gen(function* () {
380 const cwd = yield* makeTempDir();
381 const imagePaths = ["photo.png", "photo.jpg", "photo.jpeg"];
382 const binaryPaths = [...imagePaths, "document.pdf", "archive.zip", "data.bin"];
383 for (const filePath of binaryPaths) {
384 yield* writeTextFile(cwd, filePath, "\0binary contents\n");
385 }
386 yield* writeTextFile(cwd, "notes.txt", "plain text\n");
387​
388 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
389 const expectedPaths = [...binaryPaths, "notes.txt"].toSorted();
390 const listed = yield* workspaceEntries.list({ cwd });
391 expect(listed.entries.map((entry) => entry.path).toSorted()).toEqual(expectedPaths);
392 expect(listed.truncated).toBe(false);
393​
394 const searched = yield* workspaceEntries.search({
395 cwd,
396 query: "",
397 limit: 100,
398 kind: "file",
399 });
400 expect(searched.entries.map((entry) => entry.path).toSorted()).toEqual(expectedPaths);
401 expect(searched.truncated).toBe(false);
402​
403 const images = yield* workspaceEntries.search({
404 cwd,
405 query: "",
406 limit: 100,
407 imageOnly: true,
408 });
409 expect(images.entries.map((entry) => entry.path).toSorted()).toEqual(imagePaths.toSorted());
410 expect(images.truncated).toBe(false);
411 }),
412 );
413 });
414​
415 describe("listIgnoredFiles", () => {
416 it.effect("lists ignored files with sizes and skips wholly ignored folders", () =>
417 Effect.gen(function* () {
418 const cwd = yield* makeTempDir({ git: true });
419 yield* writeTextFile(cwd, ".gitignore", "node_modules/\n.env*\n");
420 yield* writeTextFile(cwd, ".env", "A=1");
421 yield* writeTextFile(cwd, "apps/web/index.ts", "y");
422 yield* git(cwd, ["add", "apps/web/index.ts"]);
423 yield* writeTextFile(cwd, "apps/web/.env.local", "B=22");
424 yield* writeTextFile(cwd, "node_modules/pkg/index.js", "x");
425​
426 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
427 expect(yield* workspaceEntries.listIgnoredFiles({ cwd })).toEqual({
428 files: [
429 { path: ".env", byteLength: 3 },
430 { path: "apps/web/.env.local", byteLength: 4 },
431 ],
432 truncated: false,
433 });
434 }),
435 );
436 });
437​
438 describe("search", () => {
439 it.effect("applies the file filter before limiting search results", () =>
440 Effect.gen(function* () {
441 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-file-limit-" });
442 yield* writeTextFile(cwd, "src/index.ts");
443 yield* writeTextFile(cwd, "src/internal.ts");
444​
445 const result = yield* searchWorkspaceEntries({
446 cwd,
447 query: "src",
448 limit: 1,
449 kind: "file",
450 });
451​
452 // Native ranking can put either matching file first.
453 expect(result.entries).toHaveLength(1);
454 expect(result.entries[0]?.kind).toBe("file");
455 expect(["src/index.ts", "src/internal.ts"]).toContain(result.entries[0]?.path);
456 expect(result.truncated).toBe(true);
457 }),
458 );
459​
460 it.effect("excludes gitignored paths for git repositories", () =>
461 Effect.gen(function* () {
462 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-gitignore-", git: true });
463 yield* writeTextFile(cwd, ".gitignore", ".convex/\nconvex/\nignored.txt\n");
464 yield* writeTextFile(cwd, "src/keep.ts", "export {};");
465 yield* writeTextFile(cwd, "ignored.txt", "ignore me");
466 yield* writeTextFile(cwd, ".convex/local-storage/data.json", "{}");
467 yield* writeTextFile(cwd, "convex/UOoS-l/convex_local_storage/modules/data.json", "{}");
468​
469 const result = yield* searchWorkspaceEntries({ cwd, query: "", limit: 100 });
470 const paths = result.entries.map((entry) => entry.path);
471​
472 expect(paths).toContain("src");
473 expect(paths).toContain("src/keep.ts");
474 expect(paths).not.toContain("ignored.txt");
475 expect(paths.some((entryPath) => entryPath.startsWith(".convex/"))).toBe(false);
476 expect(paths.some((entryPath) => entryPath.startsWith("convex/"))).toBe(false);
477 }),
478 );
479​
480 it.effect("excludes tracked paths that match ignore rules", () =>
481 Effect.gen(function* () {
482 const cwd = yield* makeTempDir({
483 prefix: "t3code-workspace-tracked-gitignore-",
484 git: true,
485 });
486 yield* writeTextFile(cwd, ".convex/local-storage/data.json", "{}");
487 yield* writeTextFile(cwd, "src/keep.ts", "export {};");
488 yield* git(cwd, ["add", ".convex/local-storage/data.json", "src/keep.ts"]);
489 yield* writeTextFile(cwd, ".gitignore", ".convex/\n");
490​
491 const result = yield* searchWorkspaceEntries({ cwd, query: "", limit: 100 });
492 const paths = result.entries.map((entry) => entry.path);
493​
494 expect(paths).toContain("src");
495 expect(paths).toContain("src/keep.ts");
496 expect(paths.some((entryPath) => entryPath.startsWith(".convex/"))).toBe(false);
497 }),
498 );
499 });
500​
501 describe("searchContents", () => {
502 it.effect("returns content matches with file paths, line numbers, and ranges", () =>
503 Effect.gen(function* () {
504 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-search-" });
505 yield* writeTextFile(
506 cwd,
507 "src/shapes.ts",
508 "export const square = 4;\nexport const Square = 16;\nexport const squareSize = 8;\n",
509 );
510 yield* writeTextFile(cwd, "src/other.ts", "const circle = true;\n");
511​
512 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
513 const result = yield* workspaceEntries.searchContents({
514 cwd,
515 query: "Square",
516 limit: 100,
517 caseSensitive: false,
518 wholeWord: true,
519 useRegex: false,
520 });
521​
522 expect(result.matches.map((match) => [match.path, match.lineNumber])).toEqual([
523 ["src/shapes.ts", 1],
524 ["src/shapes.ts", 2],
525 ]);
526 expect(result.matches[0]?.matchRanges).toEqual([{ start: 13, end: 19 }]);
527 expect(result.truncated).toBe(false);
528 }),
529 );
530​
531 it.effect("honors case sensitivity and gitignore rules", () =>
532 Effect.gen(function* () {
533 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-ignore-", git: true });
534 yield* writeTextFile(cwd, ".gitignore", "ignored.txt\n");
535 yield* writeTextFile(cwd, "src/keep.ts", "square\nSquare\n");
536 yield* writeTextFile(cwd, "ignored.txt", "Square\n");
537​
538 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
539 const result = yield* workspaceEntries.searchContents({
540 cwd,
541 query: "Square",
542 limit: 100,
543 caseSensitive: true,
544 wholeWord: false,
545 useRegex: false,
546 });
547​
548 expect(result.matches).toHaveLength(1);
549 expect(result.matches[0]).toMatchObject({ path: "src/keep.ts", lineNumber: 2 });
550 }),
551 );
552​
553 it.effect("finds later whole-word matches in a file after rejected raw matches", () =>
554 Effect.gen(function* () {
555 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-late-whole-word-" });
556 yield* writeTextFile(cwd, "src/words.ts", `${"afoo\n".repeat(10)}foo\n`);
557​
558 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
559 const result = yield* workspaceEntries.searchContents({
560 cwd,
561 query: "foo",
562 limit: 1,
563 caseSensitive: true,
564 wholeWord: true,
565 useRegex: false,
566 });
567​
568 expect(result.matches).toEqual([
569 expect.objectContaining({
570 path: "src/words.ts",
571 lineNumber: 11,
572 matchRanges: [{ start: 0, end: 3 }],
573 }),
574 ]);
575 }),
576 );
577​
578 it.effect("treats astral-plane letters as whole word characters", () =>
579 Effect.gen(function* () {
580 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-astral-word-" });
581 yield* writeTextFile(cwd, "src/words.ts", "𐐀foo foo foo𐐀\n");
582​
583 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
584 const result = yield* workspaceEntries.searchContents({
585 cwd,
586 query: "foo",
587 limit: 100,
588 caseSensitive: true,
589 wholeWord: true,
590 useRegex: false,
591 });
592​
593 expect(result.matches).toEqual([
594 expect.objectContaining({
595 path: "src/words.ts",
596 lineNumber: 1,
597 matchRanges: [{ start: 6, end: 9 }],
598 }),
599 ]);
600 }),
601 );
602​
603 it.effect("matches punctuation-edged whole-word queries including adjacent occurrences", () =>
604 Effect.gen(function* () {
605 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-punctuation-" });
606 yield* writeTextFile(cwd, "src/words.ts", "-foo- -foo- -foo-\n");
607​
608 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
609 const result = yield* workspaceEntries.searchContents({
610 cwd,
611 query: "-foo-",
612 limit: 100,
613 caseSensitive: true,
614 wholeWord: true,
615 useRegex: false,
616 });
617​
618 expect(result.matches).toHaveLength(1);
619 expect(result.matches[0]).toMatchObject({
620 path: "src/words.ts",
621 lineNumber: 1,
622 matchRanges: [
623 { start: 0, end: 5 },
624 { start: 6, end: 11 },
625 { start: 12, end: 17 },
626 ],
627 });
628 }),
629 );
630​
631 it.effect("caps matches per file so one dense file cannot fill the page", () =>
632 Effect.gen(function* () {
633 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-per-file-cap-" });
634 yield* writeTextFile(cwd, "src/dense.ts", "needle\n".repeat(300));
635 yield* writeTextFile(cwd, "src/other.ts", "needle\n");
636​
637 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
638 const result = yield* workspaceEntries.searchContents({
639 cwd,
640 query: "needle",
641 limit: 500,
642 caseSensitive: true,
643 wholeWord: false,
644 useRegex: false,
645 });
646​
647 const byPath = new Map<string, number>();
648 for (const match of result.matches) {
649 byPath.set(match.path, (byPath.get(match.path) ?? 0) + 1);
650 }
651 expect(byPath.get("src/dense.ts")).toBe(100);
652 expect(byPath.get("src/other.ts")).toBe(1);
653 }),
654 );
655​
656 it.effect("preserves regex escapes during case-insensitive searches", () =>
657 Effect.gen(function* () {
658 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-regex-" });
659 yield* writeTextFile(cwd, "src/shapes.ts", "Square\nsquare\n");
660​
661 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
662 const result = yield* workspaceEntries.searchContents({
663 cwd,
664 query: "\\SQUARE",
665 limit: 100,
666 caseSensitive: false,
667 wholeWord: false,
668 useRegex: true,
669 });
670​
671 expect(result.matches.map((match) => match.lineNumber)).toEqual([1, 2]);
672 }),
673 );
674​
675 it.effect("searches an invalid regex literally without matching case", () =>
676 Effect.gen(function* () {
677 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-invalid-regex-" });
678 yield* writeTextFile(cwd, "src/calls.ts", "call(Foo(bar));\n");
679​
680 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
681 const result = yield* workspaceEntries.searchContents({
682 cwd,
683 query: "foo(",
684 limit: 100,
685 caseSensitive: false,
686 wholeWord: false,
687 useRegex: true,
688 });
689​
690 expect(result.regexFallbackError).toBeDefined();
691 expect(result.matches).toEqual([
692 expect.objectContaining({
693 path: "src/calls.ts",
694 lineNumber: 1,
695 matchRanges: [{ start: 5, end: 9 }],
696 }),
697 ]);
698 }),
699 );
700​
701 it.effect("maps multi-byte lines to string-indexed ranges", () =>
702 Effect.gen(function* () {
703 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-multibyte-" });
704 yield* writeTextFile(cwd, "src/notes.ts", 'const label = "héllo wörld";\n');
705​
706 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
707 const result = yield* workspaceEntries.searchContents({
708 cwd,
709 query: "wörld",
710 limit: 100,
711 caseSensitive: true,
712 wholeWord: false,
713 useRegex: false,
714 });
715​
716 expect(result.matches).toHaveLength(1);
717 const match = result.matches[0]!;
718 const range = match.matchRanges[0]!;
719 expect(match.lineContent.slice(range.start, range.end)).toBe("wörld");
720 }),
721 );
722​
723 it.effect("keeps matches past the truncated part of a long line", () =>
724 Effect.gen(function* () {
725 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-long-line-" });
726 yield* writeTextFile(cwd, "dist/app.min.js", `${"x".repeat(600)} needleSuffix\n`);
727​
728 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
729 const search = (wholeWord: boolean) =>
730 workspaceEntries.searchContents({
731 cwd,
732 query: "needle",
733 limit: 100,
734 caseSensitive: true,
735 wholeWord,
736 useRegex: false,
737 });
738​
739 expect((yield* search(false)).matches).toEqual([
740 expect.objectContaining({ path: "dist/app.min.js", lineNumber: 1 }),
741 ]);
742 expect((yield* search(true)).matches).toEqual([]);
743 }),
744 );
745​
746 it.effect("keeps answering from the live index when a refresh outlasts the scan wait", () =>
747 Effect.gen(function* () {
748 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-refresh-" });
749 yield* writeTextFile(cwd, "src/notes.ts", "const needle = 1;\n");
750 let scansOutlastWait = false;
751 let finders = 0;
752 let rescans = 0;
753 const createFinder = FileFinder.create.bind(FileFinder);
754 vi.spyOn(FileFinder, "create").mockImplementation((options) => {
755 const created = createFinder(options);
756 if (created.ok) {
757 const finder = created.value;
758 finders += 1;
759 const scanFiles = finder.scanFiles.bind(finder);
760 finder.scanFiles = () => {
761 rescans += 1;
762 return scanFiles();
763 };
764 const waitForIndexReady = finder.waitForIndexReady.bind(finder);
765 finder.waitForIndexReady = (timeoutMs) =>
766 scansOutlastWait
767 ? Promise.resolve({ ok: true, value: false })
768 : waitForIndexReady(timeoutMs);
769 }
770 return created;
771 });
772 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
773 const searchNeedle = workspaceEntries.searchContents({
774 cwd,
775 query: "needle",
776 limit: 100,
777 caseSensitive: true,
778 wholeWord: false,
779 useRegex: false,
780 });
781 yield* searchNeedle;
782​
783 scansOutlastWait = true;
784 yield* workspaceEntries.refresh(cwd);
785 const result = yield* searchNeedle;
786​
787 expect(result.matches.map((match) => match.path)).toEqual(["src/notes.ts"]);
788 // The second search ran on the rescanned live finder, not a rebuild.
789 expect({ finders, rescans }).toEqual({ finders: 1, rescans: 1 });
790 }),
791 );
792 });
793​
794 describe("browse", () => {
795 it.effect("shows dot directories in directory mode and hidden-prefix mode", () =>
796 Effect.gen(function* () {
797 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
798 const path = yield* Path.Path;
799 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-browse-hidden-" });
800 yield* writeTextFile(cwd, ".config/settings.json", "{}");
801 yield* writeTextFile(cwd, "config/settings.json", "{}");
802 const cwdWithSeparator = yield* appendSeparator(cwd);
803​
804 const directoryResult = yield* workspaceEntries.browse({
805 partialPath: cwdWithSeparator,
806 });
807 const hiddenPrefixResult = yield* workspaceEntries.browse({
808 partialPath: `${cwdWithSeparator}.c`,
809 });
810​
811 expect(directoryResult.entries.map((entry) => entry.name)).toEqual([".config", "config"]);
812 expect(hiddenPrefixResult).toEqual({
813 parentPath: cwd,
814 entries: [{ name: ".config", fullPath: path.join(cwd, ".config") }],
815 });
816 }),
817 );
818​
819 it.effect("marks only a missing directory as missing when browsing fails", () =>
820 Effect.gen(function* () {
821 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
822 const path = yield* Path.Path;
823 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-browse-missing-" });
824 yield* writeTextFile(cwd, "file.txt", "");
825​
826 const missing = yield* workspaceEntries
827 .browse({ partialPath: `${path.join(cwd, "absent", "nested")}${path.sep}` })
828 .pipe(Effect.flip);
829 const underFile = yield* workspaceEntries
830 .browse({ partialPath: `${path.join(cwd, "file.txt")}${path.sep}` })
831 .pipe(Effect.flip);
832​
833 expect(missing).toMatchObject({
834 _tag: "WorkspaceEntriesReadDirectoryError",
835 pathMissing: true,
836 });
837 expect(underFile).toMatchObject({
838 _tag: "WorkspaceEntriesReadDirectoryError",
839 pathMissing: false,
840 });
841 }),
842 );
843 });
844});