From 2c884ca690afd4cb8a93402616c42152b2d42612 Mon Sep 17 00:00:00 2001 From: tt2468 Date: Mon, 22 Apr 2024 22:28:45 -0700 Subject: [PATCH] utils: Make SetJsonFileContent() create directories by default --- src/utils/Json.cpp | 19 ++++++++++++++++--- src/utils/Json.h | 2 +- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/src/utils/Json.cpp b/src/utils/Json.cpp index 6f686494..9211b3dc 100644 --- a/src/utils/Json.cpp +++ b/src/utils/Json.cpp @@ -185,18 +185,31 @@ bool Utils::Json::GetJsonFileContent(std::string fileName, json &content) try { content = json::parse(f); } catch (json::parse_error &e) { - blog(LOG_WARNING, "Failed to decode content of JSON file `%s`. Error: %s", fileName.c_str(), e.what()); + blog(LOG_WARNING, "[Utils::Json::GetJsonFileContent] Failed to decode content of JSON file `%s`. Error: %s", fileName.c_str(), e.what()); return false; } return true; } -bool Utils::Json::SetJsonFileContent(std::string fileName, const json &content) +bool Utils::Json::SetJsonFileContent(std::string fileName, const json &content, bool makeDirs) { + if (makeDirs) { + std::error_code ec; + auto p = std::filesystem::path(fileName).parent_path(); + if (!ec && !std::filesystem::exists(p, ec)) + std::filesystem::create_directories(p, ec); + if (ec) { + blog(LOG_ERROR, "[Utils::Json::SetJsonFileContent] Failed to create path directories: %s", ec.message().c_str()); + return false; + } + } + std::ofstream f(fileName); - if (!f.is_open()) + if (!f.is_open()) { + blog(LOG_ERROR, "[Utils::Json::SetJsonFileContent] Failed to open file `%s` for writing", fileName.c_str()); return false; + } // Set indent to 2 spaces, then dump content f << std::setw(2) << content; diff --git a/src/utils/Json.h b/src/utils/Json.h index 57c9173d..b9f013c1 100644 --- a/src/utils/Json.h +++ b/src/utils/Json.h @@ -76,7 +76,7 @@ namespace Utils { obs_data_t *JsonToObsData(json j); json ObsDataToJson(obs_data_t *d, bool includeDefault = false); bool GetJsonFileContent(std::string fileName, json &content); - bool SetJsonFileContent(std::string fileName, const json &content); + bool SetJsonFileContent(std::string fileName, const json &content, bool makeDirs = true); static inline bool Contains(const json &j, std::string key) { return j.contains(key) && !j[key].is_null(); } } }