Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - FileSystem cannot create a FIFO, and reads spy on native realpath.
2import * as NodeChildProcess from "node:child_process";
3import * as NodeFSP from "node:fs/promises";
4
5import * as NodePath from "@effect/platform-node/NodePath";
6import * as NodeServices from "@effect/platform-node/NodeServices";
7import { it, describe, expect } from "@effect/vitest";
8import * as Effect from "effect/Effect";
9import * as FileSystem from "effect/FileSystem";
10import * as Layer from "effect/Layer";
11import * as Path from "effect/Path";
12
13import * as ServerConfig from "../config.ts";
14import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
15import * as VcsProcess from "../vcs/VcsProcess.ts";
16import * as KnownWorkspaces from "./KnownWorkspaces.ts";
17import * as WorkspaceEntries from "./WorkspaceEntries.ts";
18import * as WorkspaceFileSystem from "./WorkspaceFileSystem.ts";
19import * as WorkspacePaths from "./WorkspacePaths.ts";
20import * as HostProcess from "@t3tools/shared/HostProcess";
21import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
22import { vi } from "vite-plus/test";
23
24vi.mock("node:fs/promises", async (importOriginal) => {
25 const actual = await importOriginal<typeof NodeFSP>();
26 return { ...actual, realpath: vi.fn(actual.realpath) };
27});
28
29const UNKNOWN_WORKSPACE_PREFIX = "t3code-unknown-workspace-";
30const layerKnownWorkspacesTest = Layer.mock(KnownWorkspaces.KnownWorkspaces)({
31 assertContains: (cwd) =>
32 cwd.includes(UNKNOWN_WORKSPACE_PREFIX)
33 ? Effect.fail(new KnownWorkspaces.UnknownWorkspaceError({ cwd }))
34 : Effect.void,
35});
36
37const layerProject = WorkspaceFileSystem.layer.pipe(
38 Layer.provide(layerKnownWorkspacesTest),
39 Layer.provide(WorkspacePaths.layer),
40 Layer.provide(WorkspaceEntries.layer.pipe(Layer.provide(WorkspacePaths.layer))),
41);
42
43const layerTest = Layer.empty.pipe(
44 Layer.provideMerge(layerProject),
45 Layer.provideMerge(WorkspaceEntries.layer.pipe(Layer.provide(WorkspacePaths.layer))),
46 Layer.provideMerge(WorkspacePaths.layer),
47 Layer.provideMerge(VcsDriverRegistry.layer.pipe(Layer.provide(VcsProcess.layer))),
48 Layer.provide(
49 ServerConfig.ServerConfig.layerTest(process.cwd(), {
50 prefix: "t3-workspace-files-test-",
51 }),
52 ),
53 Layer.provideMerge(NodeServices.layer),
54);
55
56const makeTempDir = Effect.gen(function* () {
57 const fileSystem = yield* FileSystem.FileSystem;
58 return yield* fileSystem.makeTempDirectoryScoped({
59 prefix: "t3code-workspace-files-",
60 });
61});
62
63const writeTextFile = Effect.fn("writeTextFile")(function* (
64 cwd: string,
65 relativePath: string,
66 contents = "",
67) {
68 const fileSystem = yield* FileSystem.FileSystem;
69 const path = yield* Path.Path;
70 const absolutePath = path.join(cwd, relativePath);
71 yield* fileSystem
72 .makeDirectory(path.dirname(absolutePath), { recursive: true })
73 .pipe(Effect.orDie);
74 yield* fileSystem.writeFileString(absolutePath, contents).pipe(Effect.orDie);
75});
76
77it.layer(layerTest, { excludeTestServices: true })("WorkspaceFileSystemLive", (it) => {
78 describe("getMetadata", () => {
79 it.effect(
80 "reports actual kinds for extensionless files, dotfiles, and dotted directories",
81 () =>
82 Effect.gen(function* () {
83 const service = yield* WorkspaceFileSystem.WorkspaceFileSystem;
84 const fs = yield* FileSystem.FileSystem;
85 const path = yield* Path.Path;
86 const cwd = yield* makeTempDir;
87 yield* writeTextFile(cwd, "custom-name", "hello");
88 yield* writeTextFile(cwd, ".npmrc", "registry=test");
89 yield* fs.makeDirectory(path.join(cwd, "folder.ts"));
90 const file = path.join(cwd, "custom-name");
91 const result = yield* service.getMetadata({
92 paths: [
93 file,
94 path.join(cwd, ".npmrc"),
95 path.join(cwd, "folder.ts"),
96 file,
97 path.join(cwd, "missing"),
98 "relative-path",
99 ],
100 });
101 expect(result.entries).toEqual([
102 { kind: "file", byteLength: 5 },
103 { kind: "file", byteLength: 13 },
104 { kind: "directory" },
105 { kind: "file", byteLength: 5 },
106 null,
107 null,
108 ]);
109 }),
110 );
111
112 it.effect("detects an extensionless script and image without returning their contents", () =>
113 Effect.gen(function* () {
114 const service = yield* WorkspaceFileSystem.WorkspaceFileSystem;
115 const fs = yield* FileSystem.FileSystem;
116 const path = yield* Path.Path;
117 const cwd = yield* makeTempDir;
118 const script = "#!/usr/bin/env python3\nprint('hello')\n";
119 yield* writeTextFile(cwd, "run", script);
120 const image = path.join(cwd, "image");
121 yield* fs.writeFile(
122 image,
123 new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
124 );
125 expect(
126 (yield* service.getMetadata({ paths: [path.join(cwd, "run"), image] })).entries,
127 ).toEqual([
128 { kind: "file", byteLength: script.length, mimeType: "text/x-python" },
129 { kind: "file", byteLength: 8, mimeType: "image/png" },
130 ]);
131 }),
132 );
133
134 // A file chip for `file://attacker.test/s/a.ts` in an agent's message sent
135 // the Windows user's NTLM credentials to attacker.test as it rendered.
136 it.effect("never stats a network path", () =>
137 Effect.gen(function* () {
138 const fs = yield* FileSystem.FileSystem;
139 const statted: Array<string> = [];
140 const service = yield* WorkspaceFileSystem.make.pipe(
141 Effect.provideService(
142 FileSystem.FileSystem,
143 FileSystem.FileSystem.of({
144 ...fs,
145 stat: (requestedPath) => {
146 statted.push(requestedPath);
147 return fs.stat(requestedPath);
148 },
149 }),
150 ),
151 Effect.provide(layerKnownWorkspacesTest),
152 );
153 const paths = [
154 "\\\\attacker.test\\s\\a.ts",
155 "//attacker.test/s/a.ts",
156 "/\\attacker.test\\s",
157 ];
158 expect((yield* service.getMetadata({ paths })).entries).toEqual([null, null, null]);
159 expect(statted).toEqual([]);
160 }),
161 );
162 });
163
164 describe("readFile", () => {
165 it.effect("reads host files outside the workspace root by absolute path", () =>
166 Effect.gen(function* () {
167 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
168 const path = yield* Path.Path;
169 const cwd = yield* makeTempDir;
170 const outsideDir = yield* makeTempDir;
171 yield* writeTextFile(outsideDir, "cleanup-report.md", "# Report\n");
172 const absolutePath = path.join(outsideDir, "cleanup-report.md");
173
174 const result = yield* workspaceFileSystem.readFile({
175 cwd,
176 relativePath: absolutePath,
177 });
178
179 expect(result).toEqual({
180 relativePath: absolutePath,
181 contents: "# Report\n",
182 byteLength: 9,
183 truncated: false,
184 });
185 }),
186 );
187
188 it.effect("reads ~/ paths from the server home outside the workspace", () =>
189 Effect.gen(function* () {
190 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
191 const cwd = yield* makeTempDir;
192 const home = yield* makeTempDir;
193 yield* writeTextFile(home, ".claude/CLAUDE.md", "# Notes\n");
194 yield* writeTextFile(cwd, "~/.claude/CLAUDE.md", "Workspace decoy\n");
195
196 const result = yield* workspaceFileSystem
197 .readFile({ cwd, relativePath: "~/.claude/CLAUDE.md" })
198 .pipe(Effect.provideService(HostProcess.HomeDirectory, home));
199
200 expect(result).toEqual({
201 relativePath: "~/.claude/CLAUDE.md",
202 contents: "# Notes\n",
203 byteLength: 8,
204 truncated: false,
205 });
206 }),
207 );
208
209 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
210 "rejects a FIFO without blocking on open",
211 () =>
212 Effect.gen(function* () {
213 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
214 const path = yield* Path.Path;
215 const cwd = yield* makeTempDir;
216 const outsideDir = yield* makeTempDir;
217 const fifoPath = path.join(outsideDir, "pipe");
218 yield* Effect.promise(
219 () =>
220 new Promise<void>((resolve, reject) =>
221 NodeChildProcess.execFile("mkfifo", [fifoPath], (error) =>
222 error ? reject(error) : resolve(),
223 ),
224 ),
225 );
226
227 const error = yield* workspaceFileSystem
228 .readFile({ cwd, relativePath: fifoPath })
229 .pipe(Effect.flip);
230
231 expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspacePathNotFileError);
232 expect((yield* workspaceFileSystem.getMetadata({ paths: [fifoPath] })).entries).toEqual([
233 { kind: "other" },
234 ]);
235 }),
236 );
237
238 it.effect("refuses a network path outside the workspace", () =>
239 Effect.gen(function* () {
240 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
241
242 const error = yield* workspaceFileSystem
243 .readFile({ cwd: "//nas.test/share/project", relativePath: "//attacker.test/s/a.md" })
244 .pipe(Effect.flip);
245
246 expect(error).toBeInstanceOf(WorkspacePaths.WorkspacePathOutsideRootError);
247 }),
248 );
249
250 // This resolves inside the project, but Windows reads `\\?\` paths as
251 // written, so realpath on the raw string signed in to attacker.test.
252 it.effect("reads the network path it checked", () =>
253 Effect.gen(function* () {
254 const workspaceFileSystem = yield* WorkspaceFileSystem.make.pipe(
255 Effect.provide(Layer.merge(layerKnownWorkspacesTest, NodePath.layerWin32)),
256 );
257 // Rejects without touching the filesystem, so a Windows runner never looks the share up.
258 const realpath = vi
259 .mocked(NodeFSP.realpath)
260 .mockClear()
261 .mockRejectedValueOnce(Object.assign(new Error("ENOENT"), { code: "ENOENT" }));
262
263 yield* workspaceFileSystem
264 .readFile({
265 cwd: "\\\\?\\UNC\\nas.test\\share\\project",
266 relativePath: "\\\\?\\UNC\\attacker.test\\s\\..\\..\\nas.test\\share\\project\\a.md",
267 })
268 .pipe(Effect.exit);
269
270 expect(realpath.mock.calls.map(([target]) => target)).toEqual([
271 "\\\\?\\UNC\\nas.test\\share\\project\\a.md",
272 ]);
273 }),
274 );
275
276 // Resolving `..` before realpath would read beside the link instead of its target.
277 // Windows collapses `..` before the filesystem sees a path, so it has no such reads.
278 it.effect.skipIf(!symlinksSupported || HostProcess.Platform.defaultValue() === "win32")(
279 "reads `..` after a link from the link's target",
280 () =>
281 Effect.gen(function* () {
282 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
283 const fs = yield* FileSystem.FileSystem;
284 const path = yield* Path.Path;
285 const root = yield* makeTempDir;
286 yield* writeTextFile(root, "target/parent.md", "beside the target\n");
287 yield* writeTextFile(root, "parent.md", "beside the link\n");
288 yield* fs.makeDirectory(path.join(root, "target", "child"));
289 yield* fs.symlink(path.join(root, "target", "child"), path.join(root, "link"));
290
291 const result = yield* workspaceFileSystem.readFile({
292 cwd: root,
293 relativePath: `${root}/link/../parent.md`,
294 });
295
296 expect(result.contents).toBe("beside the target\n");
297 }),
298 );
299
300 it.effect.skipIf(!symlinksSupported)(
301 "rejects symlinks that resolve outside the workspace root",
302 () =>
303 Effect.gen(function* () {
304 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
305 const fileSystem = yield* FileSystem.FileSystem;
306 const path = yield* Path.Path;
307 const cwd = yield* makeTempDir;
308 const outsideDir = yield* makeTempDir;
309 yield* writeTextFile(outsideDir, "secret.txt", "outside\n");
310 yield* fileSystem.symlink(
311 path.join(outsideDir, "secret.txt"),
312 path.join(cwd, "linked-secret.txt"),
313 );
314
315 const error = yield* workspaceFileSystem
316 .readFile({ cwd, relativePath: "linked-secret.txt" })
317 .pipe(Effect.flip);
318 const resolvedWorkspaceRoot = yield* fileSystem.realPath(cwd);
319 const resolvedPath = yield* fileSystem.realPath(path.join(outsideDir, "secret.txt"));
320
321 expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceFilePathEscapeError);
322 expect(error).toMatchObject({
323 workspaceRoot: cwd,
324 relativePath: "linked-secret.txt",
325 resolvedWorkspaceRoot,
326 resolvedPath,
327 });
328 expect("cause" in error).toBe(false);
329
330 yield* fileSystem.symlink(outsideDir, path.join(cwd, "linked-dir"));
331 const missingChildError = yield* workspaceFileSystem
332 .readFile(
333 Object.assign(
334 { cwd, relativePath: "linked-dir/missing/t3.json" },
335 { allowMissing: true },
336 ),
337 )
338 .pipe(Effect.flip);
339 expect(missingChildError).toBeInstanceOf(
340 WorkspaceFileSystem.WorkspaceFilePathEscapeError,
341 );
342 }),
343 );
344
345 it.effect("rejects binary files without leaking their contents into the error", () =>
346 Effect.gen(function* () {
347 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
348 const fileSystem = yield* FileSystem.FileSystem;
349 const path = yield* Path.Path;
350 const cwd = yield* makeTempDir;
351 const absolutePath = path.join(cwd, "asset.bin");
352 yield* fileSystem.writeFile(absolutePath, Uint8Array.from([0x61, 0, 0x62]));
353
354 const error = yield* workspaceFileSystem
355 .readFile({ cwd, relativePath: "asset.bin" })
356 .pipe(Effect.flip);
357 const resolvedPath = yield* fileSystem.realPath(absolutePath);
358
359 expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceBinaryFileError);
360 expect(error).toMatchObject({
361 workspaceRoot: cwd,
362 relativePath: "asset.bin",
363 resolvedPath,
364 });
365 expect("cause" in error).toBe(false);
366 expect("contents" in error).toBe(false);
367 }),
368 );
369 });
370
371 describe("writeFile", () => {
372 it.effect("rejects writes outside a known workspace", () =>
373 Effect.gen(function* () {
374 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
375 const fileSystem = yield* FileSystem.FileSystem;
376 const cwd = yield* fileSystem.makeTempDirectoryScoped({
377 prefix: UNKNOWN_WORKSPACE_PREFIX,
378 });
379
380 const error = yield* workspaceFileSystem
381 .writeFile({ cwd, relativePath: "plan.md", contents: "# nope\n" })
382 .pipe(Effect.flip);
383
384 expect(error).toBeInstanceOf(KnownWorkspaces.UnknownWorkspaceError);
385 expect(yield* fileSystem.readDirectory(cwd)).toEqual([]);
386 }),
387 );
388
389 it.effect("rejects writes by absolute path", () =>
390 Effect.gen(function* () {
391 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
392 const path = yield* Path.Path;
393 const cwd = yield* makeTempDir;
394 const outsideDir = yield* makeTempDir;
395 const absolutePath = path.join(outsideDir, "cleanup-report.md");
396
397 const error = yield* workspaceFileSystem
398 .writeFile({ cwd, relativePath: absolutePath, contents: "# Edited\n" })
399 .pipe(Effect.flip);
400
401 expect(error).toBeInstanceOf(WorkspacePaths.WorkspacePathOutsideRootError);
402 }),
403 );
404
405 it.effect("invalidates workspace entry search cache after writes", () =>
406 Effect.gen(function* () {
407 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
408 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
409 const cwd = yield* makeTempDir;
410 yield* writeTextFile(cwd, "src/existing.ts", "export {};\n");
411
412 const beforeWrite = yield* workspaceEntries.list({ cwd });
413 expect(beforeWrite.entries.some((entry) => entry.path === "plans/effect-rpc.md")).toBe(
414 false,
415 );
416
417 yield* workspaceFileSystem.writeFile({
418 cwd,
419 relativePath: "plans/effect-rpc.md",
420 contents: "# Plan\n",
421 });
422
423 const afterWrite = yield* workspaceEntries.list({ cwd });
424 expect(afterWrite.entries).toEqual(
425 expect.arrayContaining([expect.objectContaining({ path: "plans/effect-rpc.md" })]),
426 );
427 expect(afterWrite.truncated).toBe(false);
428 }),
429 );
430
431 it.effect("rejects writes outside the workspace root", () =>
432 Effect.gen(function* () {
433 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
434 const cwd = yield* makeTempDir;
435 const path = yield* Path.Path;
436 const fileSystem = yield* FileSystem.FileSystem;
437
438 const error = yield* workspaceFileSystem
439 .writeFile({
440 cwd,
441 relativePath: "../escape.md",
442 contents: "# nope\n",
443 })
444 .pipe(Effect.flip);
445
446 expect(error.message).toContain(
447 "Workspace file path must be relative to the project root: ../escape.md",
448 );
449
450 const escapedPath = path.resolve(cwd, "..", "escape.md");
451 const escapedStat = yield* fileSystem
452 .stat(escapedPath)
453 .pipe(Effect.orElseSucceed(() => null));
454 expect(escapedStat).toBeNull();
455 }),
456 );
457
458 it.effect.skipIf(!symlinksSupported)(
459 "rejects writes through symlinks that resolve outside the workspace root",
460 () =>
461 Effect.gen(function* () {
462 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
463 const fileSystem = yield* FileSystem.FileSystem;
464 const path = yield* Path.Path;
465 const cwd = yield* makeTempDir;
466 const outsideDir = yield* makeTempDir;
467 yield* writeTextFile(outsideDir, "existing.md", "outside\n");
468 yield* fileSystem.symlink(outsideDir, path.join(cwd, "linked-dir"));
469 yield* fileSystem.symlink(
470 path.join(outsideDir, "existing.md"),
471 path.join(cwd, "linked-file.md"),
472 );
473 yield* fileSystem.symlink(
474 path.join(outsideDir, "missing.md"),
475 path.join(cwd, "dangling.md"),
476 );
477
478 for (const relativePath of [
479 "linked-dir/new.md",
480 "linked-dir/nested/new.md",
481 "linked-file.md",
482 ]) {
483 const error = yield* workspaceFileSystem
484 .writeFile({ cwd, relativePath, contents: "# nope\n" })
485 .pipe(Effect.flip);
486 expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceFilePathEscapeError);
487 }
488 const danglingError = yield* workspaceFileSystem
489 .writeFile({ cwd, relativePath: "dangling.md", contents: "# nope\n" })
490 .pipe(Effect.flip);
491 expect(danglingError).toBeInstanceOf(
492 WorkspaceFileSystem.WorkspaceFileSystemOperationError,
493 );
494 expect(danglingError).toMatchObject({ operation: "realpath-target" });
495
496 expect((yield* fileSystem.readDirectory(outsideDir)).toSorted()).toEqual(["existing.md"]);
497 expect(yield* fileSystem.readFileString(path.join(outsideDir, "existing.md"))).toBe(
498 "outside\n",
499 );
500 }),
501 );
502
503 it.effect.skipIf(!symlinksSupported)(
504 "writes through symlinks that stay inside the workspace root",
505 () =>
506 Effect.gen(function* () {
507 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
508 const fileSystem = yield* FileSystem.FileSystem;
509 const path = yield* Path.Path;
510 const parentDir = yield* makeTempDir;
511 const cwd = path.join(parentDir, "workspace");
512 const cwdAlias = path.join(parentDir, "workspace-alias");
513 yield* writeTextFile(cwd, "docs/README.md", "old\n");
514 yield* fileSystem.symlink(path.join(cwd, "docs"), path.join(cwd, "docs-alias"));
515 yield* fileSystem.symlink("docs/README.md", path.join(cwd, "README.md"));
516 yield* fileSystem.symlink(cwd, cwdAlias);
517
518 yield* workspaceFileSystem.writeFile({
519 cwd,
520 relativePath: "docs-alias/plans/plan.md",
521 contents: "# Plan\n",
522 });
523 yield* workspaceFileSystem.writeFile({
524 cwd,
525 relativePath: "README.md",
526 contents: "new\n",
527 });
528 yield* workspaceFileSystem.writeFile({
529 cwd: cwdAlias,
530 relativePath: "notes.md",
531 contents: "notes\n",
532 });
533 // `..` after a link in cwd is resolved by name, as for the relative path.
534 yield* fileSystem.symlink(path.join(cwd, "docs/plans"), path.join(cwd, "plans-alias"));
535 yield* workspaceFileSystem.writeFile({
536 cwd: `${path.join(cwd, "plans-alias")}${path.sep}..`,
537 relativePath: "dotdot.md",
538 contents: "dotdot\n",
539 });
540
541 expect(yield* fileSystem.readFileString(path.join(cwd, "docs/plans/plan.md"))).toBe(
542 "# Plan\n",
543 );
544 expect(yield* fileSystem.readFileString(path.join(cwd, "docs/README.md"))).toBe("new\n");
545 expect(yield* fileSystem.readLink(path.join(cwd, "README.md"))).toBe("docs/README.md");
546 expect(yield* fileSystem.readFileString(path.join(cwd, "notes.md"))).toBe("notes\n");
547 expect(yield* fileSystem.readFileString(path.join(cwd, "dotdot.md"))).toBe("dotdot\n");
548 }),
549 );
550
551 // On Windows `\` is a separator, so the name cannot exist there.
552 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
553 "keeps a backslash in a file name as part of the name",
554 () =>
555 Effect.gen(function* () {
556 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
557 const fileSystem = yield* FileSystem.FileSystem;
558 const cwd = yield* makeTempDir;
559 yield* writeTextFile(cwd, "a\\b.md", "old\n");
560
561 yield* workspaceFileSystem.writeFile({ cwd, relativePath: "a\\b.md", contents: "new\n" });
562
563 expect(
564 (yield* workspaceFileSystem.readFile({ cwd, relativePath: "a\\b.md" })).contents,
565 ).toBe("new\n");
566 expect(yield* fileSystem.readDirectory(cwd)).toEqual(["a\\b.md"]);
567 }),
568 );
569
570 it.effect("refuses writes into git's own folders", () =>
571 Effect.gen(function* () {
572 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
573 const fileSystem = yield* FileSystem.FileSystem;
574 const path = yield* Path.Path;
575 const cwd = yield* makeTempDir;
576 yield* writeTextFile(cwd, ".git/config", "[core]\n");
577 yield* writeTextFile(cwd, ".bare/HEAD", "ref: refs/heads/main\n");
578 yield* writeTextFile(cwd, ".bare/objects/info/packs");
579 yield* writeTextFile(cwd, ".bare/refs/heads/main");
580 yield* writeTextFile(cwd, ".bare/hooks/pre-push.sample");
581 // Only a linked worktree's `.git` file ends the upward check, not any `.git` folder.
582 yield* fileSystem.makeDirectory(path.join(cwd, ".bare/hooks/.git"));
583 yield* writeTextFile(cwd, ".bare/worktrees/main/HEAD", "ref: refs/heads/main\n");
584 yield* writeTextFile(cwd, ".bare/worktrees/main/commondir", "../..\n");
585 if (symlinksSupported) yield* fileSystem.symlink(".git", path.join(cwd, "docs"));
586
587 for (const [folder, relativePath] of [
588 [cwd, ".git/config"],
589 [cwd, ".git/hooks/pre-commit"],
590 [cwd, "sub/.git"],
591 [cwd, ".GIT/config"],
592 [cwd, ".gıt/config"],
593 [cwd, ".git. /config"],
594 [cwd, ".git::$INDEX_ALLOCATION/config"],
595 [cwd, "GIT~1/config"],
596 [path.join(cwd, ".git"), "config"],
597 [cwd, ".bare/config"],
598 [path.join(cwd, ".bare"), "hooks/post-checkout"],
599 [path.join(cwd, ".bare/hooks"), "post-checkout"],
600 [path.join(cwd, ".bare/worktrees/main"), "commondir"],
601 ...(symlinksSupported ? [[cwd, "docs/config"] as const] : []),
602 ] as const) {
603 const error = yield* workspaceFileSystem
604 .writeFile({ cwd: folder, relativePath, contents: "[core]\n\tfsmonitor = x\n" })
605 .pipe(Effect.flip);
606 expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceFilePathEscapeError);
607 }
608
609 expect(yield* fileSystem.readFileString(path.join(cwd, ".git/config"))).toBe("[core]\n");
610 expect(yield* fileSystem.exists(path.join(cwd, ".bare/config"))).toBe(false);
611 expect((yield* fileSystem.readDirectory(path.join(cwd, ".bare/hooks"))).toSorted()).toEqual(
612 [".git", "pre-push.sample"],
613 );
614 expect(yield* fileSystem.exists(path.join(cwd, "sub"))).toBe(false);
615 expect(
616 yield* fileSystem.readFileString(path.join(cwd, ".bare/worktrees/main/commondir")),
617 ).toBe("../..\n");
618 }),
619 );
620
621 it.effect.skipIf(!symlinksSupported)(
622 "refuses writes through a git config that links to a file outside git's folders",
623 () =>
624 Effect.gen(function* () {
625 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
626 const fileSystem = yield* FileSystem.FileSystem;
627 const path = yield* Path.Path;
628 const cwd = yield* makeTempDir;
629 yield* writeTextFile(cwd, "shared/config", "[core]\n");
630 yield* fileSystem.makeDirectory(path.join(cwd, ".git"));
631 yield* fileSystem.symlink("../shared/config", path.join(cwd, ".git/config"));
632
633 const error = yield* workspaceFileSystem
634 .writeFile({ cwd, relativePath: ".git/config", contents: "[core]\n\tfsmonitor = x\n" })
635 .pipe(Effect.flip);
636
637 expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceFilePathEscapeError);
638 expect(yield* fileSystem.readFileString(path.join(cwd, "shared/config"))).toBe(
639 "[core]\n",
640 );
641 }),
642 );
643
644 it.effect("writes files that sit beside git's folders", () =>
645 Effect.gen(function* () {
646 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
647 const fileSystem = yield* FileSystem.FileSystem;
648 const path = yield* Path.Path;
649 const parentDir = yield* makeTempDir;
650 const bare = path.join(parentDir, "repo.git");
651 yield* writeTextFile(bare, "HEAD", "ref: refs/heads/main\n");
652 yield* writeTextFile(bare, "objects/info/packs");
653 yield* writeTextFile(bare, "refs/heads/main");
654 yield* writeTextFile(bare, "main/.git", `gitdir: ${path.join(bare, "worktrees/main")}\n`);
655
656 for (const [cwd, relativePath] of [
657 [path.join(bare, "main"), ".gitignore"],
658 [path.join(bare, "main"), ".gitattributes"],
659 [path.join(bare, "main"), ".github/workflows/ci.yml"],
660 [path.join(bare, "main"), "vendor/lib.git/README.md"],
661 [path.join(bare, "main/.github"), "CODEOWNERS"],
662 [bare, "main/plan.md"],
663 ] as const) {
664 yield* workspaceFileSystem.writeFile({ cwd, relativePath, contents: "ok\n" });
665 expect(yield* fileSystem.readFileString(path.join(cwd, relativePath))).toBe("ok\n");
666 }
667 }),
668 );
669 });
670});