diff options
| author | Dennis Brentjes <d.brentjes@gmail.com> | 2016-08-28 15:19:31 +0200 |
|---|---|---|
| committer | Dennis Brentjes <d.brentjes@gmail.com> | 2016-08-28 15:19:31 +0200 |
| commit | d86042141ef0a0e77935f4b48d1a627fc1ec776b (patch) | |
| tree | 4bc95d561c60306d1152f71aa53bd18d9229f172 /configpp.cpp | |
| download | configpp-master.tar.gz configpp-master.tar.bz2 configpp-master.zip | |
Diffstat (limited to 'configpp.cpp')
| -rw-r--r-- | configpp.cpp | 84 |
1 files changed, 84 insertions, 0 deletions
diff --git a/configpp.cpp b/configpp.cpp new file mode 100644 index 0000000..c434979 --- /dev/null +++ b/configpp.cpp @@ -0,0 +1,84 @@ + +#include "configpp.hpp" + +#include <boost/filesystem/path.hpp> +#include <boost/filesystem/operations.hpp> +#include <boost/property_tree/json_parser.hpp> + +#include <fstream> + +namespace configpp { + +std::unique_ptr<Config> 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
\ No newline at end of file |
