-
Notifications
You must be signed in to change notification settings - Fork 0
/
cli.cpp
76 lines (62 loc) · 1.49 KB
/
cli.cpp
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
#include <cstdio>
#include <cstring>
#include "cli.hpp"
namespace cli {
const char* const kStatusMessages[] = {
"success", "invalid option argument type", "missing option argument",
"invalid option argument", "unexpected option name"};
const char* StatusMessage(Status s) { return kStatusMessages[s]; }
Status ParseOpts(uint argc, char* argv[], Opt opts[], uint opts_size,
uint* argi) {
uint i = 1;
while (i < argc && std::strncmp(argv[i], "--", 2) == 0) {
if (std::strcmp(argv[i], "--") == 0) {
++i;
break;
}
if (i + 1 >= argc) {
*argi = i;
return kStatus_MissingOptArg;
}
uint j = 0;
while (j < opts_size && std::strcmp(&argv[i][2], opts[j].name) != 0) {
++j;
}
if (j == opts_size) {
*argi = i;
return kStatus_UnexpectedOptName;
}
const char* format;
switch (opts[j].arg_type) {
case kOptArgType_Int: {
format = "%d";
break;
}
case kOptArgType_Uint: {
format = "%u";
break;
}
case kOptArgType_Float: {
format = "%f";
break;
}
case kOptArgType_String: {
format = "%s";
break;
}
default: {
*argi = i;
return kStatus_InvalidOptArgType;
}
}
int rc = std::sscanf(argv[i + 1], format, opts[j].arg);
if (rc != 1) {
*argi = i;
return kStatus_InvalidOptArg;
}
i += 2;
}
*argi = i;
return kStatus_Ok;
}
} // namespace cli