Browse Source

Move try/catch from settings to file, overwrite invalid settings file

master
Riyyi 4 years ago
parent
commit
cdbb456ce8
  1. 28
      inferno/src/inferno/io/file.h
  2. 18
      inferno/src/inferno/settings.cpp
  3. 2
      inferno/src/inferno/settings.h

28
inferno/src/inferno/io/file.h

@ -19,28 +19,48 @@ namespace Inferno {
static int32_t length(const std::string& path, std::ifstream& file);
template<typename T>
static void ioRead(T* t, const std::string& path)
static bool ioRead(T* t, const std::string& path)
{
std::ifstream file(path);
ASSERT(file.is_open(), "File could not open '{}'", path);
if (file.is_open()) {
if (!file.is_open()) {
return false;
}
try {
file >> *t;
}
catch (...) {
file.close();
return false;
}
file.close();
return true;
}
template<typename T>
static void ioWrite(T* t, const std::string& path)
static bool ioWrite(T* t, const std::string& path)
{
std::ofstream file (path);
ASSERT(file.is_open(), "File could not open! {}", path);
if (file.is_open()) {
if (!file.is_open()) {
return false;
}
try {
// Write file with single tabs, nicely formatted
file << std::setfill ('\t') << std::setw(1) << *t << std::endl;
}
catch (...) {
file.close();
return false;
}
file.close();
return true;
}
};

18
inferno/src/inferno/settings.cpp

@ -15,6 +15,7 @@ namespace Inferno {
void Settings::initialize()
{
Settings::load();
Settings::save();
info() << "Settings initialized";
}
@ -23,29 +24,32 @@ namespace Inferno {
{
}
void Settings::load()
bool Settings::load()
{
json object;
try {
File::ioRead(&object, m_path);
}
catch (...) {
if (!File::ioRead(&object, m_path)) {
warn() << "Settings invalid formatting, using default values";
return false;
}
auto settings = Json::getPropertyValue<SettingsProperties>(object, json::value_t::object);
if (settings) {
m_properties = settings.value();
}
return true;
}
bool Settings::save()
{
json object = m_properties;
File::ioWrite(&object, m_path);
info() << "Settings saved";
if (!File::ioWrite(&object, m_path)) {
warn() << "Settings could not be saved";
return false;
}
info() << "Settings saved";
return true;
}

2
inferno/src/inferno/settings.h

@ -15,7 +15,7 @@ namespace Inferno {
static void initialize();
static void destroy();
static void load();
static bool load();
static bool save();
static inline SettingsProperties& get() { return m_properties; }

Loading…
Cancel
Save