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

atomicWrite.ts

25 lines876 Bytes

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