forked from pingdotgg/t3code
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathatomicWrite.ts
More file actions
25 lines (22 loc) · 876 Bytes
/
atomicWrite.ts
File metadata and controls
25 lines (22 loc) · 876 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import { Effect, FileSystem, Path } from "effect";
import * as Random from "effect/Random";
export const writeFileStringAtomically = (input: {
readonly filePath: string;
readonly contents: string;
}) =>
Effect.scoped(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempFileId = yield* Random.nextUUIDv4;
const targetDirectory = path.dirname(input.filePath);
yield* fs.makeDirectory(targetDirectory, { recursive: true });
const tempDirectory = yield* fs.makeTempDirectoryScoped({
directory: targetDirectory,
prefix: `${path.basename(input.filePath)}.`,
});
const tempPath = path.join(tempDirectory, `${tempFileId}.tmp`);
yield* fs.writeFileString(tempPath, input.contents);
yield* fs.rename(tempPath, input.filePath);
}),
);