aboutsummaryrefslogtreecommitdiff
path: root/src/config.cpp
blob: aec29a460ee7ac62ab5d8d76557595f05b91f984 (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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include <filesystem>
#include <vector>
#include <fstream>
#include <format>
#include <utility>

#include <ryml.hpp>
#include <ryml_std.hpp>
#include <mw/error.hpp>

#include "config.hpp"

namespace {

mw::E<std::vector<char>> readFile(const std::filesystem::path& path)
{
    std::ifstream f(path, std::ios::binary);
    std::vector<char> content;
    content.reserve(102400);
    content.assign(std::istreambuf_iterator<char>(f),
                   std::istreambuf_iterator<char>());
    if(f.bad() || f.fail())
    {
        return std::unexpected(mw::runtimeError(
            std::format("Failed to read file {}", path.string())));
    }

    return content;
}

} // namespace

mw::E<Configuration> Configuration::fromYaml(const std::filesystem::path& path)
{
    auto buffer = readFile(path);
    if(!buffer.has_value())
    {
        return std::unexpected(buffer.error());
    }

    ryml::Tree tree = ryml::parse_in_place(ryml::to_substr(*buffer));
    Configuration config;
    if(tree["listen-address"].readable())
    {
        tree["listen-address"] >> config.listen_address;
    }
    if(tree["listen-port"].readable())
    {
        tree["listen-port"] >> config.listen_port;
    }
    if(tree["socket-user"].readable())
    {
        tree["socket-user"] >> config.socket_user;
    }
    if(tree["socket-group"].readable())
    {
        tree["socket-group"] >> config.socket_group;
    }
    if(tree["socket-permission"].readable())
    {
        tree["socket-permission"] >> config.socket_permission;
    }
    if(tree["base-url"].readable())
    {
        tree["base-url"] >> config.base_url;
    }
    if(tree["data-dir"].readable())
    {
        tree["data-dir"] >> config.data_dir;
    }
    if(tree["openid-url-prefix"].readable())
    {
        tree["openid-url-prefix"] >> config.openid_url_prefix;
    }
    if(tree["client-id"].readable())
    {
        tree["client-id"] >> config.client_id;
    }
    if(tree["client-secret"].readable())
    {
        tree["client-secret"] >> config.client_secret;
    }

    return mw::E<Configuration>{std::in_place, std::move(config)};
}