Removing temp file on error

Signed-off-by: Alex Andreev <alex.andreev.email@gmail.com>
This commit is contained in:
Alex Andreev authored and Sebastian Malton committed 2021-08-26 12:24:58 -04:00
1 parent 87926c2498
commit 3d1fdff094
1 file changed
+5 -2
@@ -24,16 +24,19 @@ import fs from "fs";
import tempy from "tempy"; import tempy from "tempy";
import * as lockFile from "proper-lockfile"; import * as lockFile from "proper-lockfile";
import YAML from "json-to-pretty-yaml"; import YAML from "json-to-pretty-yaml";
import { noop } from "../../utils";
export async function saveKubeconfig(config: KubeConfig, path: string) { export async function saveKubeconfig(config: KubeConfig, path: string) {
const tmpFilePath = tempy.file();
lockFile.lock(path).then(async (release) => { lockFile.lock(path).then(async (release) => {
const tmpFilePath = tempy.file();
const contents = YAML.stringify(JSON.parse(config.exportConfig())); const contents = YAML.stringify(JSON.parse(config.exportConfig()));
await fs.promises.writeFile(tmpFilePath, contents); await fs.promises.writeFile(tmpFilePath, contents);
await fs.promises.rename(tmpFilePath, path); await fs.promises.rename(tmpFilePath, path);
release(); release();
}).catch((e) => { }).catch(async (e) => {
await fs.unlink(tmpFilePath, noop);
throw new Error(`Failed to acquire lock file.\n${e}`); throw new Error(`Failed to acquire lock file.\n${e}`);
}); });
} }