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