Skip to content
Source
Sign inSign up
Open History to see the last commit

removeEmptyDirectory.ts

31 lines1.1 KB

1// @effect-diagnostics nodeBuiltinImport:off - Effect's FileSystem has no rmdir.
2import * as NodeFSP from "node:fs/promises";
3​
4import * as Effect from "effect/Effect";
5import * as Schema from "effect/Schema";
6​
7export class RemoveEmptyDirectoryError extends Schema.TaggedError<RemoveEmptyDirectoryError>()(
8 "RemoveEmptyDirectoryError",
9 { path: Schema.String, cause: Schema.Defect() },
10) {
11 override get message(): string {
12 return `Could not remove the directory ${this.path}.`;
13 }
15​
16/**
17 * Removes `path` only while it is an empty directory. Succeeds with false when
18 * anything else is there, including files written after the caller looked.
19 * Other failures, such as a permission error, stay errors.
20 */
21export const removeEmptyDirectory = (path: string) =>
22 Effect.tryPromise({
23 try: () => NodeFSP.rmdir(path),
24 catch: (cause) => new RemoveEmptyDirectoryError({ path, cause }),
25 }).pipe(
26 Effect.as(true),
27 Effect.catchIf(
28 (error) => (error.cause as NodeJS.ErrnoException | undefined)?.code === "ENOTEMPTY",
29 () => Effect.succeed(false),
30 ),
31 );