#include "configpp.hpp" #include #include #include #include namespace configpp { std::unique_ptr Config::config_ptr = nullptr; #if defined( _WIN32 ) || defined( _WIN64 ) boost::filesystem::path get_config_base_dir() { if(!std::getenv("APPDATA")) { throw std::runtime_error("Environment variable \"APPDATA\" is not set, could not find suitable config home."); } boost::filesystem::path appdata(std::getenv("APPDATA")); return appdata } #endif #if defined( __unix__ ) && !defined( __APPLE__) && !defined( __MACH__ ) boost::filesystem::path get_config_base_dir() { boost::filesystem::path config_home; boost::filesystem::path path; if(!std::getenv("XDG_CONFIG_HOME")) { if(!std::getenv("HOME")) { throw std::runtime_error("Neither \"XDG_CONFIG_HOME\" nor \"HOME\" environment variable are set, could not find suitable config home."); } else { config_home = getenv("HOME"); path = config_home / boost::filesystem::path(".config"); } } else { path = getenv("XDG_CONFIG_HOME"); } return path; } #endif #if defined( __APPLE__ ) && defined( __MACH__ ) boost::filesystem::path get_config_base_dir(std::string subdir) { boost::filesystem::path path; if(!std::getenv("HOME")) { throw std::runtime_error("\"HOME\" environment variable is not set, could not find a suitable config home."); } else { path = boost::filesystem::path(std::getenv("HOME")); } return path; } #endif using namespace boost::filesystem; Config::Config(std::string subdir, std::string filename) : config() , subdir(subdir) , filename(filename) { auto dir = get_config_base_dir() / path(subdir); auto file_path = dir / filename; if(exists(file_path)) { std::ifstream file_stream(file_path.string()); boost::property_tree::read_json(file_stream, config); } } Config::~Config() { auto dir = get_config_base_dir() / path(subdir); auto file_path = dir / filename; if(!exists(dir)) { boost::filesystem::create_directories(dir); } std::ofstream file_stream(file_path.string()); boost::property_tree::write_json(file_stream, config); } } //namespace configpp