2#ifndef _CONSOLIX_CONFIG_COMPONENT_HPP_INCLUDED
3#define _CONSOLIX_CONFIG_COMPONENT_HPP_INCLUDED
9#if CONSOLIX_USE_JSON == 1
12#include <nlohmann/json.hpp>
23 template <
typename ConfigType>
24 class ConfigComponent :
public IAppComponent {
29 explicit ConfigComponent(
30 const std::string& default_file =
"config.json",
31 const std::string& cli_flag =
"--config")
32 : m_default_file(default_file), m_cli_flag(cli_flag) {
44 bool initialize()
override {
45 if (!has_service<CliOptions>()) {
50 if (!has_service<CliArguments>())
return false;
58 bool is_initialized()
const override {
63 void process()
override {}
66 std::string m_default_file;
67 std::string m_cli_flag;
68 ConfigType m_config_data;
69 std::atomic<bool> m_is_init{
false};
74 std::lock_guard<std::mutex> lock(m_mutex);
75 std::string config_path = resolve_file_path();
76# if defined(_WIN32) || defined(_WIN64)
77 std::ifstream file(utf8_to_ansi(config_path));
79 std::ifstream file(config_path);
83# if CONSOLIX_USE_LOGIT == 1
84 LOGIT_PRINT_ERROR(
"Failed to open config file: ", config_path);
88 "Failed to open config file: " << config_path;
89 throw std::runtime_error(
"Failed to open config file: " + config_path);
94 std::string json_content((std::istreambuf_iterator<char>(file)),
95 std::istreambuf_iterator<char>());
98 json_content = strip_json_comments(json_content);
101 nlohmann::json json_data = nlohmann::json::parse(json_content);
103 m_config_data = json_data.get<ConfigType>();
106 register_service<ConfigType>([
this]() {
107 return std::make_shared<ConfigType>(m_config_data);
109 }
catch (
const std::exception& e) {
110# if CONSOLIX_USE_LOGIT == 1
111 LOGIT_PRINT_ERROR(
"Failed to parse config file: ", e.what());
115 "Failed to parse config file: " << e.what();
122 std::string resolve_file_path() {
123 std::string config_path = m_default_file;
126 auto args = get_service<CliArguments>();
127 if (args.count(m_cli_flag)) {
128 config_path = args[m_cli_flag].as<std::string>();
130# if defined(_WIN32) || defined(_WIN64)
131 return get_exec_dir() +
"\\" + config_path;
133 return get_exec_dir() +
"/" + config_path;
136# if defined(_WIN32) || defined(_WIN64)
137 return get_exec_dir() +
"\\" + m_default_file;
139 return get_exec_dir() +
"/" + m_default_file;
#define CONSOLIX_STREAM()
Fallback for general logging.
< Utility modules and helpers.
ColorManipulator color(TextColor color)
Creates a color manipulator for use in output streams.