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