summaryrefslogtreecommitdiff
path: root/src/cfg.cc
blob: b65246f1140ed9d50e2250f2ad3398b95f1b04e2 (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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
#include "cfg.hh"

#include "io.hh"
#include "line.hh"
#include "paths.hh"
#include "str.hh"

#include <charconv>
#include <cstdint>
#include <format>
#include <functional>
#include <map>
#include <memory>
#include <optional>
#include <string>
#include <string_view>
#include <system_error>
#include <utility>
#include <vector>

namespace cfg {

namespace {

inline char ascii_lowercase(char c) {
  if (c >= 'A' && c <= 'Z') {
    // NOLINTNEXTLINE(bugprone-narrowing-conversions)
    return c | 0x20;
  }
  return c;
}

bool ascii_lowercase_eq(std::string_view a, std::string_view b) {
  if (a.size() != b.size())
    return false;
  auto it_a = a.begin();
  auto it_b = b.begin();
  for (; it_a != a.end(); ++it_a, ++it_b) {
    if (ascii_lowercase(*it_a) != *it_b)
      return false;
  }
  return true;
}

class ConfigSingleImpl : public Config {
 public:
  ConfigSingleImpl() = default;

  bool load(std::filesystem::path const& path,
            std::vector<std::string>& errors) {
    auto io_reader = io::open(std::string(path));
    if (!io_reader.has_value()) {
      errors.push_back(
          std::format("Unable to open {} for reading", path.string()));
      return false;
    }
    bool all_ok = true;
    auto line_reader = line::open(std::move(io_reader.value()));
    while (true) {
      auto line = line_reader->read();
      if (line.has_value()) {
        auto trimmed = str::trim(line.value());
        if (trimmed.empty() || trimmed.front() == '#')
          continue;
        auto eq = trimmed.find('=');
        if (eq == std::string_view::npos) {
          errors.push_back(
              std::format("{}:{}: Invalid line, expected key = value.",
                          path.string(), line_reader->number()));
          all_ok = false;
          continue;
        }
        auto key = str::trim(trimmed.substr(0, eq));
        auto value = str::trim(trimmed.substr(eq + 1));
        auto ret = values_.emplace(key, value);
        if (!ret.second) {
          errors.push_back(std::format("{}:{}: Duplicate key {} ignored.",
                                       path.string(), line_reader->number(),
                                       key));
          all_ok = false;
          continue;
        }
      } else {
        switch (line.error()) {
          case io::ReadError::Eof:
            break;
          default:
            errors.push_back(std::format("{}: Read error", path.string()));
            all_ok = false;
            break;
        }
        break;
      }
    }
    return all_ok;
  }

  [[nodiscard]]
  std::optional<std::string_view> get(std::string_view name) const override {
    auto it = values_.find(name);
    if (it == values_.end())
      return std::nullopt;
    return it->second;
  }

 private:
  std::map<std::string, std::string, std::less<>> values_;
};

class ConfigXdgImpl : public Config {
 public:
  ConfigXdgImpl() = default;

  bool load(std::string_view name, std::vector<std::string>& errors) {
    bool all_ok = true;
    for (auto const& dir : paths::config_dirs()) {
      auto file = dir / name;
      if (std::filesystem::exists(file)) {
        auto cfg = std::make_unique<ConfigSingleImpl>();
        if (!cfg->load(file, errors))
          all_ok = false;
        configs_.push_back(std::move(cfg));
      }
    }
    return all_ok;
  }

  [[nodiscard]]
  std::optional<std::string_view> get(std::string_view name) const override {
    for (auto const& config : configs_) {
      auto ret = config->get(name);
      if (ret.has_value())
        return ret;
    }
    return std::nullopt;
  }

 private:
  std::vector<std::unique_ptr<ConfigSingleImpl>> configs_;
};

}  // namespace

bool Config::has(std::string_view name) const { return get(name).has_value(); }

std::optional<int64_t> Config::get_int64(std::string_view name) const {
  auto str = get(name);
  if (str.has_value()) {
    auto* const end = str->data() + str->size();
    int64_t ret;
    // NOLINTNEXTLINE(bugprone-suspicious-stringview-data-usage)
    auto [ptr, ec] = std::from_chars(str->data(), end, ret);
    if (ec == std::errc() && ptr == end)
      return ret;
  }
  return std::nullopt;
}

std::optional<uint64_t> Config::get_uint64(std::string_view name) const {
  auto str = get(name);
  if (str.has_value()) {
    auto* const end = str->data() + str->size();
    uint64_t ret;
    // NOLINTNEXTLINE(bugprone-suspicious-stringview-data-usage)
    auto [ptr, ec] = std::from_chars(str->data(), end, ret);
    if (ec == std::errc() && ptr == end)
      return ret;
  }
  return std::nullopt;
}

std::optional<bool> Config::get_bool(std::string_view name) const {
  auto str = get(name);
  if (str.has_value()) {
    if (ascii_lowercase_eq(str.value(), "true") ||
        ascii_lowercase_eq(str.value(), "yes"))
      return true;
    if (ascii_lowercase_eq(str.value(), "false") ||
        ascii_lowercase_eq(str.value(), "no"))
      return false;
  }
  return std::nullopt;
}

std::unique_ptr<Config> load_all(std::string_view name,
                                 std::vector<std::string>& errors) {
  auto ret = std::make_unique<ConfigXdgImpl>();
  ret->load(name, errors);
  return ret;
}

std::unique_ptr<Config> load_one(std::filesystem::path const& path,
                                 std::vector<std::string>& errors) {
  auto ret = std::make_unique<ConfigSingleImpl>();
  ret->load(path, errors);
  return ret;
}

}  // namespace cfg