SRS-control 0.1.4
Loading...
Searching...
No Matches
ConfigHandler.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <filesystem>
4#include <glaze/core/opts.hpp>
5#include <glaze/core/reflect.hpp>
6#include <glaze/glaze.hpp>
7#include <glaze/json/read.hpp>
8#include <glaze/json/write.hpp>
9#include <spdlog/spdlog.h>
11#include <string>
12#include <string_view>
13
14namespace srs::config
15{
16 inline void output_config_to_json(const Config& app_config, std::string_view json_filename)
17 {
18 if (std::filesystem::exists(json_filename))
19 {
20 spdlog::critical("Cannot dump the default value to the configuration file {:?} as it's already existed!",
21 json_filename);
22 return;
23 }
24 const auto parent_dir = std::filesystem::absolute(std::filesystem::path{ json_filename }).parent_path();
25 std::filesystem::create_directories(parent_dir);
26 auto buffer = std::string{};
27 auto error_code = glz::write_file_json<glz::opts{ .prettify = true, .new_lines_in_arrays = false }>(
28 app_config, json_filename, buffer);
29 if (error_code)
30 {
31 spdlog::warn("Error occurred during writing the json file {}: {}",
32 json_filename,
33 glz::format_error(error_code, buffer));
34 }
35 }
36
37 inline void set_config_from_json(Config& app_config, std::string_view json_filename)
38 {
39 if (json_filename.empty())
40 {
41 return;
42 }
43 if (not std::filesystem::exists(json_filename))
44 {
45 spdlog::warn("configuration file {:?} doesn't exist. Creating a new file with default values",
46 json_filename);
47 output_config_to_json(app_config, json_filename);
48 }
49 else
50 {
51 auto buffer = std::string{};
52 auto error_code = glz::read_file_json(app_config, json_filename, buffer);
53 if (error_code)
54 {
55 spdlog::warn("Error occurred during reading the json file {}: {}",
56 json_filename,
57 glz::format_error(error_code, buffer));
58 }
59 }
60 }
61
62} // namespace srs::config
void output_config_to_json(const Config &app_config, std::string_view json_filename)
void set_config_from_json(Config &app_config, std::string_view json_filename)
Main configuration struct.