Open History to see the last commit
1import * as Effect from "effect/Effect";
2import * as FileSystem from "effect/FileSystem";
3import * as Layer from "effect/Layer";
4import * as PlatformError from "effect/PlatformError";
5// @effect-diagnostics-next-line nodeBuiltinImport:off -- types the unpatched `original-fs` module.
6import type * as NodeFS from "node:fs";
7
8const errorTag = (code: unknown): PlatformError.SystemErrorTag => {
9 switch (code) {
10 case "ENOENT":
11 return "NotFound";
12 case "EACCES":
13 case "EPERM":
14 return "PermissionDenied";
15 case "EEXIST":
16 return "AlreadyExists";
17 case "EISDIR":
18 case "ENOTDIR":
19 case "ELOOP":
20 return "BadResource";
21 case "EBUSY":
22 return "Busy";
23 case "ENOTEMPTY":
24 return "DirectoryNotEmpty";
25 default:
26 return "Unknown";
27 }
28};
29
30/**
31 * Under Electron, `node:fs` treats `.asar` files as folders and never unlinks them, so a recursive
32 * delete of a folder holding one (Electron in a worktree's `node_modules`) fails partway with
33 * ENOTEMPTY. Recursive deletes go through `original-fs`, Electron's unpatched fs; plain Node has none.
34 */
35export const layer = Layer.effect(
36 FileSystem.FileSystem,
37 Effect.gen(function* () {
38 const fileSystem = yield* FileSystem.FileSystem;
39 const originalFs = process.getBuiltinModule("original-fs") as typeof NodeFS | undefined;
40 if (originalFs === undefined) return fileSystem;
41 return FileSystem.make({
42 ...fileSystem,
43 remove: (path, options) =>
44 options?.recursive
45 ? Effect.tryPromise({
46 try: () =>
47 originalFs.promises.rm(path, { recursive: true, force: options.force ?? false }),
48 catch: (cause) =>
49 PlatformError.systemError({
50 _tag: errorTag(
51 cause instanceof Error && "code" in cause ? cause.code : undefined,
52 ),
53 module: "FileSystem",
54 method: "remove",
55 pathOrDescriptor: path,
56 cause,
57 }),
58 })
59 : fileSystem.remove(path, options),
60 });
61 }),
62);