ArKanjo 0.5.1
A tool for find code duplicated functions in codebases
parser_options.hpp
Go to the documentation of this file.
1#pragma once
2#include <optional>
3#include <string>
4#include <map>
5#include <vector>
6#include <getopt.h>
7
9
15};
16
17struct CliOption {
18 const char *long_name;
21 const char *description {""};
22};
23
27#define OPTION_END {nullptr, 0, NoArgument, nullptr}
28
37 std::map<std::string, std::string> args;
38
46 std::vector<std::string> extra_args;
47
54 bool has(const std::string& name) const {
55 return args.find(name) != args.end();
56 }
57
64 std::optional<std::string_view> get(const std::string& name) const {
65 auto it = args.find(name);
66
67 if (it == args.end())
68 return std::nullopt;
69
70 return it->second;
71 }
72
83 template<typename T> std::optional<T> get_as(const std::string& name) const {
84 auto value = get(name);
85
86 if (!value)
87 return std::nullopt;
88
89 if constexpr (std::is_same_v<T, std::string>) {
90 return std::string(*value);
91 } else if constexpr (std::is_same_v<T, int>) {
92 return std::stoi(std::string(*value));
93 } else if constexpr (std::is_same_v<T, size_t>) {
94 return static_cast<size_t>(std::stoull(std::string(*value)));
95 } else if constexpr (std::is_same_v<T, double>) {
96 return std::stod(std::string(*value));
97 } else if constexpr (std::is_same_v<T, bool>) {
98 return *value == "true";
99 } else {
100 static_assert(!sizeof(T), "Unsupported type");
101 }
102 }
103};
104
117bool parse_options(int argc, char* argv[], const std::vector<CliOption>& options, ParsedOptions& ctx_options);
bool parse_options(int argc, char *argv[], const std::vector< CliOption > &options, ParsedOptions &ctx_options)
Analyzes command-line arguments and populates ParsedOptions.
ArgumentsType
@ RequiredArgument
@ OptionalArgument
@ NoArgument
@ PositionalArgument
ArgumentsType has_arg
const char * long_name
const char * description
std::vector< std::string > extra_args
List of extra arguments that are not options.
bool has(const std::string &name) const
Checks whether an option exists.
std::optional< std::string_view > get(const std::string &name) const
Returns the value of an option.
std::optional< T > get_as(const std::string &name) const
Returns the value of an option converted to the requested type.
std::map< std::string, std::string > args
Map from option name to value.