utils: Make SetJsonFileContent() create directories by default

This commit is contained in:
tt2468 2024-04-22 22:28:45 -07:00
parent f72f23a9d7
commit 2c884ca690
2 changed files with 17 additions and 4 deletions

View File

@ -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;

View File

@ -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(); }
}
}