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

atomicWrite.ts

27 lines952 Bytes

1import * as Effect from "effect/Effect";
2import * as FileSystem from "effect/FileSystem";
3import * as Path from "effect/Path";
4import * as Random from "effect/Random";
5​
6export const writeFileStringAtomically = (input: {
7 readonly filePath: string;
8 readonly contents: string;
9}) =>
10 Effect.scoped(
11 Effect.gen(function* () {
12 const fs = yield* FileSystem.FileSystem;
13 const path = yield* Path.Path;
14 const tempFileId = yield* Random.nextUUIDv4;
15 const targetDirectory = path.dirname(input.filePath);
16​
17 yield* fs.makeDirectory(targetDirectory, { recursive: true });
18 const tempDirectory = yield* fs.makeTempDirectoryScoped({
19 directory: targetDirectory,
20 prefix: `${path.basename(input.filePath)}.`,
21 });
22 const tempPath = path.join(tempDirectory, `${tempFileId}.tmp`);
23​
24 yield* fs.writeFileString(tempPath, input.contents);
25 yield* fs.rename(tempPath, input.filePath);
26 }),
27 );