#pragma once #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if defined(__unix__) || defined(__APPLE__) extern char** environ; // NOLINT #define VOID_CONFIG_HAS_ENVIRON 1 #endif namespace Void::Configuration { /// Layered key-value configuration store with dotted nested keys. /// /// Values are plain strings; typed access via get_as(). Layers are /// applied via overlay(): the last overlay wins on key conflicts. /// Typical usage: /// /// auto cfg = Config::from_env_prefix("MYAPP_"); // MYAPP_LOG__LEVEL → /// log.level if (auto r = Config::from_ini("app.ini"); r.has_value()) /// cfg.overlay(*r); // ini overrides env /// cfg.overlay(Config::from_args(argc, argv)); // --log.level=debug /// wins auto level = cfg.get_or("log.level", "info"); auto retries = /// cfg.get_as("net.retries"); // Result /// /// Sources: from_env / from_env_prefix (environment), from_file /// (KEY=VALUE), from_ini (sections become key prefixes), from_json /// (nested objects flatten into dotted keys), from_args (--key=value). class Config { public: Config() = default; /// Populate from specific named environment variables. /// Keys absent from the environment are silently skipped. [[nodiscard]] static Config from_env(std::initializer_list keys) { Config cfg; for (auto key : keys) { if (auto r = get_env(key); r.has_value()) { cfg.values_.emplace(std::string{key}, std::move(*r)); Void::Log::debug("Configuration", "from_env: loaded '{}'", key); } } return cfg; } /// Parse a KEY=VALUE text file (one pair per line, # for comments). /// Lines without '=' produce a warning log and are skipped. [[nodiscard]] static Void::Result::Result from_file(const std::filesystem::path& path) { auto text = Void::FileSystem::read_file(path); if (!text.has_value()) { return Void::Result::fail( std::format("Configuration::Config::from_file: {}", text.error().message())); } Config cfg; std::istringstream ss{*text}; std::string line; int lineno = 0; while (std::getline(ss, line)) { ++lineno; if (!line.empty() && line.back() == '\r') { line.pop_back(); } std::string_view sv{line}; while (!sv.empty() && sv.front() == ' ') { sv.remove_prefix(1); } if (sv.empty() || sv.front() == '#') { continue; } auto eq = sv.find('='); if (eq == std::string_view::npos) { Void::Log::warn("Configuration", "from_file: '{}' line {}: missing '='", path.string(), lineno); continue; } auto key = sv.substr(0, eq); while (!key.empty() && key.back() == ' ') { key.remove_suffix(1); } auto val = sv.substr(eq + 1); cfg.values_.emplace(std::string{key}, std::string{val}); } Void::Log::debug("Configuration", "from_file: loaded {} keys from '{}'", cfg.values_.size(), path.string()); return Void::Result::ok(std::move(cfg)); } /// Layer `other` on top: other's values win on key conflicts. void overlay(const Config& other) { for (const auto& [k, v] : other.values_) { values_.insert_or_assign(k, v); } } /// Explicit per-key override (highest priority). void set(std::string_view key, std::string value) { values_.insert_or_assign(std::string{key}, std::move(value)); } /// Look up a key. Returns an error if the key is not present. [[nodiscard]] Void::Result::Result get(std::string_view key) const { auto it = values_.find(std::string{key}); if (it == values_.end()) { return Void::Result::fail(std::format( "Configuration::Config::get: key '{}' not found", key)); } return Void::Result::ok(std::string_view{it->second}); } /// Look up a key, returning `fallback` when the key is absent. [[nodiscard]] std::string_view get_or(std::string_view key, std::string_view fallback = {}) const { auto it = values_.find(std::string{key}); return it != values_.end() ? std::string_view{it->second} : fallback; } [[nodiscard]] std::size_t size() const noexcept { return values_.size(); } [[nodiscard]] bool empty() const noexcept { return values_.empty(); } // ═════════════════════════════════════════════════════════════════ // Additional sources // ═════════════════════════════════════════════════════════════════ /// Scan the whole environment for variables starting with `prefix`. /// The prefix is stripped, `__` becomes `.`, and the key is /// lowercased: MYAPP_LOG__LEVEL=debug → log.level=debug. [[nodiscard]] static Config from_env_prefix(std::string_view prefix) { Config cfg; #ifdef VOID_CONFIG_HAS_ENVIRON for (char** env = environ; *env != nullptr; ++env) { const std::string_view kv{*env}; const auto eq = kv.find('='); if (eq == std::string_view::npos || !kv.starts_with(prefix)) { continue; } auto raw_key = kv.substr(prefix.size(), eq - prefix.size()); std::string key; key.reserve(raw_key.size()); for (std::size_t i = 0; i < raw_key.size(); ++i) { if (raw_key[i] == '_' && i + 1 < raw_key.size() && raw_key[i + 1] == '_') { key += '.'; ++i; } else { key += static_cast(std::tolower( static_cast(raw_key[i]))); } } cfg.values_.emplace(std::move(key), std::string{kv.substr(eq + 1)}); } Void::Log::debug("Configuration", "from_env_prefix('{}'): {} keys", prefix, cfg.size()); #else (void)prefix; #endif return cfg; } /// Parse an INI file: `[section]` + `key = value` becomes /// "section.key"; pairs before any section keep their bare key. [[nodiscard]] static Void::Result::Result from_ini(const std::filesystem::path& path) { auto text = Void::FileSystem::read_file(path); if (!text.has_value()) { return Void::Result::fail( std::format("Configuration::Config::from_ini: {}", text.error().message())); } return from_ini_text(*text); } [[nodiscard]] static Void::Result::Result from_ini_text(std::string_view text) { Void::Ini::IniFile ini; if (auto err = Void::Ini::IniFile::parse(ini, text); err.has_value()) { return Void::Result::fail(std::format( "Configuration::Config::from_ini: line {}: {}", err->line, err->message)); } Config cfg; for (const auto& name : ini.sections()) { const auto* section = ini.section(name); if (section == nullptr) { continue; } for (const auto& [key, value] : *section) { auto full = name.empty() ? key : name + "." + key; cfg.values_.insert_or_assign(std::move(full), value); } } return Void::Result::ok(std::move(cfg)); } /// Parse a JSON file; nested objects flatten into dotted keys, /// arrays into numeric segments ("servers.0.host"). Scalars are /// stored in their canonical string form. [[nodiscard]] static Void::Result::Result from_json(const std::filesystem::path& path) { auto text = Void::FileSystem::read_file(path); if (!text.has_value()) { return Void::Result::fail( std::format("Configuration::Config::from_json: {}", text.error().message())); } return from_json_text(*text); } [[nodiscard]] static Void::Result::Result from_json_text(std::string_view text) { auto parsed = Void::Json::parse(text); if (!parsed.has_value()) { return Void::Result::fail(std::format( "Configuration::Config::from_json: line {} col {}: {}", parsed.error().line, parsed.error().col, parsed.error().message)); } Config cfg; flatten_json(cfg, "", *parsed); return Void::Result::ok(std::move(cfg)); } /// Collect `--key=value`, `--key value` and bare `--flag` /// (stored as "true") arguments. Non-option arguments are ignored. [[nodiscard]] static Config from_args(int argc, const char* const* argv) { Config cfg; for (int i = 1; i < argc; ++i) { const std::string_view arg{argv[i]}; if (!arg.starts_with("--") || arg.size() <= 2) { continue; } const auto body = arg.substr(2); if (const auto eq = body.find('='); eq != std::string_view::npos) { cfg.values_.insert_or_assign( std::string{body.substr(0, eq)}, std::string{body.substr(eq + 1)}); } else if (i + 1 < argc && std::string_view{argv[i + 1]}.substr(0, 2) != "--") { cfg.values_.insert_or_assign(std::string{body}, std::string{argv[i + 1]}); ++i; } else { cfg.values_.insert_or_assign(std::string{body}, "true"); } } return cfg; } // ═════════════════════════════════════════════════════════════════ // Typed access // ═════════════════════════════════════════════════════════════════ /// Look up and convert. Supported T: integral and floating types, /// bool ("true/false/1/0/yes/no/on/off", case-insensitive), enums /// (by enumerator name, reflection builds), std::string, and /// std::chrono durations ("250ms", "10s", "5m", "1h", "500us", /// "30ns" — converted to T, rejecting lossy narrowing). template [[nodiscard]] Void::Result::Result get_as(std::string_view key) const { const auto it = values_.find(std::string{key}); if (it == values_.end()) { return Void::Result::fail(std::format( "Configuration::Config::get_as: key '{}' not found", key)); } return convert(key, it->second); } /// Typed lookup with fallback for missing keys. Conversion errors /// on a *present* key still surface the fallback but are logged. template [[nodiscard]] T get_or_as(std::string_view key, T fallback) const { auto r = get_as(key); if (r.has_value()) { return std::move(*r); } return fallback; } // ═════════════════════════════════════════════════════════════════ // Key enumeration / subtrees // ═════════════════════════════════════════════════════════════════ /// All keys, sorted. [[nodiscard]] std::vector keys() const { std::vector out; out.reserve(values_.size()); for (const auto& [k, _] : values_) { out.push_back(k); } std::sort(out.begin(), out.end()); return out; } /// A new Config holding every key under "prefix." with the prefix /// stripped: subtree("log") of {log.level, log.file.path} yields /// {level, file.path}. [[nodiscard]] Config subtree(std::string_view prefix) const { Config out; const auto full = std::string{prefix} + "."; for (const auto& [k, v] : values_) { if (k.starts_with(full)) { out.values_.emplace(k.substr(full.size()), v); } } return out; } [[nodiscard]] bool contains(std::string_view key) const { return values_.contains(std::string{key}); } private: static void flatten_json(Config& cfg, const std::string& prefix, const Void::Json::Value& v) { using Void::Json::Value; if (v.is_object()) { for (const auto& [k, child] : v.as_object()) { flatten_json(cfg, prefix.empty() ? k : prefix + "." + k, child); } } else if (v.is_array()) { std::size_t i = 0; for (const auto& child : v.as_array()) { flatten_json(cfg, prefix + "." + std::to_string(i), child); ++i; } } else if (v.is_string()) { cfg.values_.insert_or_assign(prefix, v.as_string()); } else if (v.is_bool()) { cfg.values_.insert_or_assign(prefix, v.as_bool() ? "true" : "false"); } else if (v.is_int()) { cfg.values_.insert_or_assign( prefix, std::to_string(v.as_int())); } else if (v.is_uint()) { cfg.values_.insert_or_assign( prefix, std::to_string(v.as_uint())); } else if (v.is_number()) { const double d = v.as_number(); if (std::isfinite(d) && !(d == 0.0 && std::signbit(d)) && std::floor(d) == d && std::abs(d) < 1e15) { cfg.values_.insert_or_assign( prefix, std::to_string(static_cast(d))); } else { cfg.values_.insert_or_assign(prefix, std::format("{}", d)); } } // null: key omitted } template struct IsDuration : std::false_type { }; template struct IsDuration> : std::true_type { }; template static Void::Result::Result convert(std::string_view key, const std::string& raw) { auto fail = [&](std::string_view what) { return Void::Result::fail(std::format( "Configuration::Config::get_as: key '{}': {} ('{}')", key, what, raw)); }; if constexpr (std::is_same_v) { return Void::Result::ok(raw); } else if constexpr (std::is_same_v) { std::string lower; lower.reserve(raw.size()); for (const char c : raw) { lower += static_cast( std::tolower(static_cast(c))); } if (lower == "true" || lower == "1" || lower == "yes" || lower == "on") { return Void::Result::ok(true); } if (lower == "false" || lower == "0" || lower == "no" || lower == "off") { return Void::Result::ok(false); } return fail("not a boolean"); } else if constexpr (std::is_enum_v) { #ifdef VOID_HAS_ENUM_REFLECTION if (auto e = Void::Detail::enum_parse(raw); e.has_value()) { return Void::Result::ok(*e); } return fail("no such enumerator"); #else return fail("enum parsing requires reflection"); #endif } else if constexpr (IsDuration::value) { auto parsed = parse_duration(raw); if (!parsed.has_value()) { return fail("not a duration (use e.g. 250ms, 10s, 5m)"); } return Void::Result::ok( std::chrono::duration_cast(*parsed)); } else if constexpr (std::is_arithmetic_v) { T value{}; const char* begin = raw.data(); const char* end = raw.data() + raw.size(); const auto [ptr, ec] = std::from_chars(begin, end, value); if (ec == std::errc{} && ptr == end) { return Void::Result::ok(value); } // Byte-size units for integral targets: "10MB", "1GiB". if constexpr (std::is_integral_v) { if (auto bytes = parse_bytes(raw); bytes.has_value()) { return Void::Result::ok(static_cast(*bytes)); } return fail("not a number or byte size"); } return fail("not a number"); } else { static_assert(std::is_same_v, "unsupported get_as type"); } } static std::optional parse_duration(const std::string& raw) { // Single source of truth lives in Time/Format.hpp. return Void::Time::parse_duration(raw); } // Parse a byte-size string: a number followed by an SI // (KB/MB/GB/TB, powers of 1000) or binary (KiB/MiB/GiB/TiB, powers // of 1024) unit. A bare "B" or empty suffix means bytes. Returns // nullopt otherwise. static std::optional parse_bytes(const std::string& raw) { double number = 0; const char* begin = raw.data(); const char* end = raw.data() + raw.size(); const auto [ptr, ec] = std::from_chars(begin, end, number); if (ec != std::errc{} || ptr == begin) { return std::nullopt; } std::string_view suffix{ptr, end}; while (!suffix.empty() && suffix.front() == ' ') { suffix.remove_prefix(1); } double mult = 0; if (suffix.empty() || suffix == "B") { mult = 1.0; } else if (suffix == "KB") { mult = 1e3; } else if (suffix == "MB") { mult = 1e6; } else if (suffix == "GB") { mult = 1e9; } else if (suffix == "TB") { mult = 1e12; } else if (suffix == "KiB") { mult = 1024.0; } else if (suffix == "MiB") { mult = 1024.0 * 1024.0; } else if (suffix == "GiB") { mult = 1024.0 * 1024.0 * 1024.0; } else if (suffix == "TiB") { mult = 1024.0 * 1024.0 * 1024.0 * 1024.0; } else { return std::nullopt; } return static_cast(number * mult); } std::unordered_map values_; }; } // namespace Void::Configuration