-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli-utility.cpp
More file actions
107 lines (88 loc) · 2.39 KB
/
cli-utility.cpp
File metadata and controls
107 lines (88 loc) · 2.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <CLI/CLI.hpp>
#define UTIL_VERSION "0.0.1"
typedef int (*FnPtr)(CLI::Option*);
struct util_cmd_option
{
CLI::Option *option;
FnPtr option_func;
};
class MyFormatter : public CLI::Formatter
{
protected:
std::string get_option_name(std::string str) const
{
std::map<std::string, std::string> cmd_table;
cmd_table["--help"] = "";
cmd_table["--version"] = "";
cmd_table["--add"] = " <a> <b>";
cmd_table["--square"] = " [<a>]";
return cmd_table[str];
}
public:
MyFormatter() : Formatter() {}
std::string make_option_opts(const CLI::Option * opt) const override
{
return get_option_name(opt->get_name());
}
};
static int
version(CLI::Option* opt)
{
std::cout << UTIL_VERSION << "\n";
return 0;
}
static int
add(CLI::Option* opt)
{
std::vector<int> arg;
opt->results(arg);
std::cout << arg[0] * arg[1] << "\n";
return 0;
}
static int
square(CLI::Option* opt)
{
std::vector<int> arg;
opt->results(arg);
std::cout << arg[0] * arg[0] << "\n";
return 0;
}
static int
cmd_init(CLI::App* app, std::vector<struct util_cmd_option>* opts)
{
CLI::Option *option;
option = app->add_flag("-v, --version", "Show program version");
opts->push_back({option, version});
option = app->add_option("-a, --add", "Return a + b\n<a> : 0 ~ 100\n<b> : 0 ~ 200");
option->expected(2);
option->check(CLI::Validator(CLI::Range(0, 100)).application_index(0));
option->check(CLI::Validator(CLI::Range(0, 200)).application_index(1));
opts->push_back({option, add});
option = app->add_option("-s, --square", "Return a * a");
option->expected(0, 1);
option->check(CLI::Range(0, 100));
opts->push_back({option, square});
return 0;
}
int
main(int argc, char **argv)
{
auto fmt = std::make_shared<MyFormatter>();
fmt->column_width(20);
CLI::App app("Calculator Utility");
app.failure_message(CLI::FailureMessage::help);
app.formatter(fmt);
std::vector< struct util_cmd_option > opts;
cmd_init(&app, &opts);
CLI11_PARSE(app, argc, argv);
for (size_t i = 0; i < opts.size(); i++) {
if (*(opts[i].option)) {
opts[i].option_func(opts[i].option);
}
}
return 0;
}