-
Notifications
You must be signed in to change notification settings - Fork 2
/
quickstart.cpp
279 lines (239 loc) · 10.4 KB
/
quickstart.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
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
#include <c4/conf/conf.hpp>
#include <vector>
#include <string>
#include <iostream>
C4_SUPPRESS_WARNING_GCC_CLANG_PUSH
C4_SUPPRESS_WARNING_GCC("-Wuseless-cast")
C4_SUPPRESS_WARNING_GCC_CLANG("-Wold-style-cast")
C4_SUPPRESS_WARNING_MSVC_WITH_PUSH(4702) // unreachable code
using namespace c4::conf;
// these are the settings used to fill the default config tree
const char default_settings[] = R"(
foo:
- foo0
- foo1
- foo2
- foo3
bar:
bar0: indeed0
bar1: indeed1
bar2: indeed2
baz: definitely
)";
// some custom actions for command line switches
void show_help(const char *exename);
void setfoo(Tree &tree, csubstr);
void setbar(Tree &tree, csubstr);
void setfoo3(Tree &tree, csubstr foo3val);
void setbar2(Tree &tree, csubstr bar2val);
// create the specs for the command line options to be handled by
// c4conf. These options will transform the config tree:
const ConfigActionSpec conf_specs[] = {
// using an explicit csubstr() is required by GCC5, but not with
// later versions, which will pick the proper csubstr constructor.
spec_for<ConfigAction::set_node> (csubstr("-cn" ), csubstr("--conf-node" )),
spec_for<ConfigAction::load_file>(csubstr("-cf" ), csubstr("--conf-file" )),
spec_for<ConfigAction::load_dir> (csubstr("-cd" ), csubstr("--conf-dir" )),
spec_for(&setfoo , csubstr("-sf" ), csubstr("--set-foo" ), csubstr({} ), csubstr("call setfoo()")),
spec_for(&setbar , csubstr("-sb" ), csubstr("--set-bar" ), csubstr({} ), csubstr("call setbar()")),
spec_for(&setfoo3, csubstr("-sf3"), csubstr("--set-foo3-val"), csubstr("<foo3val>" ), csubstr("call setfoo3() with a required arg)")),
spec_for(&setbar2, csubstr("-sb2"), csubstr("--set-bar2-val"), csubstr("[<bar2val>]"), csubstr("call setbar2() with an optional arg)")),
};
// Load settings, and override them with any command-line arguments.
// The arguments registered above are filtered out of the input, and
// any other arguments will remain.
c4::yml::Tree makeconf(int *argc, char ***argv)
{
// This is our config tree; fill it with the defaults.
c4::yml::Tree tree = c4::yml::parse_in_arena("(defaults)", default_settings);
// Parse the input args, filtering out the config options
// registered above, and gathering them into the returned
// container. Any options not listed in conf_specs are ignored and
// will remain in (argc, argv). Note that this overload creating a
// vector of ParsedOpt is chosen for brevity; you can use a
// lower-level overload writing into a memory span.
auto configs = parse_opts<std::vector<ParsedOpt>>(argc, argv, conf_specs, C4_COUNTOF(conf_specs));
// After successfully parsing, you should also do validation, but
// we skip that step in this sample.
//
// Now apply the config options onto the defaults tree. All
// options are handled in the order given by the user.
c4::conf::Workspace workspace(&tree);
workspace.apply_opts(configs);
return tree;
}
int main(int argc, char **argv)
{
// This is our resulting config tree:
c4::yml::Tree tree = makeconf(&argc, &argv);
// At this point, any c4conf arguments are filtered out of argc
// and argv. If there are further arguments to be parsed by the
// application, this is the occasion to do it. In this example, we
// only have --help, and raise an error on any other argument. To
// be clear, --help could be handled by parse_opts(), but we
// choose to deal with it here instead to show that c4conf does
// not take over the options of your program.
for(auto *arg = argv + 1; arg < argv + argc; ++arg)
{
csubstr s{*arg, strlen(*arg)};
if(s == "-h" || s == "--help")
{
show_help(argv[0]);
return 0;
}
else
{
std::cout << "unknown argument: " << *arg << "\n";
return (int)(arg - argv);
}
}
// Now you can deserialize the config tree
// into your program's native data structures.
// Since this is an example, we stop here and just
// dump the tree to the output:
std::cout << tree;
return 0;
}
//-----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// Because of the nature of this example, a prior config option given
// by the user may have changed foo/bar to a different type
// incompatible with the actions below. So these ensure that it has
// the proper structure:
void ensure_foo(Tree &tree)
{
if(!tree["foo"].is_seq() || tree["foo"].num_children() < 4)
C4_ERROR("cannot setfoo()");
}
void ensure_bar(Tree &tree)
{
if(!tree["bar"].is_map() || tree["bar"].num_children() < 3)
C4_ERROR("cannot setbar()");
}
void setfoo(Tree &tree, csubstr)
{
ensure_foo(tree);
tree["foo"][2] = "foo2, actually footoo";
tree["foo"][3].change_type(c4::yml::SEQ);
tree["foo"][3][0] = "foo3elm0";
tree["foo"][3][1] = "foo3elm1";
tree["foo"][3][2] = "foo3elm2";
}
void setbar(Tree &tree, csubstr)
{
ensure_bar(tree);
tree["bar"]["add more"] = "one";
tree["bar"]["add more again"] = "two";
tree["baz"] = "definitely maybe";
}
void setfoo3(Tree &tree, csubstr foo3val)
{
ensure_foo(tree);
tree["foo"][3] = foo3val;
}
void setbar2(Tree &tree, csubstr bar2val)
{
ensure_bar(tree);
tree["bar"]["bar2"] = bar2val;
}
void show_help(const char *exename)
{
// c4conf enables you to show formatted help for the c4conf options
auto dump = [](csubstr s){ std::cout << s; };
print_help(dump, conf_specs, C4_COUNTOF(conf_specs), "conf options");
// Now we show several usage examples together
// with the resulting output:
constexpr const char fg_white[] = "\033[97m";
constexpr const char fg_dark_gray[] = "\033[90m";
constexpr const char fg_reset[] = "\033[0m";
constexpr const char st_bold[] = "\033[1m";
constexpr const char st_bold_reset[] = "\033[21m";
constexpr const char bg_reset[] = "\033[49m";
constexpr const char bg_black[] = "\033[40m";
std::vector<char*> argvbuf;
csubstr basename = csubstr{exename, strlen(exename)}.basename();
auto show_example = [&](const char *desc, std::vector<std::string> args) -> std::ostream& {
// create argc/argv
argvbuf.resize(args.size());
for(size_t i = 0; i < args.size(); ++i) argvbuf[i] = &args[i][0];
int argc = (int) args.size();
char **argv = argvbuf.data();
// print the description
std::cout << bg_black << fg_dark_gray << desc << fg_reset << bg_reset << ":\n";
// print the command
std::cout << bg_black << st_bold << fg_white << "$ " << basename << ' ';
for(auto &a : args) std::cout << a << ' ';
std::cout << fg_reset << st_bold_reset << bg_reset << '\n';
// print the result
std::cout << makeconf(&argc, &argv);
return std::cout;
};
std::cout << "\n";
std::cout << R"(
--------
EXAMPLES
--------
Given these default settings:
)" << default_settings << R"(
... you can do any of the following:
)"; show_example("# run with defaults, do not change anything",
{}) << R"(
)"; show_example("# change seq node values",
{"-cn", "foo[1]=1.234e9"}) << R"(
)"; show_example("# change map node values",
{"-cn", "bar.bar2=newvalue"}) << R"(
)"; show_example("# change values repeatedly. Later values prevail",
{"-cn", "foo[1]=1.234e9", "-cn", "foo[1]=2.468e9"}) << R"(
)"; show_example("# append elements to a seq",
{"-cn", "foo=[these,will,be,appended]"}) << R"(
)"; show_example("# append elements to a map",
{"-cn", "bar='{these: will, be: appended}'"}) << R"(
)"; show_example("# remove all elements in a seq, replace with different elements",
{"-cn", "'foo=~'", "-cn", "foo=[all,new]"}) << R"(
)"; show_example("# remove all elements in a map, replace with different elements",
{"-cn", "'bar=~'", "-cn", "bar='{all: new}'"}) << R"(
)"; show_example("# replace a seq with a different type, eg val",
{"-cn", "foo=newfoo"}) << R"(
)"; show_example("# replace a map with a different type, eg val",
{"-cn", "bar=newbar"}) << R"(
)"; show_example("# add new nodes, eg seq",
{"-cn", "coffee=[morning,lunch,afternoon]"}) << R"(
)"; show_example("# add new nodes, eg map",
{"-cn", "wine='{green: summer, red: winter, champagne: year-round}'"}) << R"(
)"; show_example("# add new nested nodes to a seq",
{"-cn", "foo[3]=[a,b,c]"}) << R"(
)"; show_example("# add new nested nodes to a map",
{"-cn", "bar.possibly=[d,e,f]"}) << R"(
)"; show_example("# In seqs, target node indices do not need to be contiguous.\n"
"# This will add a new seq nested in foo, and\n"
"# foo[4] will also be created with a null",
{"-cn", "foo[5]=[d,e,f]"}) << R"(
)"; show_example("# NOTE:\n"
"# All of -cn/-cf/-cd have an implied target node, which\n"
"# defaults to the tree's root node. So take care if\n"
"# omitting the target node; that will replace the whole\n"
"# root node with the given value",
{"-cn", "eraseall"}) << R"(
)"; show_example("# call setfoo()",
{"-sf"}) << R"(
)"; show_example("# call setfoo3(). The following arg is mandatory",
{"-sf3", "123"}) << R"(
)"; show_example("# this is equivalent to the previous example",
{"-cn", "foo[3]=123"}) << R"(
)"; show_example("# call setbar2()",
{"-sb2", "'the value'"}) << R"(
)"; show_example("# this is equivalent to the previous example",
{"-cn", "'bar.bar2=the value'"}) << R"(
)"; show_example("# call setbar2(), with omitted arg",
{"-sb2"}) << R"(
)"; show_example("# this is equivalent to the previous example",
{"-cn", "'bar.bar2=~'"}) << R"(
# Notice above that the tilde `~` (which in YAML is understood as the null
# value) is escaped with quotes when it is part of an argument. This is
# needed to prevent the shell from replacing `~` with the user's home
# dir before the executable is called.
)";
}
C4_SUPPRESS_WARNING_GCC_CLANG_POP
C4_SUPPRESS_WARNING_MSVC_POP