Refactor: Config System

This commit is contained in:
xiaozhou233 committed 2026-03-24 19:24:37 +08:00
1 parent 9dab75b5fd
commit 205e608d60
2 files changed
+40 -67

No files matched your search

+25 -67
View File
@@ -1,86 +1,44 @@
#include <string>
#include <fstream>
#include <stdexcept>
#include <filesystem>
#pragma once
#include <JuiceAgent/Logger.hpp>
#include <tinytoml/toml.h>
#include <plog/Log.h>
#include <filesystem>
#include <fstream>
namespace config
{
class Config {
private:
std::string config_path;
toml::Value config;
toml::Value config{};
bool valid = false;
public:
Config(const std::string& config_path)
: config_path(config_path)
{
PLOGD << "[Config] Loading config file: " << config_path;
explicit Config(const char* c_runtime_dir) {
std::filesystem::path path = std::filesystem::path(c_runtime_dir) / "config.toml";
std::ifstream file(config_path);
if (!file.is_open()) {
PLOGE << "[Config] Failed to open config file: " << config_path;
throw std::runtime_error("Failed to open config file: " + config_path);
std::ifstream ifs(path);
if (!ifs.is_open()) {
PLOGE << "Failed to open config file: " << path;
return;
}
toml::ParseResult pr = toml::parse(file);
try {
auto pr = toml::parse(ifs);
if (!pr.valid()) {
PLOGE << "[Config] Failed to parse config file: " << config_path
<< " | Reason: " << pr.errorReason;
if (!pr.valid()) {
PLOGE << "Invalid TOML file: " << pr.errorReason;
return;
}
throw std::runtime_error(
"Failed to parse config file: " + config_path + "\n" + pr.errorReason
);
config = pr.value;
valid = true;
} catch (const std::exception& e) {
PLOGE << "TOML parse error: " << e.what();
}
config = pr.value;
PLOGI << "[Config] Successfully loaded config file: " << config_path;
}
template<typename T>
T get_or_default(const std::string& key, const T& default_value) const
{
const toml::Value* value = config.find(key);
if (!value) {
PLOGW << "[Config] Key not found: " << key
<< " | Using default value";
return default_value;
}
if (!value->is<T>()) {
PLOGE << "[Config] Type mismatch for key: " << key
<< " | Expected type does not match | Using default value";
return default_value;
}
PLOGD << "[Config] Read key: " << key;
return value->as<T>();
}
std::string get_path_or_default(const std::string& key, const std::string& def) const
{
std::string result = get_or_default<std::string>(key, def);
std::filesystem::path p(result);
if (p.is_relative()) {
std::filesystem::path full =
std::filesystem::path(config_path).parent_path() / p;
PLOGD << "[Config] Resolved relative path: " << result
<< " -> " << full.string();
return full.string();
}
PLOGD << "[Config] Using absolute path: " << result;
return result;
bool is_valid() const {
return valid;
}
};
}