qxLib
layered_configs_manager.inl
Go to the documentation of this file.
1 /**
2 
3  @file layered_configs_manager.inl
4  @author Khrapov
5  @date 12.05.2026
6  @copyright © Nick Khrapov, 2026. All right reserved.
7 
8 **/
9 
10 namespace qx
11 {
12 
13 namespace details
14 {
15 
16 template<class T>
18 {
19  using type = T;
20 };
21 
22 template<>
23 struct layered_config_variable_type<string_view>
24 {
25  using type = string;
26 };
27 
28 } // namespace details
29 
30 inline void layered_configs_manager::set_app_description(string sAppDescription) noexcept
31 {
32  m_sAppDescription = std::move(sAppDescription);
33 }
34 
35 inline void layered_configs_manager::set_args(int argc, char* argv[]) noexcept
36 {
37  if (argc <= 0 || argv == nullptr)
38  {
39  m_Args.clear();
40  return;
41  }
42 
43  m_Args.clear();
44  m_Args.reserve(static_cast<size_t>(argc));
45  for (int i = 0; i < argc; ++i)
46  m_Args.push_back(to_string(cstring_view(argv[i])));
47 }
48 
49 inline bool layered_configs_manager::show_help() const noexcept
50 {
51  if (!contains_if(
52  m_Args,
53  [](const string& sValue)
54  {
55  const string_view svValue = sValue;
56  return svValue == QXT("--help") || svValue == QXT("-h");
57  }))
58  {
59  return false;
60  }
61 
62  struct data_with_runtime_name : details::layered_config_variable_data
63  {
64  string_view svRuntimeName;
65  };
66 
67  std::map<string_view, std::vector<data_with_runtime_name>> groups;
68  for (const auto& [svRuntimeName, data] : m_VariableData)
69  {
70  groups[data.svGroupName].emplace_back(data, svRuntimeName);
71  }
72 
73  for (std::vector<data_with_runtime_name>& lines : groups | std::views::values)
74  {
75  sort(
76  lines,
77  [](const data_with_runtime_name& left, const data_with_runtime_name& right)
78  {
79  return left.bRequired > right.bRequired && left.svFullCommandLineName > right.svFullCommandLineName;
80  });
81  }
82 
83  string sHelp;
84  if (!groups.empty())
85  {
86  constexpr string_view svRequired = QXT("required ");
87 
88  size_t nMaxFullCommandLineNameLength = 0;
89  size_t nMaxShortCommandLineNameLength = 0;
90  size_t nMaxTypeNameLength = 0;
91  size_t nMaxRequiredNameLength = 0;
92  for (const std::vector<data_with_runtime_name>& lines : groups | std::views::values)
93  {
94  for (const data_with_runtime_name& line : lines)
95  {
96  nMaxFullCommandLineNameLength =
97  std::max(nMaxFullCommandLineNameLength, line.svFullCommandLineName.size());
98  nMaxShortCommandLineNameLength =
99  std::max(nMaxShortCommandLineNameLength, line.svShortCommandLineName.size());
100  nMaxTypeNameLength = std::max(nMaxTypeNameLength, line.svTypeName.size());
101  nMaxRequiredNameLength = std::max(
102  nMaxRequiredNameLength,
103  line.bRequired ? svRequired.size() : line.pTToString(m_Variables.at(line.svRuntimeName)).size());
104  }
105  }
106 
107  sHelp.append_format(QXT("\n\nUsage: {} [options]\n"), m_Args[0]);
108  sHelp += QXT("Using formats: [--key], [-k], [--key=value], [-k=value], [--key value], [-k value]\n\n");
109 
110  if (!m_sAppDescription.empty())
111  sHelp.append_format(QXT("{}\n\n"), m_sAppDescription);
112 
113  for (const auto& [svGroupName, lines] : groups)
114  {
115  if (!svGroupName.empty())
116  sHelp.append_format(QXT("{}:\n"), svGroupName);
117  else
118  sHelp += QXT("General options:\n");
119 
120  sHelp +=
121  QXT("--------------------------------------------------------------------------------------------------"
122  "----------------------\n");
123 
124  for (const data_with_runtime_name& line : lines)
125  {
126  sHelp.append_format(
127  QXT("{:<{}} {:<{}} {:<{}} {:<{}}{}\n"),
128  line.svFullCommandLineName,
129  nMaxFullCommandLineNameLength,
130  line.svShortCommandLineName,
131  nMaxShortCommandLineNameLength,
132  line.svTypeName,
133  nMaxTypeNameLength,
134  line.bRequired ? svRequired
135  : string_view(line.pTToString(m_Variables.at(line.svRuntimeName)) + QXT(" ")),
136  nMaxRequiredNameLength,
137  line.svDescription);
138  }
139 
140  sHelp += QXT("\n");
141  }
142  }
143  else
144  {
145  sHelp += QXT("This app doesn't have any command line arguments.\n\n");
146  if (!m_sAppDescription.empty())
147  sHelp.append_format(QXT("{}\n\n"), m_sAppDescription);
148  }
149 
150  QX_LOG(qx::verbosity::important, sHelp);
151 
152  return true;
153 }
154 
155 inline bool layered_configs_manager::parse() noexcept
156 {
157  std::unordered_map<string_view, std::any> variables;
158 
159  // read default variables
160  for (const auto& [svRuntimeName, value] : m_DefaultVariables)
161  if (!m_Variables.contains(svRuntimeName))
162  variables[svRuntimeName] = value;
163 
164  // read envs
165  for (const auto& [svRuntimeName, data] : m_VariableData)
166  {
167  if (const char* pszEnvValue = std::getenv(to_cstring(data.svEnvName).c_str()))
168  {
169  std::optional<std::any> optValue = data.pStringToT(to_string(pszEnvValue));
170  if (!optValue)
171  continue;
172 
173  variables[svRuntimeName] = std::move(*optValue);
174  }
175  }
176 
177  // read command lines args
178  for (size_t i = 1; i < m_Args.size(); ++i)
179  {
180  const string_view svArgument = m_Args[i];
181 
182  bool bShortKey = false;
183  string_view svKey;
184  string_view svValue;
185 
186  svKey = string_view(svArgument.begin(), svArgument.end());
187  if (svArgument.starts_with(QXT("--")))
188  {
189  bShortKey = false;
190  }
191  else if (svArgument.starts_with(QXT("-")))
192  {
193  bShortKey = true;
194  }
195  else
196  {
197  QX_LOG(
198  qx::verbosity::warning,
199  "Invalid command argument format: {}. "
200  "Use \"--key=value\", \"--key value\", \"-k value\", \"--key\", \"-k\" instead.",
201  svArgument);
202  continue;
203  }
204 
205  // --key=value / -k=value
206  if (const size_t nEqualPos = svKey.find('='); nEqualPos != string_view::npos)
207  {
208  svValue = string_view(svKey.begin() + nEqualPos + 1, svKey.end());
209  svKey = string_view(svKey.begin(), svKey.begin() + nEqualPos);
210  }
211  // --key value / -k value
212  else if (i + 1 < m_Args.size())
213  {
214  const string_view svNextArgument = m_Args[i + 1];
215 
216  if (!svNextArgument.starts_with(QXT("-")))
217  {
218  svValue = svNextArgument;
219  ++i;
220  }
221  else
222  {
223  // --key / -k
224  svValue = QXT("true");
225  }
226  }
227  // --key / -k
228  else
229  {
230  svValue = QXT("true");
231  }
232 
233  if (svKey.empty())
234  {
235  QX_LOG(qx::verbosity::warning, "Empty command argument key: {}.", svArgument);
236  continue;
237  }
238 
239  if (svValue.empty())
240  {
241  QX_LOG(qx::verbosity::warning, "Empty command argument value: {}.", svArgument);
242  continue;
243  }
244 
245  for (const auto& [svRuntimeName, data] : m_VariableData)
246  {
247  const bool bNameMatches =
248  bShortKey && svKey == data.svShortCommandLineName || !bShortKey && svKey == data.svFullCommandLineName;
249  if (!bNameMatches)
250  continue;
251 
252  std::optional<std::any> optValue = data.pStringToT(svValue);
253  if (!optValue)
254  continue;
255 
256  variables[svRuntimeName] = std::move(*optValue);
257  break;
258  }
259  }
260 
261  bool bAllRequiredVariablesPresent = true;
262  for (const auto& [svRuntimeName, data] : m_VariableData)
263  {
264  if (data.bRequired && !variables.contains(svRuntimeName))
265  {
266  QX_LOG(qx::verbosity::error, "Required variable missing: {}.", data.svFullCommandLineName);
267  bAllRequiredVariablesPresent = false;
268  }
269  }
270 
271  // override default and previous values
272  for (const auto& [svRuntimeName, value] : variables)
273  m_Variables[svRuntimeName] = value;
274 
275  return bAllRequiredVariablesPresent;
276 }
277 
278 template<class T>
279 inline std::expected<T, layered_configs_manager::get_error> layered_configs_manager::get(
280  string_view svRuntimeName) const noexcept
281 {
282  const auto value = get(svRuntimeName);
283  if (!value)
284  return std::unexpected(value.error());
285 
286  const auto* pValue = std::any_cast<typename details::layered_config_variable_type<T>::type>(&value->get());
287  if (!pValue)
288  return std::unexpected(get_error::type_mismatch);
289 
290  return *pValue;
291 }
292 
293 template<class T>
294 inline std::expected<void, layered_configs_manager::set_error> layered_configs_manager::set(
295  string_view svRuntimeName,
296  T value) noexcept
297 {
298  using stored_type = typename details::layered_config_variable_type<T>::type;
299  return set(svRuntimeName, std::any(stored_type(std::move(value))));
300 }
301 
302 inline std::expected<std::reference_wrapper<const std::any>, layered_configs_manager::get_error>
303  layered_configs_manager::get(string_view svRuntimeName) const noexcept
304 {
305  const auto itValue = m_Variables.find(svRuntimeName);
306  if (itValue != m_Variables.end())
307  return std::cref(itValue->second);
308 
309  const auto itDefault = m_DefaultVariables.find(svRuntimeName);
310  if (itDefault == m_DefaultVariables.end())
311  return std::unexpected(get_error::unknown_variable);
312 
313  return std::cref(itDefault->second);
314 }
315 
316 inline std::expected<void, layered_configs_manager::set_error> layered_configs_manager::set(
317  string_view svRuntimeName,
318  std::any value) noexcept
319 {
320  const auto it = m_DefaultVariables.find(svRuntimeName);
321 
322  if (it == m_DefaultVariables.end())
323  return std::unexpected(set_error::unknown_variable);
324 
325  if (it->second.type() != value.type())
326  return std::unexpected(set_error::type_mismatch);
327 
328  m_Variables[it->first] = std::move(value);
329  return {};
330 }
331 
332 inline std::expected<string, layered_configs_manager::get_error> layered_configs_manager::get_string(
333  string_view svRuntimeName) const noexcept
334 {
335  const std::expected<std::reference_wrapper<const std::any>, get_error> value = get(svRuntimeName);
336  if (!value)
337  return std::unexpected(value.error());
338 
339  return m_VariableData.at(svRuntimeName).pTToString(value->get());
340 }
341 
342 inline std::expected<void, layered_configs_manager::set_error> layered_configs_manager::set_string(
343  string_view svRuntimeName,
344  string_view svValue) noexcept
345 {
346  const auto itData = m_VariableData.find(svRuntimeName);
347  if (itData == m_VariableData.end())
348  return std::unexpected(set_error::unknown_variable);
349 
350  auto optValue = itData->second.pStringToT(svValue);
351  if (!optValue)
352  return std::unexpected(set_error::invalid_value);
353 
354  return set(svRuntimeName, std::move(*optValue));
355 }
356 
357 inline std::vector<layered_config_variable_info> layered_configs_manager::get_variables() const noexcept
358 {
359  std::vector<layered_config_variable_info> variables;
360  for (const auto& [svName, data] : m_VariableData)
361  variables.emplace_back(svName, data.svDescription, data.svTypeName, data.svGroupName);
362 
363  std::ranges::sort(variables, {}, &layered_config_variable_info::svName);
364  return variables;
365 }
366 
367 inline void layered_configs_manager::reset() noexcept
368 {
369  m_Variables.clear();
370 }
371 
372 template<class T>
373 void layered_configs_manager::add_variable(
374  string_view svRuntimeName,
376  T defaultValue) noexcept
377 {
378  m_VariableData[svRuntimeName] = data;
379  m_DefaultVariables[svRuntimeName] = typename details::layered_config_variable_type<T>::type(defaultValue);
380 }
381 
382 } // namespace qx
requires format_acceptable_args_c< char_t, args_t... > void append_format(const format_string_type< std::type_identity_t< args_t >... > sFormat, args_t &&... args) noexcept
Append the formatted string to the current one.
Definition: string.inl:146
std::expected< void, set_error > set_string(string_view svRuntimeName, string_view svValue) noexcept
Set a variable from text using its existing registered parser.
void set_app_description(string sAppDescription) noexcept
Set app description. It will be shown in help message.
get_error
Errors returned when reading a registered variable.
std::vector< layered_config_variable_info > get_variables() const noexcept
Enumerate registered variables without exposing converters or stored values.
std::expected< void, set_error > set(string_view svRuntimeName, T value) noexcept
Set variable value by runtime name. Only set if the variable type matches.
void reset() noexcept
Clear all variables and command line arguments. You should call parse() after that to set variables a...
std::expected< string, get_error > get_string(string_view svRuntimeName) const noexcept
Read a value through its registered string formatter without knowing its C++ type.
std::expected< T, get_error > get(string_view svRuntimeName) const noexcept
Get variable value by runtime name.
bool parse() noexcept
Parse command line arguments, environment variables, and default values.
bool show_help() const noexcept
Show help message if "--help" or "-h" argument is present in command line arguments.
void set_args(int argc, char *argv[]) noexcept
Copy command line arguments, converting narrow input with to_string().
bool contains_if(fwd_it_t itBegin, fwd_it_t itEnd, const predicate_t &predicate)
Check if at least one of range's elements satisfies a predicate.
Definition: contains.h:55
#define QX_LOG(eVerbosity,...)
Log message.
Definition: logger.h:38
void sort(random_it_t begin, random_it_t end, compare_t compare=compare_t())
Sort by the most suitable algorithm.
Definition: sort.inl:522
void to_cstring(cstring &out, wstring_view stringView, const std::locale &locale=get_locale())
Convert wstring to cstring.
void to_string(string &out, cstring_view stringView, const std::locale &locale=get_locale())
Convert a char string to common string type.