sandbox
Loading...
Searching...
No Matches
cli.hpp
1// SPDX-License-Identifier: MIT
2#ifndef LIBSBX_CORE_CLI_HPP_
3#define LIBSBX_CORE_CLI_HPP_
4
5#include <string>
6#include <string_view>
7#include <span>
8#include <vector>
9#include <string_view>
10#include <concepts>
11#include <cinttypes>
12#include <optional>
13#include <charconv>
14
15#include <fmt/format.h>
16
17#include <libsbx/utility/logger.hpp>
18
19namespace sbx::core {
20
21template<typename Type>
22concept argument = (std::is_same_v<Type, bool> || std::is_integral_v<Type> || std::is_floating_point_v<Type> || std::is_same_v<Type, std::string>);
23
24class cli {
25
26 friend class engine;
27
28public:
29
30 cli(std::span<std::string_view> args) {
31 for (const auto& arg : args) {
32 if (arg.substr(0, 2) != "--") {
33 continue;
34 }
35
36 const auto pos = arg.find_first_of("=");
37
38 if (pos == std::string::npos) {
39 utility::logger<"core">::warn("Could not parse argument: '{}'", arg);
40 continue;
41 }
42
43 const auto key = std::string{arg.substr(2, pos - 2u)};
44 const auto value = std::string{arg.substr(pos + 1u)};
45
46 _arguments[key] = std::move(value);
47 }
48 }
49
50 template<argument Type>
51 auto argument(const std::string& name) const -> std::optional<Type> {
52 if (auto entry = _arguments.find(name); entry != _arguments.end()) {
53 const auto& value = entry->second;
54
55 if constexpr (std::is_same_v<Type, bool>) {
56 if (value == "true") {
57 return true;
58 } else if (value == "false") {
59 return false;
60 } else {
61 return std::nullopt;
62 }
63 } else if constexpr (std::is_floating_point_v<Type> || std::is_integral_v<Type>) {
64 auto result = Type{};
65
66 auto [ptr, ec] = std::from_chars(value.data(), value.data() + value.size(), result);
67
68 if (ec == std::errc::invalid_argument || ec == std::errc::result_out_of_range) {
69 return std::nullopt;
70 }
71
72 return result;
73 } else if constexpr (std::is_same_v<Type, std::string>) {
74 return value;
75 }
76 }
77
78 return std::nullopt;
79 }
80
81private:
82
83 auto _argument_value(const std::string& name) -> std::optional<std::string> {
84 if (auto entry = _arguments.find(name); entry != _arguments.end()) {
85 return entry->second;
86 }
87
88 return std::nullopt;
89 }
90
91 std::unordered_map<std::string, std::string> _arguments;
92
93}; // class cli
94
95} // namespace sbx::core
96
97#endif // LIBSBX_CORE_CLI_HPP_
Definition: cli.hpp:24
Definition: engine.hpp:32
Definition: logger.hpp:124