Skip to content

Commit

Permalink
fix: write to tmp file and rename to prevent cache corruption
Browse files Browse the repository at this point in the history
  • Loading branch information
Jnig committed Jan 15, 2024
1 parent c064aff commit bbec078
Showing 1 changed file with 17 additions and 5 deletions.
22 changes: 17 additions & 5 deletions lib/config.mjs
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
import os from "os";
import { readFile, writeFile, access, mkdir, unlink } from "fs/promises";
import {
readFile,
writeFile,
access,
mkdir,
unlink,
rename,
} from "fs/promises";
import { join } from "path";
import ini from "ini";
import crypto from "crypto";
Expand Down Expand Up @@ -36,7 +43,7 @@ async function prepareConfig() {
}

export async function getCliConfig() {
return import("../config.json")
return import("../config.json");
}

export async function writeDefaultSessions() {
Expand All @@ -50,7 +57,7 @@ export async function writeDefaultSessions() {
if (!awsConfig[key]) {
awsConfig[key] = sessions[key];
} else {
awsConfig[key] = {...sessions[key], ...awsConfig[key]};
awsConfig[key] = { ...sessions[key], ...awsConfig[key] };
}
});

Expand Down Expand Up @@ -100,7 +107,10 @@ export async function writeCache(sessionName, config) {
};

const cacheFile = join(cacheDir, getHash(sessionName) + ".json");
await writeFile(cacheFile, JSON.stringify(cache, null, 2));
const tmpFile = cacheFile + ".tmp";

await writeFile(tmpFile, JSON.stringify(cache, null, 2));
await rename(tmpFile, cacheFile);
}

export async function deleteCache(sessionName) {
Expand Down Expand Up @@ -132,6 +142,8 @@ export async function readAccountCache(sessionName) {

export async function writeAccountCache(sessionName, accounts) {
const cacheFile = join(cacheDir, sessionName + "-accounts.json");
const tmpFile = cacheFile + ".tmp";

return await writeFile(cacheFile, JSON.stringify(accounts));
await writeFile(tmpFile, JSON.stringify(accounts, null, 2));
await rename(tmpFile, cacheFile);
}

0 comments on commit bbec078

Please sign in to comment.