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

WorkspaceEntries.test.ts

905 lines35.9 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("matches glob metacharacters in the query literally", () =>
461 Effect.gen(function* () {
462 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-brackets-" });
463 yield* writeTextFile(cwd, "src/app/game/[id]/index.tsx");
464 yield* writeTextFile(cwd, "src/foo{bar}.ts");
465 yield* writeTextFile(cwd, "src/main.ts");
466 yield* writeTextFile(cwd, "src/notes.md");
467​
468 const search = (query: string) =>
469 searchWorkspaceEntries({ cwd, query, limit: 10 }).pipe(
470 Effect.map((result) => result.entries.map((entry) => entry.path)),
471 );
472​
473 for (const query of ["game/[i", "game/[id]"]) {
474 expect(yield* search(query)).toContain("src/app/game/[id]/index.tsx");
475 }
476 expect(yield* search("foo{bar}.ts")).toContain("src/foo{bar}.ts");
477 expect((yield* search("*.{ts,tsx}")).toSorted()).toEqual([
478 "src/app/game/[id]/index.tsx",
479 "src/foo{bar}.ts",
480 "src/main.ts",
481 ]);
482 expect((yield* search("*.{ts}")).toSorted()).toEqual(["src/foo{bar}.ts", "src/main.ts"]);
483 expect(yield* search("src/{main}.ts")).toEqual(["src/main.ts"]);
484 expect(yield* search("src/{foo{bar},notes}.md")).toEqual(["src/notes.md"]);
485 }),
486 );
487​
488 it.effect("excludes gitignored paths for git repositories", () =>
489 Effect.gen(function* () {
490 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-gitignore-", git: true });
491 yield* writeTextFile(cwd, ".gitignore", ".convex/\nconvex/\nignored.txt\n");
492 yield* writeTextFile(cwd, "src/keep.ts", "export {};");
493 yield* writeTextFile(cwd, "ignored.txt", "ignore me");
494 yield* writeTextFile(cwd, ".convex/local-storage/data.json", "{}");
495 yield* writeTextFile(cwd, "convex/UOoS-l/convex_local_storage/modules/data.json", "{}");
496​
497 const result = yield* searchWorkspaceEntries({ cwd, query: "", limit: 100 });
498 const paths = result.entries.map((entry) => entry.path);
499​
500 expect(paths).toContain("src");
501 expect(paths).toContain("src/keep.ts");
502 expect(paths).not.toContain("ignored.txt");
503 expect(paths.some((entryPath) => entryPath.startsWith(".convex/"))).toBe(false);
504 expect(paths.some((entryPath) => entryPath.startsWith("convex/"))).toBe(false);
505 }),
506 );
507​
508 it.effect("excludes tracked paths that match ignore rules", () =>
509 Effect.gen(function* () {
510 const cwd = yield* makeTempDir({
511 prefix: "t3code-workspace-tracked-gitignore-",
512 git: true,
513 });
514 yield* writeTextFile(cwd, ".convex/local-storage/data.json", "{}");
515 yield* writeTextFile(cwd, "src/keep.ts", "export {};");
516 yield* git(cwd, ["add", ".convex/local-storage/data.json", "src/keep.ts"]);
517 yield* writeTextFile(cwd, ".gitignore", ".convex/\n");
518​
519 const result = yield* searchWorkspaceEntries({ cwd, query: "", limit: 100 });
520 const paths = result.entries.map((entry) => entry.path);
521​
522 expect(paths).toContain("src");
523 expect(paths).toContain("src/keep.ts");
524 expect(paths.some((entryPath) => entryPath.startsWith(".convex/"))).toBe(false);
525 }),
526 );
527​
528 it.effect("finds a path inside a gitignored nested git worktree only by its exact path", () =>
529 Effect.gen(function* () {
530 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-worktree-", git: true });
531 const env = {
532 ...process.env,
533 GIT_AUTHOR_NAME: "Test",
534 GIT_AUTHOR_EMAIL: "test@example.com",
535 GIT_COMMITTER_NAME: "Test",
536 GIT_COMMITTER_EMAIL: "test@example.com",
537 };
538 yield* writeTextFile(cwd, ".gitignore", ".worktrees/\n");
539 yield* git(cwd, ["add", ".gitignore"]);
540 yield* git(cwd, ["commit", "-m", "init"], env);
541 yield* git(cwd, ["worktree", "add", "-b", "x", ".worktrees/x"]);
542 yield* writeTextFile(cwd, ".worktrees/x/src/foo.py", "print(1)");
543​
544 const exact = yield* searchWorkspaceEntries({
545 cwd,
546 query: "src/foo.py",
547 limit: 25,
548 kind: "file",
549 });
550 expect(exact.entries).toEqual([{ path: ".worktrees/x/src/foo.py", kind: "file" }]);
551​
552 const partial = yield* searchWorkspaceEntries({ cwd, query: "src/fo", limit: 25 });
553 expect(partial.entries.map((entry) => entry.path)).not.toContain(".worktrees/x/src/foo.py");
554 }),
555 );
556 });
557​
558 describe("searchContents", () => {
559 it.effect("returns content matches with file paths, line numbers, and ranges", () =>
560 Effect.gen(function* () {
561 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-search-" });
562 yield* writeTextFile(
563 cwd,
564 "src/shapes.ts",
565 "export const square = 4;\nexport const Square = 16;\nexport const squareSize = 8;\n",
566 );
567 yield* writeTextFile(cwd, "src/other.ts", "const circle = true;\n");
568​
569 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
570 const result = yield* workspaceEntries.searchContents({
571 cwd,
572 query: "Square",
573 limit: 100,
574 caseSensitive: false,
575 wholeWord: true,
576 useRegex: false,
577 });
578​
579 expect(result.matches.map((match) => [match.path, match.lineNumber])).toEqual([
580 ["src/shapes.ts", 1],
581 ["src/shapes.ts", 2],
582 ]);
583 expect(result.matches[0]?.matchRanges).toEqual([{ start: 13, end: 19 }]);
584 expect(result.truncated).toBe(false);
585 }),
586 );
587​
588 it.effect("honors case sensitivity and gitignore rules", () =>
589 Effect.gen(function* () {
590 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-ignore-", git: true });
591 yield* writeTextFile(cwd, ".gitignore", "ignored.txt\n");
592 yield* writeTextFile(cwd, "src/keep.ts", "square\nSquare\n");
593 yield* writeTextFile(cwd, "ignored.txt", "Square\n");
594​
595 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
596 const result = yield* workspaceEntries.searchContents({
597 cwd,
598 query: "Square",
599 limit: 100,
600 caseSensitive: true,
601 wholeWord: false,
602 useRegex: false,
603 });
604​
605 expect(result.matches).toHaveLength(1);
606 expect(result.matches[0]).toMatchObject({ path: "src/keep.ts", lineNumber: 2 });
607 }),
608 );
609​
610 it.effect("finds later whole-word matches in a file after rejected raw matches", () =>
611 Effect.gen(function* () {
612 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-late-whole-word-" });
613 yield* writeTextFile(cwd, "src/words.ts", `${"afoo\n".repeat(10)}foo\n`);
614​
615 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
616 const result = yield* workspaceEntries.searchContents({
617 cwd,
618 query: "foo",
619 limit: 1,
620 caseSensitive: true,
621 wholeWord: true,
622 useRegex: false,
623 });
624​
625 expect(result.matches).toEqual([
626 expect.objectContaining({
627 path: "src/words.ts",
628 lineNumber: 11,
629 matchRanges: [{ start: 0, end: 3 }],
630 }),
631 ]);
632 }),
633 );
634​
635 it.effect("treats astral-plane letters as whole word characters", () =>
636 Effect.gen(function* () {
637 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-astral-word-" });
638 yield* writeTextFile(cwd, "src/words.ts", "𐐀foo foo foo𐐀\n");
639​
640 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
641 const result = yield* workspaceEntries.searchContents({
642 cwd,
643 query: "foo",
644 limit: 100,
645 caseSensitive: true,
646 wholeWord: true,
647 useRegex: false,
648 });
649​
650 expect(result.matches).toEqual([
651 expect.objectContaining({
652 path: "src/words.ts",
653 lineNumber: 1,
654 matchRanges: [{ start: 6, end: 9 }],
655 }),
656 ]);
657 }),
658 );
659​
660 it.effect("matches punctuation-edged whole-word queries including adjacent occurrences", () =>
661 Effect.gen(function* () {
662 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-punctuation-" });
663 yield* writeTextFile(cwd, "src/words.ts", "-foo- -foo- -foo-\n");
664​
665 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
666 const result = yield* workspaceEntries.searchContents({
667 cwd,
668 query: "-foo-",
669 limit: 100,
670 caseSensitive: true,
671 wholeWord: true,
672 useRegex: false,
673 });
674​
675 expect(result.matches).toHaveLength(1);
676 expect(result.matches[0]).toMatchObject({
677 path: "src/words.ts",
678 lineNumber: 1,
679 matchRanges: [
680 { start: 0, end: 5 },
681 { start: 6, end: 11 },
682 { start: 12, end: 17 },
683 ],
684 });
685 }),
686 );
687​
688 it.effect("caps matches per file so one dense file cannot fill the page", () =>
689 Effect.gen(function* () {
690 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-per-file-cap-" });
691 yield* writeTextFile(cwd, "src/dense.ts", "needle\n".repeat(300));
692 yield* writeTextFile(cwd, "src/other.ts", "needle\n");
693​
694 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
695 const result = yield* workspaceEntries.searchContents({
696 cwd,
697 query: "needle",
698 limit: 500,
699 caseSensitive: true,
700 wholeWord: false,
701 useRegex: false,
702 });
703​
704 const byPath = new Map<string, number>();
705 for (const match of result.matches) {
706 byPath.set(match.path, (byPath.get(match.path) ?? 0) + 1);
707 }
708 expect(byPath.get("src/dense.ts")).toBe(100);
709 expect(byPath.get("src/other.ts")).toBe(1);
710 }),
711 );
712​
713 it.effect("preserves regex escapes during case-insensitive searches", () =>
714 Effect.gen(function* () {
715 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-regex-" });
716 yield* writeTextFile(cwd, "src/shapes.ts", "Square\nsquare\n");
717​
718 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
719 const result = yield* workspaceEntries.searchContents({
720 cwd,
721 query: "\\SQUARE",
722 limit: 100,
723 caseSensitive: false,
724 wholeWord: false,
725 useRegex: true,
726 });
727​
728 expect(result.matches.map((match) => match.lineNumber)).toEqual([1, 2]);
729 }),
730 );
731​
732 it.effect("searches an invalid regex literally without matching case", () =>
733 Effect.gen(function* () {
734 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-invalid-regex-" });
735 yield* writeTextFile(cwd, "src/calls.ts", "call(Foo(bar));\n");
736​
737 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
738 const result = yield* workspaceEntries.searchContents({
739 cwd,
740 query: "foo(",
741 limit: 100,
742 caseSensitive: false,
743 wholeWord: false,
744 useRegex: true,
745 });
746​
747 expect(result.regexFallbackError).toBeDefined();
748 expect(result.matches).toEqual([
749 expect.objectContaining({
750 path: "src/calls.ts",
751 lineNumber: 1,
752 matchRanges: [{ start: 5, end: 9 }],
753 }),
754 ]);
755 }),
756 );
757​
758 it.effect("maps multi-byte lines to string-indexed ranges", () =>
759 Effect.gen(function* () {
760 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-multibyte-" });
761 yield* writeTextFile(cwd, "src/notes.ts", 'const label = "héllo wörld";\n');
762​
763 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
764 const result = yield* workspaceEntries.searchContents({
765 cwd,
766 query: "wörld",
767 limit: 100,
768 caseSensitive: true,
769 wholeWord: false,
770 useRegex: false,
771 });
772​
773 expect(result.matches).toHaveLength(1);
774 const match = result.matches[0]!;
775 const range = match.matchRanges[0]!;
776 expect(match.lineContent.slice(range.start, range.end)).toBe("wörld");
777 }),
778 );
779​
780 it.effect("keeps matches past the truncated part of a long line", () =>
781 Effect.gen(function* () {
782 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-long-line-" });
783 yield* writeTextFile(cwd, "dist/app.min.js", `${"x".repeat(600)} needleSuffix\n`);
784​
785 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
786 const search = (wholeWord: boolean) =>
787 workspaceEntries.searchContents({
788 cwd,
789 query: "needle",
790 limit: 100,
791 caseSensitive: true,
792 wholeWord,
793 useRegex: false,
794 });
795​
796 expect((yield* search(false)).matches).toEqual([
797 expect.objectContaining({ path: "dist/app.min.js", lineNumber: 1 }),
798 ]);
799 expect((yield* search(true)).matches).toEqual([]);
800 }),
801 );
802​
803 it.effect("keeps answering from the live index when a refresh outlasts the scan wait", () =>
804 Effect.gen(function* () {
805 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-refresh-" });
806 yield* writeTextFile(cwd, "src/notes.ts", "const needle = 1;\n");
807 let scansOutlastWait = false;
808 let finders = 0;
809 let rescans = 0;
810 const createFinder = FileFinder.create.bind(FileFinder);
811 vi.spyOn(FileFinder, "create").mockImplementation((options) => {
812 const created = createFinder(options);
813 if (created.ok) {
814 const finder = created.value;
815 finders += 1;
816 // The synchronous rescan waits on fff's picker lock on the event loop.
817 finder.scanFiles = () => {
818 throw new Error("refresh must not rescan on the JS thread");
819 };
820 const scanFilesAsync = finder.scanFilesAsync.bind(finder);
821 finder.scanFilesAsync = () => {
822 rescans += 1;
823 return scanFilesAsync();
824 };
825 const waitForIndexReady = finder.waitForIndexReady.bind(finder);
826 finder.waitForIndexReady = (timeoutMs) =>
827 scansOutlastWait
828 ? Promise.resolve({ ok: true, value: false })
829 : waitForIndexReady(timeoutMs);
830 }
831 return created;
832 });
833 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
834 const searchNeedle = workspaceEntries.searchContents({
835 cwd,
836 query: "needle",
837 limit: 100,
838 caseSensitive: true,
839 wholeWord: false,
840 useRegex: false,
841 });
842 yield* searchNeedle;
843​
844 scansOutlastWait = true;
845 yield* workspaceEntries.refresh(cwd);
846 const result = yield* searchNeedle;
847​
848 expect(result.matches.map((match) => match.path)).toEqual(["src/notes.ts"]);
849 // The second search ran on the rescanned live finder, not a rebuild.
850 expect({ finders, rescans }).toEqual({ finders: 1, rescans: 1 });
851 }),
852 );
853 });
854​
855 describe("browse", () => {
856 it.effect("shows dot directories in directory mode and hidden-prefix mode", () =>
857 Effect.gen(function* () {
858 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
859 const path = yield* Path.Path;
860 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-browse-hidden-" });
861 yield* writeTextFile(cwd, ".config/settings.json", "{}");
862 yield* writeTextFile(cwd, "config/settings.json", "{}");
863 const cwdWithSeparator = yield* appendSeparator(cwd);
864​
865 const directoryResult = yield* workspaceEntries.browse({
866 partialPath: cwdWithSeparator,
867 });
868 const hiddenPrefixResult = yield* workspaceEntries.browse({
869 partialPath: `${cwdWithSeparator}.c`,
870 });
871​
872 expect(directoryResult.entries.map((entry) => entry.name)).toEqual([".config", "config"]);
873 expect(hiddenPrefixResult).toEqual({
874 parentPath: cwd,
875 entries: [{ name: ".config", fullPath: path.join(cwd, ".config") }],
876 });
877 }),
878 );
879​
880 it.effect("marks only a missing directory as missing when browsing fails", () =>
881 Effect.gen(function* () {
882 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
883 const path = yield* Path.Path;
884 const cwd = yield* makeTempDir({ prefix: "t3code-workspace-browse-missing-" });
885 yield* writeTextFile(cwd, "file.txt", "");
886​
887 const missing = yield* workspaceEntries
888 .browse({ partialPath: `${path.join(cwd, "absent", "nested")}${path.sep}` })
889 .pipe(Effect.flip);
890 const underFile = yield* workspaceEntries
891 .browse({ partialPath: `${path.join(cwd, "file.txt")}${path.sep}` })
892 .pipe(Effect.flip);
893​
894 expect(missing).toMatchObject({
895 _tag: "WorkspaceEntriesReadDirectoryError",
896 pathMissing: true,
897 });
898 expect(underFile).toMatchObject({
899 _tag: "WorkspaceEntriesReadDirectoryError",
900 pathMissing: false,
901 });
902 }),
903 );
904 });
905});