Open History to see the last commit
1import * as Effect from "effect/Effect";
2import * as FileSystem from "effect/FileSystem";
3import * as Path from "effect/Path";
4
5export const writeFileStringAtomically = (input: {
6 readonly filePath: string;
7 readonly contents: string;
8}) =>
9 Effect.scoped(
10 Effect.gen(function* () {
11 const fs = yield* FileSystem.FileSystem;
12 const path = yield* Path.Path;
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, "contents.tmp");
21
22 yield* fs.writeFileString(tempPath, input.contents);
23 yield* fs.rename(tempPath, input.filePath);
24 }),
25 );