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

atomicWrite.ts

37 lines1.4 KB

1import * as Effect from "effect/Effect";
2import * as FileSystem from "effect/FileSystem";
3import * as Path from "effect/Path";
4import { resolveSymlinkTarget } from "@t3tools/shared/symlink";
5​
6/**
7 * A symlinked target is resolved first so the link survives and its destination is
8 * rewritten, since renaming over the link itself would swap it for a regular file.
9 */
10export const writeFileStringAtomically = (input: {
11 readonly filePath: string;
12 readonly contents: string;
13}) =>
14 Effect.scoped(
15 Effect.gen(function* () {
16 const fs = yield* FileSystem.FileSystem;
17 const path = yield* Path.Path;
18 const targetPath = yield* resolveSymlinkTarget(input.filePath);
19 const targetDirectory = path.dirname(targetPath);
20​
21 yield* fs.makeDirectory(targetDirectory, { recursive: true });
22 // The temp directory is cleanup, not part of the write: failing to remove
23 // it (a virus scanner holding it on Windows) must not fail a write that
24 // already landed.
25 const tempDirectory = yield* Effect.acquireRelease(
26 fs.makeTempDirectory({
27 directory: targetDirectory,
28 prefix: `${path.basename(targetPath)}.`,
29 }),
30 (directory) => fs.remove(directory, { recursive: true }).pipe(Effect.ignore({ log: true })),
31 );
32 const tempPath = path.join(tempDirectory, "contents.tmp");
33​
34 yield* fs.writeFileString(tempPath, input.contents);
35 yield* fs.rename(tempPath, targetPath);
36 }),
37 );