From 57c99b4cd974f727faaa2c2bb655824c22dea1df Mon Sep 17 00:00:00 2001 From: Andrew Belt Date: Sat, 25 Feb 2023 15:01:51 -0500 Subject: [PATCH] Write to temp settings.json file and overwrite, in case Rack crashes while writing it. --- src/settings.cpp | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/settings.cpp b/src/settings.cpp index eb445125..04c50abd 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -8,6 +8,7 @@ #include #include #include +#include namespace rack { @@ -491,14 +492,17 @@ void save(std::string path) { json_t* rootJ = toJson(); if (!rootJ) return; + DEFER({json_decref(rootJ);}); - FILE* file = std::fopen(path.c_str(), "w"); + std::string tmpPath = path + ".tmp"; + FILE* file = std::fopen(tmpPath.c_str(), "w"); if (!file) return; - DEFER({std::fclose(file);}); json_dumpf(rootJ, file, JSON_INDENT(2)); - json_decref(rootJ); + std::fclose(file); + system::remove(path); + system::rename(tmpPath, path); } void load(std::string path) { @@ -515,9 +519,9 @@ void load(std::string path) { json_t* rootJ = json_loadf(file, 0, &error); if (!rootJ) throw Exception("Settings file has invalid JSON at %d:%d %s", error.line, error.column, error.text); + DEFER({json_decref(rootJ);}); fromJson(rootJ); - json_decref(rootJ); }