Repository navigation
Expand file tree
/
Copy pathcmdline.cppm
More file actions
782 lines (718 loc) · 37.4 KB
/
Copy pathcmdline.cppm
File metadata and controls
782 lines (718 loc) · 37.4 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
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
export module mcpplibs.cmdline;
import std;
export import :completions;
export import :complete;
export import :options;
export import :parse;
namespace mcpplibs::cmdline {
class SubcommandBuilder;
class SubcommandArgBuilder;
class OptBuilder;
class ArgBuilder;
export class App;
/// The command tree as declared, with the options the parse adds itself (`-h/--help`, and
/// `--version` when a version is set): what a completion script, a manual page or a tool's
/// listing of its own commands and options is generated from; its subcommands are in the
/// order the command's help lists them (since 0.0.7, `HelpOptions`).
export [[nodiscard]] completions::Command snapshot(const App& app);
export using Argv = std::vector<std::string>;
/// How `App::completion` offers completions: `entry` is the hidden command a
/// shell's adapter calls with the words to complete; `command`, when not
/// empty, a command that prints the adapter for a shell (`myapp completions
/// bash`), listed with the others: as a command declared before them, among
/// the commands without a group — or under `group`, when one is named.
export struct CompletionOptions {
std::string command = "completions";
std::string entry = "__complete";
std::string group;
};
/// The order a help lists a command's subcommands in (`App::help_options`):
/// as declared, or by name inside a group and among the commands without one.
export enum class HelpOrder { declared, alphabetical };
/// How a command's help lists its subcommands. A subcommand's `group` is the
/// heading it is listed under; the groups come in the order of the first
/// command that names each, the commands without a group after them, under
/// `ungrouped` when it is not empty. The same order is what `snapshot` hands
/// out and what a run names when a subcommand is required, so a tool's help,
/// its completions and its messages agree. None of it touches a parse: the
/// first declared subcommand still wins a name.
export struct HelpOptions {
HelpOrder order = HelpOrder::declared;
std::string ungrouped;
};
export using detail::Arg;
export using detail::Option;
export using detail::OptionValue;
export using detail::ParseError;
export using detail::ParseResult;
export using detail::ParsedArgs;
export class App {
template <typename> friend class AppItemBuilder;
friend class SubcommandBuilder;
friend class OptBuilder;
friend class ArgBuilder;
friend completions::Command snapshot(const App&);
public:
explicit App(std::string_view name) : name_(name) {}
App(App&&) noexcept = default;
App& operator=(App&&) noexcept = default;
App(const App& other) : name_(other.name_), version_(other.version_), description_(other.description_), author_(other.author_),
args_(other.args_), options_(other.options_), subcommands_(other.subcommands_), action_(other.action_),
hidden_(other.hidden_), completion_(other.completion_), group_(other.group_), help_options_(other.help_options_),
epilogue_(other.epilogue_) {}
App& operator=(const App& other) {
if (this == &other) return *this;
name_ = other.name_;
version_ = other.version_;
description_ = other.description_;
author_ = other.author_;
args_ = other.args_;
options_ = other.options_;
subcommands_ = other.subcommands_;
action_ = other.action_;
hidden_ = other.hidden_;
completion_ = other.completion_;
group_ = other.group_;
help_options_ = other.help_options_;
epilogue_ = other.epilogue_;
return *this;
}
/// The command is not listed: not in help, not among completions. It
/// parses and runs as any other (an internal command, a deprecated
/// spelling).
[[nodiscard]] App& hidden(bool hidden = true) {
hidden_ = hidden;
return *this;
}
/// Completion, built in (off unless asked for). A shell's adapter calls the
/// program with `options.entry` and the words before the cursor; the
/// program answers from its command tree, by the rules its parse reads it
/// by, and with the candidates its options and arguments state
/// (`values`, `value_hint`, `complete`). `options.command`, when not
/// empty, prints the adapter for a shell. Both are answered where `--help`
/// is, and the parse returns `ParseError` of kind `completion`.
[[nodiscard]] App& completion(CompletionOptions options = {}) {
completion_ = std::move(options);
return *this;
}
/// The heading the parent's help lists this command under; none, and it
/// follows the groups.
[[nodiscard]] App& group(std::string_view name) {
group_ = name;
return *this;
}
/// How this command's help lists its subcommands.
[[nodiscard]] App& help_options(HelpOptions options) {
help_options_ = std::move(options);
return *this;
}
/// Printed after the subcommands of this command's help: the lines to
/// copy, where to read on. A missing final newline is added.
[[nodiscard]] App& help_epilogue(std::string_view text) {
epilogue_ = text;
return *this;
}
[[nodiscard]] App& version(std::string_view version) {
version_ = version;
return *this;
}
[[nodiscard]] App& author(std::string_view author) {
author_ = author;
return *this;
}
[[nodiscard]] App& description(std::string_view desc) {
description_ = desc;
return *this;
}
[[nodiscard]] App& arg(Arg argument) {
args_.push_back(std::move(argument));
return *this;
}
[[nodiscard]] ArgBuilder arg(std::string_view name);
[[nodiscard]] App& option(Option opt) {
options_.push_back(std::move(opt));
return *this;
}
[[nodiscard]] OptBuilder option(std::string_view name);
[[nodiscard]] App& subcommand(App sub) {
subcommands_.push_back(std::move(sub));
return *this;
}
[[nodiscard]] SubcommandBuilder subcommand(std::string_view name);
/// The command's action: `void(const ParsedArgs&)`, whose status is 0, or
/// `int(const ParsedArgs&)`, whose result is the status `run` returns.
template <typename Fn>
requires std::invocable<Fn&, const ParsedArgs&>
[[nodiscard]] App& action(Fn&& fn) {
using result_t = std::invoke_result_t<Fn&, const ParsedArgs&>;
static_assert(std::is_void_v<result_t> || std::is_convertible_v<result_t, int>,
"an action returns void or a status convertible to int");
if constexpr (std::is_void_v<result_t>)
action_ = [f = std::forward<Fn>(fn)](const ParsedArgs& p) mutable { f(p); return 0; };
else
action_ = [f = std::forward<Fn>(fn)](const ParsedArgs& p) mutable { return static_cast<int>(f(p)); };
return *this;
}
[[nodiscard]] ParseResult parse(int argc, char* argv[]) const {
std::vector<std::string_view> tokens;
tokens.reserve(argc > 1 ? argc - 1 : 0);
for (int i = 1; i < argc; ++i) tokens.emplace_back(argv[i]);
return parse_tokens(tokens);
}
[[nodiscard]] ParseResult parse_from(std::span<const std::string> args) const {
if (args.empty()) return std::unexpected(ParseError{.message = "no program name"});
std::vector<std::string_view> tokens;
tokens.reserve(args.size() - 1);
for (std::size_t i = 1; i < args.size(); ++i) tokens.emplace_back(args[i]);
return parse_tokens(tokens);
}
[[nodiscard]] ParseResult parse_from(std::string_view command_line) const {
std::vector<std::string> tokens = split_command_line(command_line);
if (tokens.empty()) return std::unexpected(ParseError{.message = "empty command line"});
return parse_from(std::span<const std::string>(tokens));
}
/// Runs the action for a parse of this command and returns its status.
///
/// The command the words named is the deepest matched subcommand, at any
/// depth. Its action runs with its own parse; a command without an action
/// leaves the run to its nearest ancestor that has one, which receives the
/// ancestor's parse (and dispatches on `subcommand_name()` itself). When no
/// command on the path has an action, a command with subcommands was named
/// without one: the run writes the subcommands to standard error and
/// returns 2. A command with neither returns 0.
int run(const ParsedArgs& parsed) const {
std::vector<std::pair<const App*, const ParsedArgs*>> path{{this, &parsed}};
while (path.back().second->has_subcommand()) {
const auto [app, args] = path.back();
const App* sub = app->find_subcommand(args->subcommand_name());
auto sub_args = args->subcommand();
if (!sub || !sub_args) break;
path.emplace_back(sub, &sub_args->get());
}
for (auto it = path.rbegin(); it != path.rend(); ++it)
if (it->first->action_) return it->first->action_(*it->second);
const App& named = *path.back().first;
if (named.subcommands_.empty()) return 0;
std::string command(name_);
for (std::size_t i = 1; i < path.size(); ++i) command += " " + path[i].first->name_;
std::string names;
for (const auto& c : listed(named, true)) names += (names.empty() ? "" : ", ") + std::string(c.name);
std::println(std::cerr, "{}: a subcommand is required: {}", command, names);
std::println(std::cerr, "{}: see '{} --help'", name_, command);
return 2;
}
/// Parses `argv` and runs it. Help and the version are printed to standard
/// output and return 0; a parse error is written to standard error and
/// returns 2 (the status of a usage error); otherwise the action's status
/// is returned.
int run(int argc, char* argv[]) const { return finish_run(parse(argc, argv)); }
/// The same for the words of a command line, the program name first.
int run(std::span<const std::string> args) const { return finish_run(parse_from(args)); }
void print_help(std::string_view program_name = "") const {
std::string prog = program_name.empty() ? std::string(name_) : std::string(program_name);
if (!version_.empty()) std::println("{} {}", prog, version_);
if (!description_.empty()) std::println("\n{}\n", description_);
std::println("USAGE:");
std::println(" {} [OPTIONS]", prog);
for (const auto& argument : args_)
std::println(" {} <{}>", prog, argument.name);
if (!options_.empty()) {
std::println("\nOPTIONS:");
for (const auto& opt : options_) {
std::string opt_str;
if (opt.short_) opt_str += std::format("-{}, ", opt.short_);
if (!opt.long_name.empty()) opt_str += "--" + opt.long_name;
if (!opt.value_name_.empty()) opt_str += " <" + opt.value_name_ + ">";
// Manual padding: GCC 15 C++23 modules crash with {:20} width specifiers
while (opt_str.size() < 20) opt_str += ' ';
std::println(" {} {}", opt_str, opt.help_);
}
}
const bool listsCompletion = completion_ && !completion_->command.empty()
&& (program_name.empty() || program_name == name_);
const auto commands = listed(*this, listsCompletion);
if (!commands.empty()) {
std::println("\nSUBCOMMANDS:");
std::string_view heading; // the heading the last line was listed under
for (const auto& c : commands) {
const std::string_view under = c.group.empty() ? std::string_view(help_options_.ungrouped) : c.group;
if (under != heading) {
if (!under.empty()) std::println(" {}:", under);
heading = under;
}
std::string padded(c.name);
while (padded.size() < 12) padded += ' ';
std::println(" {} {}", padded, c.description);
}
}
if (!epilogue_.empty()) std::print("\n{}{}", epilogue_, epilogue_.ends_with('\n') ? "" : "\n");
}
[[nodiscard]] std::string completions(Shell shell) const;
private:
using global_keys_t = std::set<std::string, std::less<>>;
using global_opts_t = std::map<std::string, OptionValue, std::less<>>;
using OptRef = std::optional<std::reference_wrapper<const Option>>;
[[nodiscard]] ParseResult parse_tokens(std::span<const std::string_view> tokens) const {
if (completion_ && !tokens.empty()) {
if (tokens[0] == completion_->entry) {
std::vector<std::string> words(tokens.begin() + 1, tokens.end());
std::print("{}", completions::render(completions::complete(snapshot(*this), words)));
return std::unexpected(ParseError::make_completion());
}
if (!completion_->command.empty() && tokens[0] == completion_->command
&& (tokens.size() < 2 || tokens[1] != "--help")) {
const auto shell = tokens.size() > 1 ? shell_from_string(tokens[1]) : std::nullopt;
if (!shell)
return std::unexpected(ParseError{.message = std::format(
"{} names a shell: bash, zsh, fish, powershell", completion_->command)});
std::print("{}", completions::adapter(*shell, name_, completion_->entry));
return std::unexpected(ParseError::make_completion());
}
}
global_keys_t global_keys;
global_opts_t global_opts;
std::vector<Option> root_globals;
for (const auto& opt : options_)
if (opt.global_) { global_keys.insert(option_key(opt)); root_globals.push_back(opt); }
return parse_impl(name_, tokens, global_keys, global_opts, root_globals);
}
int finish_run(const ParseResult& result) const {
if (!result) {
if (!result.error().is_error()) return 0;
std::println(std::cerr, "{}: {}", name_, result.error().message);
std::println(std::cerr, "{}: see '{} --help'", name_, name_);
return 2;
}
return run(*result);
}
// A line of a subcommand list: a declared command, or the one that prints
// a completion adapter (no App behind it).
struct Listed {
const App* sub = nullptr;
std::string_view name;
std::string_view description;
std::string_view group;
};
// The subcommands a help lists, in its order: a group where the first
// declared command that names it was declared, the commands without one
// after the groups, declared (a stable sort keeps it) or by name inside
// either. The completion command is listed as one declared before the
// others, under its group when it names one, without giving that group
// its place. A hidden command is not listed.
[[nodiscard]] static std::vector<Listed> listed(const App& app, bool with_completion) {
std::vector<Listed> out;
if (with_completion && app.completion_ && !app.completion_->command.empty())
out.push_back({nullptr, app.completion_->command,
"The completion script for a shell: bash, zsh, fish, powershell", app.completion_->group});
for (const auto& sub : app.subcommands_) {
if (sub.hidden_) continue;
out.push_back({&sub, sub.name_, sub.description_, sub.group_});
}
std::vector<std::string_view> groups;
// A group's place is where the first declared command names it.
for (const auto& c : out)
if (c.sub && !c.group.empty() && std::ranges::find(groups, c.group) == groups.end()) groups.push_back(c.group);
for (const auto& c : out)
if (!c.sub && !c.group.empty() && std::ranges::find(groups, c.group) == groups.end()) groups.push_back(c.group);
const auto rank = [&groups](std::string_view g) {
const auto it = std::ranges::find(groups, g);
return it == groups.end() ? groups.size() : static_cast<std::size_t>(it - groups.begin());
};
const bool by_name = app.help_options_.order == HelpOrder::alphabetical;
std::stable_sort(out.begin(), out.end(), [&](const Listed& a, const Listed& b) {
const auto ra = rank(a.group), rb = rank(b.group);
if (ra != rb) return ra < rb;
return by_name ? a.name < b.name : false;
});
return out;
}
const App* find_subcommand(std::string_view name) const {
for (const auto& sub : subcommands_)
if (sub.name_ == name) return ⊂
return nullptr;
}
static std::vector<std::string> split_command_line(std::string_view command_line) {
std::vector<std::string> tokens;
std::string current;
bool in_quote = false;
char quote_char = '\0';
for (char ch : command_line) {
if (in_quote) {
if (ch == quote_char) in_quote = false;
else current += ch;
} else if (ch == '"' || ch == '\'') {
in_quote = true;
quote_char = ch;
} else if (std::isspace(static_cast<unsigned char>(ch))) {
if (!current.empty()) {
tokens.push_back(std::move(current));
current.clear();
}
} else {
current += ch;
}
}
if (!current.empty()) tokens.push_back(std::move(current));
return tokens;
}
[[nodiscard]] ParseResult parse_impl(
std::string_view program_name,
std::span<const std::string_view> tokens,
const global_keys_t& global_keys,
global_opts_t& global_opts,
const std::vector<Option>& root_global_options) const {
ParsedArgs result;
std::vector<std::string> positionals;
bool only_positionals = false;
auto apply_option = [&](const Option& opt, const std::string& key_str, std::string val, bool is_flag) {
if (global_keys.contains(key_str)) {
if (is_flag) global_opts[key_str].count++;
else global_opts[key_str] = OptionValue{1, {std::move(val)}};
} else {
if (is_flag) result.opts[key_str].count++;
else if (opt.multiple_) result.opts[key_str].values.push_back(std::move(val));
else result.opts[key_str] = OptionValue{1, {std::move(val)}};
}
};
auto find_global_option = [&root_global_options](std::string_view long_name, char short_name) -> OptRef {
for (const auto& opt : root_global_options) {
if (short_name && opt.matches_short(short_name)) return std::cref(opt);
if (!long_name.empty() && opt.matches_long(long_name)) return std::cref(opt);
}
return std::nullopt;
};
for (std::size_t i = 0; i < tokens.size(); ++i) {
std::string_view token = tokens[i];
if (only_positionals) {
positionals.emplace_back(token);
continue;
}
if (token == "--") {
only_positionals = true;
continue;
}
if (token == "-h" || token == "--help") {
print_help(program_name);
return std::unexpected(ParseError::make_help());
}
if (token == "--version" && !version_.empty()) {
std::println("{}", version_);
return std::unexpected(ParseError::make_version());
}
if (!subcommands_.empty() && !token.starts_with('-')) {
for (const auto& sub : subcommands_) {
if (sub.name_ == token) {
result.subcommand_name_ = sub.name_;
auto sub_result = sub.parse_impl(std::format("{} {}", program_name, sub.name_), tokens.subspan(i + 1), global_keys, global_opts, root_global_options);
if (!sub_result) return sub_result;
result.subcommand_matches = std::make_unique<ParsedArgs>(std::move(*sub_result));
result.positionals = std::move(positionals);
for (auto& [k, v] : global_opts) result.opts[k] = std::move(v);
return finish_parse(std::move(result));
}
}
}
if (token.starts_with("--") && token.size() > 2) {
std::string_view rest = token.substr(2);
auto eq_pos = rest.find('=');
std::string_view key = eq_pos != std::string_view::npos ? rest.substr(0, eq_pos) : rest;
std::string_view value_part = eq_pos != std::string_view::npos ? rest.substr(eq_pos + 1) : std::string_view{};
auto opt = find_option(key, '\0');
if (!opt) opt = find_global_option(key, '\0');
if (!opt) return std::unexpected(ParseError{.message = std::format("unknown option: --{}", key)});
const Option& found = opt->get();
std::string key_str = option_key(found);
if (found.takes_value_) {
std::string val;
if (eq_pos != std::string_view::npos)
val = std::string(value_part);
else if (i + 1 < tokens.size())
val = std::string(tokens[++i]);
else
return std::unexpected(ParseError{.message = std::format("option --{} requires a value", key)});
if (found.value_check_ && !found.value_check_(val))
return std::unexpected(ParseError{.message = std::format("option --{} takes {}, not `{}`", key, found.value_kind_, val)});
if (!found.admits(val))
return std::unexpected(ParseError{.message = std::format("option --{} takes one of {}, not `{}`", key, found.values_text(), val)});
apply_option(found, key_str, std::move(val), false);
} else {
apply_option(found, key_str, "", true);
}
continue;
}
if (token.size() == 2 && token[0] == '-' && token[1] != '-') {
char short_char = token[1];
auto opt = find_option("", short_char);
if (!opt) opt = find_global_option("", short_char);
if (!opt) return std::unexpected(ParseError{.message = std::format("unknown option: -{}", short_char)});
const Option& found = opt->get();
std::string key_str = option_key(found);
if (found.takes_value_) {
if (i + 1 >= tokens.size()) return std::unexpected(ParseError{.message = std::format("option -{} requires a value", short_char)});
std::string val(tokens[++i]);
if (found.value_check_ && !found.value_check_(val))
return std::unexpected(ParseError{.message = std::format("option -{} takes {}, not `{}`", short_char, found.value_kind_, val)});
if (!found.admits(val))
return std::unexpected(ParseError{.message = std::format("option -{} takes one of {}, not `{}`", short_char, found.values_text(), val)});
apply_option(found, key_str, std::move(val), false);
} else {
apply_option(found, key_str, "", true);
}
continue;
}
positionals.emplace_back(token);
}
result.positionals = std::move(positionals);
for (auto& [k, v] : global_opts) result.opts[k] = std::move(v);
return finish_parse(std::move(result));
}
ParseResult finish_parse(ParsedArgs parsed) const {
for (std::size_t idx = 0; idx < parsed.positionals.size(); ++idx) {
const Arg* argument = idx < args_.size() ? &args_[idx]
: (!args_.empty() && args_.back().repeatable_ ? &args_.back() : nullptr);
if (argument && !argument->admits(parsed.positionals[idx]))
return std::unexpected(ParseError{.message = std::format(
"argument '{}' takes one of {}, not `{}`", argument->name, argument->values_text(), parsed.positionals[idx])});
}
for (std::size_t idx = 0; idx < args_.size(); ++idx) {
const auto& argument = args_[idx];
if (idx < parsed.positionals.size()) continue;
if (argument.required_) return std::unexpected(ParseError{.message = std::format("required argument '{}' missing", argument.name)});
if (!argument.default_val.empty()) parsed.positionals.push_back(argument.default_val);
}
parsed.positional_names_.reserve(args_.size());
for (const auto& argument : args_) parsed.positional_names_.push_back(argument.name);
return parsed;
}
OptRef find_option(std::string_view long_name, char short_name) const {
for (const auto& opt : options_) {
if (short_name && opt.matches_short(short_name)) return std::cref(opt);
if (!long_name.empty() && opt.matches_long(long_name)) return std::cref(opt);
}
return std::nullopt;
}
static std::string option_key(const Option& opt) {
return opt.long_name.empty() ? std::string(1, opt.short_) : opt.long_name;
}
std::string name_;
std::string version_;
std::string description_;
std::string author_;
std::vector<Arg> args_;
std::vector<Option> options_;
std::vector<App> subcommands_;
std::function<int(const ParsedArgs&)> action_;
bool hidden_ = false;
std::optional<CompletionOptions> completion_;
std::string group_;
HelpOptions help_options_;
std::string epilogue_;
};
// CRTP base: shared transition methods and parent/commit management for OptBuilder & ArgBuilder.
template <typename Derived>
class AppItemBuilder {
protected:
App* parent_;
bool committed_ = false;
explicit AppItemBuilder(App* parent) : parent_(parent) {}
AppItemBuilder(AppItemBuilder&& o) noexcept : parent_(o.parent_), committed_(o.committed_) { o.parent_ = nullptr; }
AppItemBuilder(const AppItemBuilder&) = delete;
AppItemBuilder& operator=(const AppItemBuilder&) = delete;
~AppItemBuilder() = default;
void commit() {
if (parent_ && !committed_) {
static_cast<Derived*>(this)->do_commit();
committed_ = true;
}
}
public:
App& option(Option opt) { commit(); parent_->options_.push_back(std::move(opt)); return *parent_; }
OptBuilder option(std::string_view name);
App& arg(Arg argument) { commit(); parent_->args_.push_back(std::move(argument)); return *parent_; }
ArgBuilder arg(std::string_view name);
App& subcommand(App sub) { commit(); parent_->subcommands_.push_back(std::move(sub)); return *parent_; }
SubcommandBuilder subcommand(std::string_view name);
App& version(std::string_view v) { commit(); (void)parent_->version(v); return *parent_; }
App& description(std::string_view d) { commit(); (void)parent_->description(d); return *parent_; }
App& author(std::string_view a) { commit(); (void)parent_->author(a); return *parent_; }
template <typename Fn>
App& action(Fn&& fn) { commit(); (void)parent_->action(std::forward<Fn>(fn)); return *parent_; }
App& end() { auto* p = parent_; commit(); parent_ = nullptr; return *p; }
};
class OptBuilder : public AppItemBuilder<OptBuilder> {
friend class AppItemBuilder<OptBuilder>;
public:
OptBuilder(App* parent, Option opt) : AppItemBuilder(parent), option_(std::move(opt)) {}
OptBuilder(OptBuilder&& o) noexcept : AppItemBuilder(std::move(o)), option_(std::move(o.option_)) {}
OptBuilder& operator=(OptBuilder&& o) noexcept {
if (this != &o) { commit(); parent_ = o.parent_; committed_ = o.committed_; o.parent_ = nullptr; option_ = std::move(o.option_); }
return *this;
}
~OptBuilder() { commit(); }
OptBuilder& long_opt(std::string_view v) { (void)option_.long_opt(v); return *this; }
OptBuilder& short_name(char c) { (void)option_.short_name(c); return *this; }
OptBuilder& help(std::string_view h) { (void)option_.help(h); return *this; }
OptBuilder& takes_value(bool v = true) { (void)option_.takes_value(v); return *this; }
template <class Number>
OptBuilder& value_type() { (void)option_.template value_type<Number>(); return *this; }
OptBuilder& value_name(std::string_view v) { (void)option_.value_name(v); return *this; }
OptBuilder& multiple(bool m = true) { (void)option_.multiple(m); return *this; }
OptBuilder& global(bool g = true) { (void)option_.global(g); return *this; }
OptBuilder& values(std::vector<std::string> v) { (void)option_.values(std::move(v)); return *this; }
OptBuilder& value_hint(ValueHint h) { (void)option_.value_hint(h); return *this; }
OptBuilder& complete(Candidates c) { (void)option_.complete(std::move(c)); return *this; }
private:
void do_commit() { parent_->options_.push_back(std::move(option_)); }
Option option_;
};
class ArgBuilder : public AppItemBuilder<ArgBuilder> {
friend class AppItemBuilder<ArgBuilder>;
public:
ArgBuilder(App* parent, Arg a) : AppItemBuilder(parent), arg_(std::move(a)) {}
ArgBuilder(ArgBuilder&& o) noexcept : AppItemBuilder(std::move(o)), arg_(std::move(o.arg_)) {}
ArgBuilder& operator=(ArgBuilder&& o) noexcept {
if (this != &o) { commit(); parent_ = o.parent_; committed_ = o.committed_; o.parent_ = nullptr; arg_ = std::move(o.arg_); }
return *this;
}
~ArgBuilder() { commit(); }
ArgBuilder& help(std::string_view h) { (void)arg_.help(h); return *this; }
ArgBuilder& required(bool r = true) { (void)arg_.required(r); return *this; }
ArgBuilder& default_value(std::string_view v) { (void)arg_.default_value(v); return *this; }
ArgBuilder& repeatable(bool r = true) { (void)arg_.repeatable(r); return *this; }
ArgBuilder& values(std::vector<std::string> v) { (void)arg_.values(std::move(v)); return *this; }
ArgBuilder& value_hint(ValueHint h) { (void)arg_.value_hint(h); return *this; }
ArgBuilder& complete(Candidates c) { (void)arg_.complete(std::move(c)); return *this; }
private:
void do_commit() { parent_->args_.push_back(std::move(arg_)); }
Arg arg_;
};
class SubcommandBuilder {
friend class SubcommandArgBuilder;
public:
SubcommandBuilder(App* parent, App sub) : parent_(parent), sub_(std::move(sub)) {}
SubcommandBuilder(SubcommandBuilder&& o) noexcept
: parent_(o.parent_), sub_(std::move(o.sub_)), committed_(o.committed_) { o.parent_ = nullptr; }
SubcommandBuilder& operator=(SubcommandBuilder&& o) noexcept {
if (this != &o) { commit(); parent_ = o.parent_; sub_ = std::move(o.sub_); committed_ = o.committed_; o.parent_ = nullptr; }
return *this;
}
SubcommandBuilder(const SubcommandBuilder&) = delete;
SubcommandBuilder& operator=(const SubcommandBuilder&) = delete;
~SubcommandBuilder() { commit(); }
SubcommandBuilder& version(std::string_view v) { (void)sub_.version(v); return *this; }
SubcommandBuilder& author(std::string_view a) { (void)sub_.author(a); return *this; }
SubcommandBuilder& description(std::string_view d) { (void)sub_.description(d); return *this; }
SubcommandBuilder& hidden(bool h = true) { (void)sub_.hidden(h); return *this; }
SubcommandBuilder& group(std::string_view g) { (void)sub_.group(g); return *this; }
SubcommandBuilder& arg(Arg argument) { (void)sub_.arg(std::move(argument)); return *this; }
SubcommandArgBuilder arg(std::string_view name);
SubcommandBuilder& option(Option opt) { (void)sub_.option(std::move(opt)); return *this; }
OptBuilder option(std::string_view name);
template <typename Fn>
App& action(Fn&& fn) {
(void)sub_.action(std::forward<Fn>(fn));
auto* p = parent_; commit(); return *p;
}
SubcommandBuilder& subcommand(std::string_view name) {
commit(); sub_ = App(name); committed_ = false; return *this;
}
App& end() { auto* p = parent_; commit(); parent_ = nullptr; return *p; }
private:
void commit() {
if (parent_ && !committed_) { parent_->subcommands_.push_back(std::move(sub_)); committed_ = true; }
}
App* parent_;
App sub_;
bool committed_ = false;
};
class SubcommandArgBuilder {
public:
SubcommandArgBuilder(SubcommandArgBuilder&& o) noexcept
: sb_(o.sb_), arg_(std::move(o.arg_)), committed_(o.committed_) { o.sb_ = nullptr; }
SubcommandArgBuilder& operator=(SubcommandArgBuilder&&) = delete;
SubcommandArgBuilder(const SubcommandArgBuilder&) = delete;
SubcommandArgBuilder& operator=(const SubcommandArgBuilder&) = delete;
~SubcommandArgBuilder() { commit(); }
SubcommandArgBuilder& required(bool r = true) { (void)arg_.required(r); return *this; }
SubcommandArgBuilder& help(std::string_view h) { (void)arg_.help(h); return *this; }
SubcommandArgBuilder& default_value(std::string_view v) { (void)arg_.default_value(v); return *this; }
SubcommandArgBuilder& repeatable(bool r = true) { (void)arg_.repeatable(r); return *this; }
SubcommandArgBuilder& values(std::vector<std::string> v) { (void)arg_.values(std::move(v)); return *this; }
SubcommandArgBuilder& value_hint(ValueHint h) { (void)arg_.value_hint(h); return *this; }
SubcommandArgBuilder& complete(Candidates c) { (void)arg_.complete(std::move(c)); return *this; }
SubcommandArgBuilder arg(std::string_view name) { commit(); return sb_->arg(name); }
template <typename Fn>
App& action(Fn&& fn) { commit(); return sb_->action(std::forward<Fn>(fn)); }
private:
SubcommandArgBuilder(SubcommandBuilder* sb, Arg a) : sb_(sb), arg_(std::move(a)) {}
void commit() {
if (sb_ && !committed_) { (void)sb_->sub_.arg(std::move(arg_)); committed_ = true; }
}
SubcommandBuilder* sb_ = nullptr;
Arg arg_;
bool committed_ = false;
friend class SubcommandBuilder;
};
inline SubcommandBuilder App::subcommand(std::string_view name) { return SubcommandBuilder(this, App(name)); }
inline OptBuilder App::option(std::string_view name) { return OptBuilder(this, Option(name)); }
inline ArgBuilder App::arg(std::string_view name) { return ArgBuilder(this, Arg(name)); }
template <typename D>
OptBuilder AppItemBuilder<D>::option(std::string_view name) { this->commit(); return parent_->option(name); }
template <typename D>
ArgBuilder AppItemBuilder<D>::arg(std::string_view name) { this->commit(); return parent_->arg(name); }
template <typename D>
SubcommandBuilder AppItemBuilder<D>::subcommand(std::string_view name) { this->commit(); return parent_->subcommand(name); }
inline OptBuilder SubcommandBuilder::option(std::string_view name) { return OptBuilder(&sub_, Option(name)); }
inline SubcommandArgBuilder SubcommandBuilder::arg(std::string_view name) { return SubcommandArgBuilder(this, Arg(name)); }
completions::Command snapshot(const App& app) {
completions::Command cmd;
cmd.name = app.name_;
cmd.description = app.description_;
cmd.version = app.version_;
cmd.args = app.args_;
cmd.options = app.options_;
// Special cases in `App::parse_impl`:
//
// `-h/--help` is every command's own (each node of the snapshot has it).
cmd.options.emplace_back(detail::Option("help").short_name('h').help("Print help"));
// `--version` is the command's that has a version: the parse answers it
// there and nowhere below.
if (!cmd.version.empty()) cmd.options.emplace_back(detail::Option("version").help("Print version"));
// In the order the help lists them (`listed`): the command that prints an
// adapter, as `completion` added it, among them.
for (const auto& c : App::listed(app, true)) {
if (c.sub) {
cmd.subcommands.emplace_back(snapshot(*c.sub));
continue;
}
completions::Command printer;
printer.name = app.completion_->command;
printer.description = "The completion script for a shell";
printer.args.push_back(detail::Arg("shell").values({"bash", "zsh", "fish", "powershell"}));
cmd.subcommands.push_back(std::move(printer));
}
return cmd;
}
// THE ADAPTER FOR A SHELL (unchanged signatures since 0.0.4). The script a
// shell reads is the few lines that ask the program (`completions::adapter`),
// not the program's command tree written out: the tree is the program's, and
// it answers for it (`App::completion`). The adapter calls the default entry,
// `__complete`, for a tree given as a `Command`.
export void generate_completions(const completions::Command& cmd, Shell shell, std::ostream& out) {
out << completions::adapter(shell, cmd.name, CompletionOptions{}.entry);
}
export std::string generate_completions(const completions::Command& cmd, Shell shell) {
std::ostringstream oss;
generate_completions(cmd, shell, oss);
return oss.str();
}
export void generate_completions(const App& app, Shell shell, std::ostream& out) {
out << app.completions(shell);
}
export std::string generate_completions(const App& app, Shell shell) {
return app.completions(shell);
}
std::string App::completions(Shell shell) const {
return completions::adapter(shell, name_, completion_ ? completion_->entry : CompletionOptions{}.entry);
}
} // namespace mcpplibs::cmdline