logmeow/config.cpp

72 lines
2.1 KiB
C++
Raw Normal View History

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <fstream>
#include "config.h"
std::string get_config_path() {
const char* path;
path = getenv("XDG_CONFIG_HOME");
if (path) {
return std::string(path) + "/logmeow/config";
}
path = getenv("HOME");
if (path) {
return std::string(path) + "/.config/logmeow/config";
}
throw std::runtime_error("cannot find suitable config folder, please set XDG_CONFIG_HOME or HOME");
}
Config parse_config(FILE* file) {
size_t line_capacity_size = 128 * sizeof(char);
char* line = static_cast<char*>(malloc(line_capacity_size));
if (line == nullptr) {
throw std::bad_alloc();
}
Config config;
while (true) {
errno = 0;
if (getline(&line, &line_capacity_size, file) < 0) {
int errsv = errno;
free(line);
if (errsv == ENOMEM) {
throw std::bad_alloc();
} else if (errsv != 0) {
throw std::system_error(errsv, std::generic_category(), "getline()");
} else {
break;
}
}
if (line_capacity_size == 0 || line[0] == '\0' || line[0] == '#') {
continue;
}
if (char* newline = strchr(line, '\n')) {
*newline = '\0';
}
if (strncmp(line, "logcat_command=", 15 * sizeof(char)) == 0) {
config.logcat_command = &line[16];
} else {
std::invalid_argument e = std::invalid_argument(std::string("unknown config line: ") + line);
free(line);
throw e;
}
}
return config;
}
void write_config(std::ofstream& file, const Config& config) {
file << "# This is an auto-generated file, comments made will be lost\n"
<< "# This is a poor man's config file \"format\", there are only three legal lines:\n"
<< "# # a comment, only available at the start of a line\n"
<< "# (an empty line, no whitespace)\n"
<< "# key=value pairs, no spaces around the delimiter, and no unknown keys\n\n"
<< "logcat_command=" << config.logcat_command;
}