blob: 51b2bd0d2e28453f8cf71b2e268c756a942c14bd (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
|
/*
* This file is part of smolbote. It's copyrighted by the contributors recorded
* in the version control history of the file, available from its original
* location: https://neueland.iserlohn-fortress.net/cgit/smolbote
*
* SPDX-License-Identifier: GPL-3.0
*/
#pragma once
#include <configuration.h>
#include <fstream>
#include <cstdlib>
#include <filesystem>
#include <array>
#include <spdlog/spdlog.h>
inline auto init_conf(const std::string &path)
{
namespace fs = std::filesystem;
struct {
std::optional<fs::path> path;
std::unique_ptr<Configuration> ptr;
} conf;
conf.ptr = std::make_unique<Configuration, std::initializer_list<std::pair<std::string, conf_value_t>>>({
@__DEFAULT_CFG__
});
conf.path = [&]() -> std::optional<fs::path> {
if(!path.empty()) {
return fs::path(path);
}
// 1000: invalid; 0: $HOME; 1: $XDG_CONFIG_HOME
std::array<std::optional<fs::path>, 2> home = { std::nullopt, std::nullopt };
if(const char* usr = std::getenv("HOME"))
home[0] = fs::path(usr);
if(const char* xdg = std::getenv("XDG_CONFIG_HOME"))
home[1] = fs::path(xdg);
for(const auto &pair : {
@__CONFIG_PATHS__
}) {
if(pair.first < 0) {
auto p = fs::path(pair.second);
spdlog::debug("Trying {}", p.c_str());
if(fs::exists(p))
return p;
} else if(home[static_cast<std::size_t>(pair.first)]) {
auto p = home[static_cast<std::size_t>(pair.first)].value() / pair.second;
spdlog::debug("Trying {}", p.c_str());
if(fs::exists(p))
return p;
}
}
return std::nullopt;
}();
if(conf.path) {
std::fstream file(conf.path.value(), std::fstream::in);
if(file.is_open()) {
conf.ptr->read(file);
file.close();
}
}
return conf;
}
|