70 lines
1.6 KiB
C++
70 lines
1.6 KiB
C++
//
|
|
// Created by selim on 09.01.2022.
|
|
//
|
|
|
|
#include "Settings.h"
|
|
#include <nlohmann/json.hpp>
|
|
|
|
#include <cstdlib>
|
|
#include <iostream>
|
|
#include <fstream>
|
|
|
|
fs::path Settings::getDataPath() {
|
|
auto dataDir = std::getenv("XDG_DATA_HOME");
|
|
if(dataDir) {
|
|
return fs::path(dataDir) / "autocat";
|
|
}
|
|
|
|
auto home = std::getenv("HOME");
|
|
if(home) {
|
|
return fs::path(home) / ".local" / "share" / "autocat";
|
|
}
|
|
|
|
throw std::runtime_error("Failed to find data home directory");
|
|
}
|
|
|
|
std::string readString(const fs::path& path) {
|
|
std::ifstream stream(path);
|
|
stream.seekg(0, std::ios::end);
|
|
auto size = stream.tellg();
|
|
std::string buffer(size, ' ');
|
|
stream.seekg(0);
|
|
stream.read(&buffer[0], size);
|
|
return buffer;
|
|
}
|
|
|
|
void writeString(const fs::path& path, const std::string& text) {
|
|
std::ofstream stream(path);
|
|
stream << text;
|
|
}
|
|
|
|
Settings Settings::instance() {
|
|
static Settings instance;
|
|
return instance;
|
|
}
|
|
|
|
Settings::Settings() {
|
|
_dataPath = getDataPath();
|
|
if(!fs::exists(_dataPath)) {
|
|
fs::create_directories(_dataPath);
|
|
}
|
|
}
|
|
|
|
User Settings::user() const {
|
|
auto userFile = _dataPath / "user.json";
|
|
if(fs::exists(userFile)) {
|
|
auto jsonText = readString(userFile);
|
|
std::cout << "User json text: " << jsonText << std::endl;
|
|
return nlohmann::json::parse(jsonText).get<User>();
|
|
} else {
|
|
return {};
|
|
}
|
|
}
|
|
|
|
void Settings::setUser(const User &user) {
|
|
auto userFile = _dataPath / "user.json";
|
|
nlohmann::json json = user;
|
|
auto userString = json.dump(4);
|
|
writeString(userFile, userString);
|
|
}
|