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.provideMerge(
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("does not read server state files", () =>
210 Effect.gen(function* () {
211 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
212 const config = yield* ServerConfig.ServerConfig;
213 const path = yield* Path.Path;
214 const cwd = yield* makeTempDir;
215 yield* writeTextFile(config.secretsDir, "example.bin", "example\n");
216 yield* writeTextFile(config.stateDir, "statev2.sqlite", "example\n");
217
218 for (const input of [
219 { cwd, relativePath: path.join(config.secretsDir, "example.bin") },
220 { cwd: config.stateDir, relativePath: "statev2.sqlite" },
221 ]) {
222 const error = yield* workspaceFileSystem.readFile(input).pipe(Effect.flip);
223 expect(error).toBeInstanceOf(WorkspacePaths.WorkspacePathOutsideRootError);
224 }
225 }),
226 );
227
228 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
229 "rejects a FIFO without blocking on open",
230 () =>
231 Effect.gen(function* () {
232 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
233 const path = yield* Path.Path;
234 const cwd = yield* makeTempDir;
235 const outsideDir = yield* makeTempDir;
236 const fifoPath = path.join(outsideDir, "pipe");
237 yield* Effect.promise(
238 () =>
239 new Promise<void>((resolve, reject) =>
240 NodeChildProcess.execFile("mkfifo", [fifoPath], (error) =>
241 error ? reject(error) : resolve(),
242 ),
243 ),
244 );
245
246 const error = yield* workspaceFileSystem
247 .readFile({ cwd, relativePath: fifoPath })
248 .pipe(Effect.flip);
249
250 expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspacePathNotFileError);
251 expect((yield* workspaceFileSystem.getMetadata({ paths: [fifoPath] })).entries).toEqual([
252 { kind: "other" },
253 ]);
254 }),
255 );
256
257 it.effect("refuses a network path outside the workspace", () =>
258 Effect.gen(function* () {
259 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
260
261 const error = yield* workspaceFileSystem
262 .readFile({ cwd: "//nas.test/share/project", relativePath: "//attacker.test/s/a.md" })
263 .pipe(Effect.flip);
264
265 expect(error).toBeInstanceOf(WorkspacePaths.WorkspacePathOutsideRootError);
266 }),
267 );
268
269 // This resolves inside the project, but Windows reads `\\?\` paths as
270 // written, so realpath on the raw string signed in to attacker.test.
271 it.effect("reads the network path it checked", () =>
272 Effect.gen(function* () {
273 const workspaceFileSystem = yield* WorkspaceFileSystem.make.pipe(
274 Effect.provide(Layer.merge(layerKnownWorkspacesTest, NodePath.layerWin32)),
275 );
276 // Rejects without touching the filesystem, so a Windows runner never looks the share up.
277 const realpath = vi
278 .mocked(NodeFSP.realpath)
279 .mockClear()
280 .mockRejectedValueOnce(Object.assign(new Error("ENOENT"), { code: "ENOENT" }));
281
282 yield* workspaceFileSystem
283 .readFile({
284 cwd: "\\\\?\\UNC\\nas.test\\share\\project",
285 relativePath: "\\\\?\\UNC\\attacker.test\\s\\..\\..\\nas.test\\share\\project\\a.md",
286 })
287 .pipe(Effect.exit);
288
289 expect(realpath.mock.calls.map(([target]) => target)).toEqual([
290 "\\\\?\\UNC\\nas.test\\share\\project\\a.md",
291 ]);
292 }),
293 );
294
295 // Resolving `..` before realpath would read beside the link instead of its target.
296 // Windows collapses `..` before the filesystem sees a path, so it has no such reads.
297 it.effect.skipIf(!symlinksSupported || HostProcess.Platform.defaultValue() === "win32")(
298 "reads `..` after a link from the link's target",
299 () =>
300 Effect.gen(function* () {
301 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
302 const fs = yield* FileSystem.FileSystem;
303 const path = yield* Path.Path;
304 const root = yield* makeTempDir;
305 yield* writeTextFile(root, "target/parent.md", "beside the target\n");
306 yield* writeTextFile(root, "parent.md", "beside the link\n");
307 yield* fs.makeDirectory(path.join(root, "target", "child"));
308 yield* fs.symlink(path.join(root, "target", "child"), path.join(root, "link"));
309
310 const result = yield* workspaceFileSystem.readFile({
311 cwd: root,
312 relativePath: `${root}/link/../parent.md`,
313 });
314
315 expect(result.contents).toBe("beside the target\n");
316 }),
317 );
318
319 it.effect.skipIf(!symlinksSupported)(
320 "rejects symlinks that resolve outside the workspace root",
321 () =>
322 Effect.gen(function* () {
323 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
324 const fileSystem = yield* FileSystem.FileSystem;
325 const path = yield* Path.Path;
326 const cwd = yield* makeTempDir;
327 const outsideDir = yield* makeTempDir;
328 yield* writeTextFile(outsideDir, "secret.txt", "outside\n");
329 yield* fileSystem.symlink(
330 path.join(outsideDir, "secret.txt"),
331 path.join(cwd, "linked-secret.txt"),
332 );
333
334 const error = yield* workspaceFileSystem
335 .readFile({ cwd, relativePath: "linked-secret.txt" })
336 .pipe(Effect.flip);
337 const resolvedWorkspaceRoot = yield* fileSystem.realPath(cwd);
338 const resolvedPath = yield* fileSystem.realPath(path.join(outsideDir, "secret.txt"));
339
340 expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceFilePathEscapeError);
341 expect(error).toMatchObject({
342 workspaceRoot: cwd,
343 relativePath: "linked-secret.txt",
344 resolvedWorkspaceRoot,
345 resolvedPath,
346 });
347 expect("cause" in error).toBe(false);
348
349 yield* fileSystem.symlink(outsideDir, path.join(cwd, "linked-dir"));
350 const missingChildError = yield* workspaceFileSystem
351 .readFile(
352 Object.assign(
353 { cwd, relativePath: "linked-dir/missing/t3.json" },
354 { allowMissing: true },
355 ),
356 )
357 .pipe(Effect.flip);
358 expect(missingChildError).toBeInstanceOf(
359 WorkspaceFileSystem.WorkspaceFilePathEscapeError,
360 );
361 }),
362 );
363
364 it.effect("drops a multibyte character split by the read limit", () =>
365 Effect.gen(function* () {
366 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
367 const fileSystem = yield* FileSystem.FileSystem;
368 const path = yield* Path.Path;
369 const cwd = yield* makeTempDir;
370 const limit = 1024 * 1024;
371 const euro = new TextEncoder().encode("€");
372 const bytes = new Uint8Array(limit - 1 + euro.length).fill(0x61);
373 bytes.set(euro, limit - 1);
374 yield* fileSystem.writeFile(path.join(cwd, "large.txt"), bytes);
375
376 const result = yield* workspaceFileSystem.readFile({ cwd, relativePath: "large.txt" });
377
378 expect(result.truncated).toBe(true);
379 expect(result.byteLength).toBe(bytes.length);
380 expect(result.contents).toBe("a".repeat(limit - 1));
381 }),
382 );
383
384 it.effect("rejects binary files without leaking their contents into the error", () =>
385 Effect.gen(function* () {
386 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
387 const fileSystem = yield* FileSystem.FileSystem;
388 const path = yield* Path.Path;
389 const cwd = yield* makeTempDir;
390 const absolutePath = path.join(cwd, "asset.bin");
391 yield* fileSystem.writeFile(absolutePath, Uint8Array.from([0x61, 0, 0x62]));
392
393 const error = yield* workspaceFileSystem
394 .readFile({ cwd, relativePath: "asset.bin" })
395 .pipe(Effect.flip);
396 const resolvedPath = yield* fileSystem.realPath(absolutePath);
397
398 expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceBinaryFileError);
399 expect(error).toMatchObject({
400 workspaceRoot: cwd,
401 relativePath: "asset.bin",
402 resolvedPath,
403 });
404 expect("cause" in error).toBe(false);
405 expect("contents" in error).toBe(false);
406 }),
407 );
408 });
409
410 describe("writeFile", () => {
411 it.effect("rejects writes outside a known workspace", () =>
412 Effect.gen(function* () {
413 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
414 const fileSystem = yield* FileSystem.FileSystem;
415 const cwd = yield* fileSystem.makeTempDirectoryScoped({
416 prefix: UNKNOWN_WORKSPACE_PREFIX,
417 });
418
419 const error = yield* workspaceFileSystem
420 .writeFile({ cwd, relativePath: "plan.md", contents: "# nope\n" })
421 .pipe(Effect.flip);
422
423 expect(error).toBeInstanceOf(KnownWorkspaces.UnknownWorkspaceError);
424 expect(yield* fileSystem.readDirectory(cwd)).toEqual([]);
425 }),
426 );
427
428 it.effect("rejects writes by absolute path", () =>
429 Effect.gen(function* () {
430 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
431 const path = yield* Path.Path;
432 const cwd = yield* makeTempDir;
433 const outsideDir = yield* makeTempDir;
434 const absolutePath = path.join(outsideDir, "cleanup-report.md");
435
436 const error = yield* workspaceFileSystem
437 .writeFile({ cwd, relativePath: absolutePath, contents: "# Edited\n" })
438 .pipe(Effect.flip);
439
440 expect(error).toBeInstanceOf(WorkspacePaths.WorkspacePathOutsideRootError);
441 }),
442 );
443
444 it.effect("invalidates workspace entry search cache after writes", () =>
445 Effect.gen(function* () {
446 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
447 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
448 const cwd = yield* makeTempDir;
449 yield* writeTextFile(cwd, "src/existing.ts", "export {};\n");
450
451 const beforeWrite = yield* workspaceEntries.list({ cwd });
452 expect(beforeWrite.entries.some((entry) => entry.path === "plans/effect-rpc.md")).toBe(
453 false,
454 );
455
456 yield* workspaceFileSystem.writeFile({
457 cwd,
458 relativePath: "plans/effect-rpc.md",
459 contents: "# Plan\n",
460 });
461
462 const afterWrite = yield* workspaceEntries.list({ cwd });
463 expect(afterWrite.entries).toEqual(
464 expect.arrayContaining([expect.objectContaining({ path: "plans/effect-rpc.md" })]),
465 );
466 expect(afterWrite.truncated).toBe(false);
467 }),
468 );
469
470 it.effect("saves over an existing file without rescanning the workspace", () =>
471 Effect.gen(function* () {
472 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
473 const fileSystem = yield* FileSystem.FileSystem;
474 const path = yield* Path.Path;
475 const cwd = yield* makeTempDir;
476 yield* writeTextFile(cwd, "src/main.ts", "export {};\n");
477
478 yield* workspaceFileSystem.writeFile({
479 cwd,
480 relativePath: "src/main.ts",
481 contents: "export const edited = true;\n",
482 });
483
484 expect(yield* fileSystem.readFileString(path.join(cwd, "src/main.ts"))).toBe(
485 "export const edited = true;\n",
486 );
487 }).pipe(
488 Effect.provide(
489 Layer.fresh(WorkspaceFileSystem.layer).pipe(
490 Layer.provide(layerKnownWorkspacesTest),
491 Layer.provide(WorkspacePaths.layer),
492 Layer.provide(
493 Layer.mock(WorkspaceEntries.WorkspaceEntries)({
494 refresh: () => Effect.die("An overwrite rescanned the workspace."),
495 }),
496 ),
497 ),
498 ),
499 ),
500 );
501
502 it.effect("rejects writes outside the workspace root", () =>
503 Effect.gen(function* () {
504 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
505 const cwd = yield* makeTempDir;
506 const path = yield* Path.Path;
507 const fileSystem = yield* FileSystem.FileSystem;
508
509 const error = yield* workspaceFileSystem
510 .writeFile({
511 cwd,
512 relativePath: "../escape.md",
513 contents: "# nope\n",
514 })
515 .pipe(Effect.flip);
516
517 expect(error.message).toContain(
518 "Workspace file path must be relative to the project root: ../escape.md",
519 );
520
521 const escapedPath = path.resolve(cwd, "..", "escape.md");
522 const escapedStat = yield* fileSystem
523 .stat(escapedPath)
524 .pipe(Effect.orElseSucceed(() => null));
525 expect(escapedStat).toBeNull();
526 }),
527 );
528
529 it.effect.skipIf(!symlinksSupported)(
530 "rejects writes through symlinks that resolve outside the workspace root",
531 () =>
532 Effect.gen(function* () {
533 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
534 const fileSystem = yield* FileSystem.FileSystem;
535 const path = yield* Path.Path;
536 const cwd = yield* makeTempDir;
537 const outsideDir = yield* makeTempDir;
538 yield* writeTextFile(outsideDir, "existing.md", "outside\n");
539 yield* fileSystem.symlink(outsideDir, path.join(cwd, "linked-dir"));
540 yield* fileSystem.symlink(
541 path.join(outsideDir, "existing.md"),
542 path.join(cwd, "linked-file.md"),
543 );
544 yield* fileSystem.symlink(
545 path.join(outsideDir, "missing.md"),
546 path.join(cwd, "dangling.md"),
547 );
548
549 for (const relativePath of [
550 "linked-dir/new.md",
551 "linked-dir/nested/new.md",
552 "linked-file.md",
553 ]) {
554 const error = yield* workspaceFileSystem
555 .writeFile({ cwd, relativePath, contents: "# nope\n" })
556 .pipe(Effect.flip);
557 expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceFilePathEscapeError);
558 }
559 const danglingError = yield* workspaceFileSystem
560 .writeFile({ cwd, relativePath: "dangling.md", contents: "# nope\n" })
561 .pipe(Effect.flip);
562 expect(danglingError).toBeInstanceOf(
563 WorkspaceFileSystem.WorkspaceFileSystemOperationError,
564 );
565 expect(danglingError).toMatchObject({ operation: "realpath-target" });
566
567 expect((yield* fileSystem.readDirectory(outsideDir)).toSorted()).toEqual(["existing.md"]);
568 expect(yield* fileSystem.readFileString(path.join(outsideDir, "existing.md"))).toBe(
569 "outside\n",
570 );
571 }),
572 );
573
574 it.effect.skipIf(!symlinksSupported)(
575 "writes through symlinks that stay inside the workspace root",
576 () =>
577 Effect.gen(function* () {
578 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
579 const fileSystem = yield* FileSystem.FileSystem;
580 const path = yield* Path.Path;
581 const parentDir = yield* makeTempDir;
582 const cwd = path.join(parentDir, "workspace");
583 const cwdAlias = path.join(parentDir, "workspace-alias");
584 yield* writeTextFile(cwd, "docs/README.md", "old\n");
585 yield* fileSystem.symlink(path.join(cwd, "docs"), path.join(cwd, "docs-alias"));
586 yield* fileSystem.symlink("docs/README.md", path.join(cwd, "README.md"));
587 yield* fileSystem.symlink(cwd, cwdAlias);
588
589 yield* workspaceFileSystem.writeFile({
590 cwd,
591 relativePath: "docs-alias/plans/plan.md",
592 contents: "# Plan\n",
593 });
594 yield* workspaceFileSystem.writeFile({
595 cwd,
596 relativePath: "README.md",
597 contents: "new\n",
598 });
599 yield* workspaceFileSystem.writeFile({
600 cwd: cwdAlias,
601 relativePath: "notes.md",
602 contents: "notes\n",
603 });
604 // `..` after a link in cwd is resolved by name, as for the relative path.
605 yield* fileSystem.symlink(path.join(cwd, "docs/plans"), path.join(cwd, "plans-alias"));
606 yield* workspaceFileSystem.writeFile({
607 cwd: `${path.join(cwd, "plans-alias")}${path.sep}..`,
608 relativePath: "dotdot.md",
609 contents: "dotdot\n",
610 });
611
612 expect(yield* fileSystem.readFileString(path.join(cwd, "docs/plans/plan.md"))).toBe(
613 "# Plan\n",
614 );
615 expect(yield* fileSystem.readFileString(path.join(cwd, "docs/README.md"))).toBe("new\n");
616 expect(yield* fileSystem.readLink(path.join(cwd, "README.md"))).toBe("docs/README.md");
617 expect(yield* fileSystem.readFileString(path.join(cwd, "notes.md"))).toBe("notes\n");
618 expect(yield* fileSystem.readFileString(path.join(cwd, "dotdot.md"))).toBe("dotdot\n");
619 }),
620 );
621
622 // On Windows `\` is a separator, so the name cannot exist there.
623 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
624 "keeps a backslash in a file name as part of the name",
625 () =>
626 Effect.gen(function* () {
627 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
628 const fileSystem = yield* FileSystem.FileSystem;
629 const cwd = yield* makeTempDir;
630 yield* writeTextFile(cwd, "a\\b.md", "old\n");
631
632 yield* workspaceFileSystem.writeFile({ cwd, relativePath: "a\\b.md", contents: "new\n" });
633
634 expect(
635 (yield* workspaceFileSystem.readFile({ cwd, relativePath: "a\\b.md" })).contents,
636 ).toBe("new\n");
637 expect(yield* fileSystem.readDirectory(cwd)).toEqual(["a\\b.md"]);
638 }),
639 );
640
641 it.effect("refuses writes into git's own folders", () =>
642 Effect.gen(function* () {
643 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
644 const fileSystem = yield* FileSystem.FileSystem;
645 const path = yield* Path.Path;
646 const cwd = yield* makeTempDir;
647 yield* writeTextFile(cwd, ".git/config", "[core]\n");
648 yield* writeTextFile(cwd, ".bare/HEAD", "ref: refs/heads/main\n");
649 yield* writeTextFile(cwd, ".bare/objects/info/packs");
650 yield* writeTextFile(cwd, ".bare/refs/heads/main");
651 yield* writeTextFile(cwd, ".bare/hooks/pre-push.sample");
652 // Only a linked worktree's `.git` file ends the upward check, not any `.git` folder.
653 yield* fileSystem.makeDirectory(path.join(cwd, ".bare/hooks/.git"));
654 yield* writeTextFile(cwd, ".bare/worktrees/main/HEAD", "ref: refs/heads/main\n");
655 yield* writeTextFile(cwd, ".bare/worktrees/main/commondir", "../..\n");
656 if (symlinksSupported) yield* fileSystem.symlink(".git", path.join(cwd, "docs"));
657
658 for (const [folder, relativePath] of [
659 [cwd, ".git/config"],
660 [cwd, ".git/hooks/pre-commit"],
661 [cwd, "sub/.git"],
662 [cwd, ".GIT/config"],
663 [cwd, ".gıt/config"],
664 [cwd, ".git. /config"],
665 [cwd, ".git::$INDEX_ALLOCATION/config"],
666 [cwd, "GIT~1/config"],
667 [path.join(cwd, ".git"), "config"],
668 [cwd, ".bare/config"],
669 [path.join(cwd, ".bare"), "hooks/post-checkout"],
670 [path.join(cwd, ".bare/hooks"), "post-checkout"],
671 [path.join(cwd, ".bare/worktrees/main"), "commondir"],
672 ...(symlinksSupported ? [[cwd, "docs/config"] as const] : []),
673 ] as const) {
674 const error = yield* workspaceFileSystem
675 .writeFile({ cwd: folder, relativePath, contents: "[core]\n\tfsmonitor = x\n" })
676 .pipe(Effect.flip);
677 expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceFilePathEscapeError);
678 }
679
680 expect(yield* fileSystem.readFileString(path.join(cwd, ".git/config"))).toBe("[core]\n");
681 expect(yield* fileSystem.exists(path.join(cwd, ".bare/config"))).toBe(false);
682 expect((yield* fileSystem.readDirectory(path.join(cwd, ".bare/hooks"))).toSorted()).toEqual(
683 [".git", "pre-push.sample"],
684 );
685 expect(yield* fileSystem.exists(path.join(cwd, "sub"))).toBe(false);
686 expect(
687 yield* fileSystem.readFileString(path.join(cwd, ".bare/worktrees/main/commondir")),
688 ).toBe("../..\n");
689 }),
690 );
691
692 it.effect.skipIf(!symlinksSupported)(
693 "refuses writes through a git config that links to a file outside git's folders",
694 () =>
695 Effect.gen(function* () {
696 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
697 const fileSystem = yield* FileSystem.FileSystem;
698 const path = yield* Path.Path;
699 const cwd = yield* makeTempDir;
700 yield* writeTextFile(cwd, "shared/config", "[core]\n");
701 yield* fileSystem.makeDirectory(path.join(cwd, ".git"));
702 yield* fileSystem.symlink("../shared/config", path.join(cwd, ".git/config"));
703
704 const error = yield* workspaceFileSystem
705 .writeFile({ cwd, relativePath: ".git/config", contents: "[core]\n\tfsmonitor = x\n" })
706 .pipe(Effect.flip);
707
708 expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceFilePathEscapeError);
709 expect(yield* fileSystem.readFileString(path.join(cwd, "shared/config"))).toBe(
710 "[core]\n",
711 );
712 }),
713 );
714
715 it.effect("writes files that sit beside git's folders", () =>
716 Effect.gen(function* () {
717 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
718 const fileSystem = yield* FileSystem.FileSystem;
719 const path = yield* Path.Path;
720 const parentDir = yield* makeTempDir;
721 const bare = path.join(parentDir, "repo.git");
722 yield* writeTextFile(bare, "HEAD", "ref: refs/heads/main\n");
723 yield* writeTextFile(bare, "objects/info/packs");
724 yield* writeTextFile(bare, "refs/heads/main");
725 yield* writeTextFile(bare, "main/.git", `gitdir: ${path.join(bare, "worktrees/main")}\n`);
726
727 for (const [cwd, relativePath] of [
728 [path.join(bare, "main"), ".gitignore"],
729 [path.join(bare, "main"), ".gitattributes"],
730 [path.join(bare, "main"), ".github/workflows/ci.yml"],
731 [path.join(bare, "main"), "vendor/lib.git/README.md"],
732 [path.join(bare, "main/.github"), "CODEOWNERS"],
733 [bare, "main/plan.md"],
734 ] as const) {
735 yield* workspaceFileSystem.writeFile({ cwd, relativePath, contents: "ok\n" });
736 expect(yield* fileSystem.readFileString(path.join(cwd, relativePath))).toBe("ok\n");
737 }
738 }),
739 );
740 });
741});