-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcommandline.cpp
More file actions
2021 lines (1820 loc) · 84.4 KB
/
Copy pathcommandline.cpp
File metadata and controls
2021 lines (1820 loc) · 84.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
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: MIT
#include "commandline.h"
#include "commandline_p.h"
#include <cerrno>
#include <cstdio>
#include <charconv>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <fstream>
#include <unordered_map>
#include "console.h"
#include "path.h"
#include "utf.h"
#include "pimpl.h"
namespace stdc::cli {
namespace detail {
namespace {
/// Whether \a token is entirely made of what \c from_chars consumed. A number that
/// stops short of the end of the token, \c 12abc, is not a number.
bool consumed_all(std::string_view token, const char *end) {
return end == token.data() + token.size();
}
/// \c from_chars refuses a leading plus, which a command line will hand over anyway.
std::string_view drop_leading_plus(std::string_view token) {
if (token.size() > 1 && token.front() == '+') {
token.remove_prefix(1);
}
return token;
}
template <class T>
bool parse_floating_with(std::string_view token, T *out,
T (*convert)(const char *, char **)) {
if (token.empty()) {
return false;
}
std::string buf(token);
errno = 0;
char *end = nullptr;
T value = convert(buf.c_str(), &end);
if (end != buf.c_str() + buf.size() || end == buf.c_str() || errno == ERANGE) {
return false;
}
*out = value;
return true;
}
}
bool parse_signed(std::string_view token, int64_t *out, int64_t min, int64_t max) {
token = drop_leading_plus(token);
if (token.empty()) {
return false;
}
int64_t v = 0;
auto res = std::from_chars(token.data(), token.data() + token.size(), v);
if (res.ec != std::errc{} || !consumed_all(token, res.ptr)) {
return false;
}
if (v < min || v > max) {
return false;
}
*out = v;
return true;
}
bool parse_unsigned(std::string_view token, uint64_t *out, uint64_t max) {
token = drop_leading_plus(token);
if (token.empty()) {
return false;
}
// No sign to refuse by hand: from_chars into an unsigned rejects a minus outright.
// Checked on all three of MSVC, libstdc++ and libc++, each answering invalid_argument
// and leaving the output alone. The test says so too, since it is their promise this
// relies on rather than ours.
uint64_t v = 0;
auto res = std::from_chars(token.data(), token.data() + token.size(), v);
if (res.ec != std::errc{} || !consumed_all(token, res.ptr)) {
return false;
}
if (v > max) {
return false;
}
*out = v;
return true;
}
bool parse_floating(std::string_view token, float *out) {
return parse_floating_with(token, out, std::strtof);
}
bool parse_floating(std::string_view token, double *out) {
return parse_floating_with(token, out, std::strtod);
}
bool parse_floating(std::string_view token, long double *out) {
return parse_floating_with(token, out, std::strtold);
}
bool parse_boolean(std::string_view token, bool *out) {
static const std::string_view yes[] = {"true", "yes", "on", "1"};
static const std::string_view no[] = {"false", "no", "off", "0"};
for (auto word : yes) {
if (str::ascii_casecmp(token, word) == 0) {
*out = true;
return true;
}
}
for (auto word : no) {
if (str::ascii_casecmp(token, word) == 0) {
*out = false;
return true;
}
}
return false;
}
}
// ---------------------------------------------------------------------------------------
// Storage
// ---------------------------------------------------------------------------------------
namespace {
/// The tokens one declared argument took. More than one only where the argument said it
/// accepts more than one.
using ArgumentValues = std::vector<std::string>;
/// One appearance of an option, holding a slot per argument it declares.
/// Named for what it holds rather than for what it is one of, OptionResult::Occurrence
/// being the public thing that reads it.
using ArgumentSlots = std::vector<ArgumentValues>;
struct OptionData {
const Option *option = nullptr;
std::vector<ArgumentSlots> occurrences;
};
/// Which option a token names, and what the token itself said.
struct OptionMatch {
OptionData *data = nullptr;
/// What was written against the spelling, by an equals sign or by being stuck to
/// it. Absent where the token was the spelling and nothing else, which is not the
/// same as present and empty: \c --prefix= sets an empty string.
std::string_view value;
/// The spelling as it was written, so that a complaint about the option names it
/// the way the reader typed it rather than the way it was declared.
std::string_view spelling;
explicit operator bool() const {
return data != nullptr;
}
};
/// How many of \a available tokens the \a index'th of \a declared may take, given
/// whether it \a has_one already.
///
/// One each for the required arguments still to come, since a greedy one that took the
/// lot would leave \c copy \c \<src\>... \c \<dest\> with nothing for the destination.
/// The rule is the same whether the arguments belong to a command or to an option, so it
/// is written once and both ask.
///
/// Where there are not enough to go round, a greedy argument still takes one, since one
/// or more is what it promised and the argument that goes without says so itself. That
/// is the one thing \a has_one changes: a value written against the option has already
/// kept the promise, so there is nothing left to force and the reservation stands.
size_t take_for(const std::vector<Argument> &declared, size_t index, size_t available,
bool has_one = false) {
const auto &argument = declared[index];
if (argument.arity() == Argument::Single) {
return 1;
}
if (argument.arity() == Argument::Remainder) {
return available;
}
size_t reserved = 0;
for (size_t j = index + 1; j < declared.size(); ++j) {
if (declared[j].isRequired()) {
++reserved;
}
}
if (available > reserved) {
return available - reserved;
}
return has_one ? 0 : 1;
}
bool same_token(std::string_view a, std::string_view b, bool ignore_case) {
if (!ignore_case) {
return a == b;
}
return str::ascii_casecmp(a, b) == 0;
}
}
class detail::parse_data {
public:
/// Shared with the parser rather than copied, so that the pointers below stay good and
/// the tree is walked once.
std::shared_ptr<const Command> root;
const Command *target = nullptr;
std::vector<std::string> path;
/// Per positional argument of the command that was reached.
std::vector<ArgumentValues> arguments;
/// Every option in scope, its own and whatever was inherited.
std::vector<OptionData> options;
std::unordered_map<std::string, size_t> by_token;
/// Copied from the parser, so that a result can print its own help without being handed
/// the parser that made it.
std::string prologue;
std::string epilogue;
HelpLayout help_layout = HelpLayout::defaultLayout();
/// Shared with the parser rather than copied, since the parser goes on using it for the
/// next parse while this may outlive it. The same reason root is shared, and the reason
/// it is not a unique_ptr: there is no one owner to give it to.
std::shared_ptr<HelpFormatter> formatter;
Parser::DisplayOptions display_options;
int text_width = 0;
int indent = 4;
int spacing = 4;
ParseResult::Error error = ParseResult::NoError;
std::string error_text;
/// What was typed where a declared name belongs, and the names it might have meant.
/// Kept rather than measured here, so a program that never prints a correction does not
/// pay for one.
std::string error_token;
std::vector<std::string> error_candidates;
const OptionData *find(std::string_view token) const {
auto it = by_token.find(std::string(token));
return it == by_token.end() ? nullptr : &options[it->second];
}
/// The same, for the parser, which fills these in. Writing it out beats a const_cast
/// admitting the const above was never true of this data.
OptionData *findForWriting(std::string_view token) {
auto it = by_token.find(std::string(token));
return it == by_token.end() ? nullptr : &options[it->second];
}
};
// ---------------------------------------------------------------------------------------
// OptionResult
// ---------------------------------------------------------------------------------------
// Everything here reaches through _data without checking it. ParseResult::option() is the
// only thing that makes one of these, and it makes one only where there is data to point at.
int OptionResult::count() const {
return int(static_cast<const OptionData *>(_data)->occurrences.size());
}
const Option *OptionResult::option() const {
return static_cast<const OptionData *>(_data)->option;
}
OptionResult::Occurrence OptionResult::at(int n) const {
assert(n >= 0 && n < count() && "there was no such occurrence of this option");
return {_data, n};
}
namespace {
/// The slots of one occurrence. Which occurrence is at()'s precondition, so there is
/// nothing left to check here and nothing to answer with where there is no such one.
const ArgumentSlots &slots_of(const void *data, int n) {
const auto &occurrences = static_cast<const OptionData *>(data)->occurrences;
assert(n >= 0 && size_t(n) < occurrences.size());
return occurrences[size_t(n)];
}
}
// The slot is a vector of the tokens that argument took. Whether that vector is empty and
// whether the token in it is empty are different questions, which is why nothing here is
// reported as empty text.
std::optional<std::string_view> OptionResult::Occurrence::rawValue(int index) const {
const auto &slots = slots_of(_data, _n);
if (index < 0 || size_t(index) >= slots.size() || slots[size_t(index)].empty()) {
return std::nullopt;
}
return std::string_view(slots[size_t(index)].front());
}
std::vector<std::string_view> OptionResult::Occurrence::rawValues(int index) const {
std::vector<std::string_view> res;
const auto &slots = slots_of(_data, _n);
if (index < 0 || size_t(index) >= slots.size()) {
return res;
}
for (const auto &item : slots[size_t(index)]) {
res.emplace_back(item);
}
return res;
}
std::vector<std::string_view> OptionResult::allRawValues(int index) const {
std::vector<std::string_view> res;
if (index < 0) {
return res;
}
auto data = static_cast<const OptionData *>(_data);
for (const auto &slots : data->occurrences) {
if (size_t(index) >= slots.size()) {
continue;
}
for (const auto &item : slots[size_t(index)]) {
res.emplace_back(item);
}
}
return res;
}
// ---------------------------------------------------------------------------------------
// ParseResult
// ---------------------------------------------------------------------------------------
ParseResult::ParseResult() : _impl(std::make_unique<detail::parse_data>()) {
}
ParseResult::ParseResult(ParseResult &&other) noexcept = default;
ParseResult &ParseResult::operator=(ParseResult &&other) noexcept = default;
ParseResult::~ParseResult() = default;
ParseResult::Error ParseResult::error() const {
stdc_impl_t;
return impl.error;
}
const std::string &ParseResult::errorText() const {
stdc_impl_t;
return impl.error_text;
}
namespace {
/// How many single character insertions, deletions and substitutions it takes to turn
/// one into the other. Two rows rather than the whole table, since only the previous one
/// is ever read.
size_t edit_distance(const std::string &a, const std::string &b) {
std::vector<size_t> row(b.size() + 1);
for (size_t j = 0; j <= b.size(); ++j) {
row[j] = j;
}
for (size_t i = 1; i <= a.size(); ++i) {
size_t diagonal = row[0];
row[0] = i;
for (size_t j = 1; j <= b.size(); ++j) {
size_t above = row[j];
row[j] = std::min(
{row[j] + 1, row[j - 1] + 1, diagonal + (a[i - 1] == b[j - 1] ? 0 : 1)});
diagonal = above;
}
}
return row[b.size()];
}
}
std::string ParseResult::correctionText() const {
stdc_impl_t;
const auto &input = impl.error_token;
if (input.empty() || impl.error_candidates.empty()) {
return {};
}
// Half of what was typed. Looser than that and every short name is a candidate for every
// short typo, which is worse than saying nothing.
const size_t threshold = input.size() / 2;
// Set in as far as the help text sets a section body in, since this is a list under a
// line that introduces it and reads as one.
const std::string margin(size_t(impl.indent < 0 ? 0 : impl.indent), ' ');
std::string suggestions;
for (const auto &item : impl.error_candidates) {
if (edit_distance(input, item) <= threshold) {
suggestions += "\n" + margin + item;
}
}
if (suggestions.empty()) {
return {};
}
return "\"" + input + "\" is not matched. Do you mean one of the following?" + suggestions;
}
const Command *ParseResult::command() const {
stdc_impl_t;
return impl.target;
}
const std::vector<std::string> &ParseResult::commandPath() const {
stdc_impl_t;
return impl.path;
}
// The innermost command on the path that was given one, so a subcommand may say a version of
// its own and everything under a root that says one inherits it.
std::string ParseResult::versionText() const {
stdc_impl_t;
std::string res;
const Command *at = impl.root.get();
for (size_t i = 0; at; ++i) {
if (!at->version().empty()) {
res = at->version();
}
at = i + 1 < impl.path.size() ? at->findCommand(impl.path[i + 1]) : nullptr;
}
return res;
}
bool ParseResult::isRoleSet(Option::Role role) const {
if (role == Option::NoRole) {
return false;
}
stdc_impl_t;
for (const auto &item : impl.options) {
if (item.option->role() == role && !item.occurrences.empty()) {
return true;
}
}
return false;
}
// Nothing rather than an empty result, so that there is one way to ask whether an option
// was given and one kind of OptionResult to hold.
std::optional<OptionResult> ParseResult::option(std::string_view token) const {
stdc_impl_t;
auto data = impl.find(token);
if (!data || data->occurrences.empty()) {
return std::nullopt;
}
return OptionResult(data);
}
std::optional<std::string_view> ParseResult::rawValue(int index) const {
stdc_impl_t;
if (index < 0 || size_t(index) >= impl.arguments.size() ||
impl.arguments[size_t(index)].empty()) {
return std::nullopt;
}
return std::string_view(impl.arguments[size_t(index)].front());
}
std::vector<std::string_view> ParseResult::rawValues(int index) const {
stdc_impl_t;
std::vector<std::string_view> res;
if (index < 0 || size_t(index) >= impl.arguments.size()) {
return res;
}
for (const auto &item : impl.arguments[size_t(index)]) {
res.emplace_back(item);
}
return res;
}
const std::string &ParseResult::prologue() const {
stdc_impl_t;
return impl.prologue;
}
const std::string &ParseResult::epilogue() const {
stdc_impl_t;
return impl.epilogue;
}
const HelpLayout &ParseResult::helpLayout() const {
stdc_impl_t;
return impl.help_layout;
}
// Gathered by walking down the path the way the parser did. What it gathered on the way is
// what it demands at the end, so this is where the help text has to agree with it.
std::vector<const Option *> ParseResult::inheritedOptions() const {
stdc_impl_t;
std::vector<const Option *> res;
if (!impl.root || impl.path.size() <= 1) {
return res;
}
const Command *at = impl.root.get();
for (size_t i = 1; i < impl.path.size() && at; ++i) {
for (const auto &option : at->options()) {
if (option.isRecursive()) {
res.push_back(&option);
}
}
at = at->findCommand(impl.path[i]);
}
return res;
}
namespace {
HelpSizes sizesOf(const detail::parse_data *data) {
HelpSizes res;
res.indent = data->indent;
res.spacing = data->spacing;
// Zero means ask, and the answer is whatever stdout is: a terminal's width, or 80
// columns for a pipe or a file, so help captured into one reads the same everywhere.
res.textWidth = data->text_width > 0 ? data->text_width : console::width(stdout);
res.displayOptions = data->display_options;
return res;
}
/// The whole help text, laid out but not yet joined. The sizes are worked out once and
/// used for both halves, so a terminal resized between them cannot lay the usage line
/// out to one width and the descriptions to another.
std::vector<HelpFormatter::Run> helpRuns(const ParseResult &result,
const detail::parse_data *data) {
if (!data->target || !data->formatter) {
return {};
}
HelpSizes sizes = sizesOf(data);
return data->formatter->render(data->formatter->blocks(result, sizes), sizes);
}
}
std::vector<HelpBlock> ParseResult::helpBlocks() const {
stdc_impl_t;
if (!impl.target || !impl.formatter) {
return {};
}
return impl.formatter->blocks(*this, sizesOf(&impl));
}
std::string ParseResult::helpText() const {
stdc_impl_t;
std::string out;
for (const auto &run : helpRuns(*this, &impl)) {
out += run.text;
}
return out;
}
void ParseResult::showHelp() const {
stdc_impl_t;
// Through the library's own console rather than fwrite, so that one program does not
// talk to the terminal two different ways, and so a Windows console gets the transcoding
// it needs.
for (const auto &run : helpRuns(*this, &impl)) {
console::fputs(run.style.style, run.style.foreground, run.style.background, run.text,
stdout);
}
}
void ParseResult::showError() const {
if (isValid()) {
return;
}
stdc_impl_t;
// What went wrong is worth a color where there is one to be had, and console works out
// for itself whether stderr is somewhere escapes belong.
console::fputs(console::bold, console::red, console::nocolor, impl.error_text + "\n",
stderr);
if (!impl.display_options.test_flag(Parser::SkipCorrection)) {
auto correction = correctionText();
if (!correction.empty()) {
console::fputs(console::nostyle, console::nocolor, console::nocolor,
correction + "\n", stderr);
}
}
// How this program spells asking for help rather than how most of them do. A tree that
// does not offer it at all gets no line, since pointing at something nobody declared is
// worse than saying nothing.
std::string help;
for (const auto &item : impl.options) {
if (item.option->role() != Option::Help) {
continue;
}
for (const auto &token : item.option->tokens()) {
// The long spelling where there is one, since that is the one worth reading.
if (help.empty() || (help.rfind("--", 0) != 0 && token.rfind("--", 0) == 0)) {
help = token;
}
}
break;
}
if (impl.target && !help.empty()) {
std::string name;
for (size_t i = 0; i < impl.path.size(); ++i) {
name += (i ? " " : "") + impl.path[i];
}
console::fputs(console::nostyle, console::nocolor, console::nocolor,
"Try \"" + name + " " + help + "\" for more information.\n", stderr);
}
}
// ---------------------------------------------------------------------------------------
// Help
// ---------------------------------------------------------------------------------------
namespace {
/// However narrow the terminal, a description gets at least this much. Below it the text
/// is broken into a column too thin to read, which is worse than running over.
constexpr int min_description = 20;
}
HelpFormatter::HelpFormatter() = default;
HelpFormatter::~HelpFormatter() = default;
// At spaces where there are any, and between characters where there are none, which is what
// a language that writes without spaces needs. Measured in columns rather than in bytes or
// characters, so a CJK description breaks where it looks like it should.
std::vector<std::string> HelpFormatter::wrapped(const std::string &text, int columns) {
std::vector<std::string> lines;
if (columns < 1) {
lines.push_back(text);
return lines;
}
auto points = utf::utf8_to_utf32(text);
std::u32string line;
int width = 0;
const auto emit = [&lines](std::u32string piece) {
while (!piece.empty() && piece.back() == U' ') {
piece.pop_back();
}
lines.push_back(utf::utf32_to_utf8(piece));
};
const auto measure = [](const std::u32string &piece) {
int res = 0;
for (char32_t c : piece) {
res += console::display_width(c);
}
return res;
};
for (char32_t c : points) {
if (c == U'\n') {
emit(std::move(line));
line.clear();
width = 0;
continue;
}
int w = console::display_width(c);
if (width + w > columns && !line.empty()) {
// Back up to the last space, so a word is not cut in half. A word longer than
// the whole column has no space to back up to and is broken where it reached
// the edge.
auto space = line.find_last_of(U' ');
if (space == std::u32string::npos) {
emit(line);
line.clear();
} else {
auto tail = line.substr(space + 1);
emit(line.substr(0, space));
line = tail;
}
width = measure(line);
}
line.push_back(c);
width += w;
}
emit(std::move(line));
return lines;
}
std::string HelpFormatter::displayed(const Argument &argument) const {
std::string res = "<" + argument.displayName() + ">";
if (argument.arity() != Argument::Single) {
res += "...";
}
return argument.isRequired() ? res : "[" + res + "]";
}
std::string HelpFormatter::displayed(const Option &option, bool allSpellings) const {
std::string res;
if (allSpellings) {
for (size_t i = 0; i < option.tokens().size(); ++i) {
res += (i ? ", " : "") + option.tokens()[i];
}
} else {
res = option.token();
}
// Through this rather than straight to the one above, so that a formatter overriding
// only the argument rung reaches every metavar there is.
for (const auto &argument : option.arguments()) {
res += " " + displayed(argument);
}
return res;
}
namespace {
/// Whether \a option can be printed and typed at all.
///
/// One with no spelling has nothing to show and nothing to be looked up by, and
/// token() is front() on an empty vector. Command::addOption() asserts on one, so this
/// only answers false in a release build, where the assert is gone and the option is in
/// the tree regardless. Asked wherever an option's name is read, so the two places
/// cannot come to disagree about what counts.
inline bool spelled(const Option &option) {
return !option.tokens().empty();
}
/// A block that prints the way \a slot asks for, with \a title over it.
HelpBlock blockLike(const HelpBlock &slot, std::string title) {
HelpBlock res;
res.role = slot.role;
res.title = std::move(title);
res.titleStyle = slot.titleStyle;
res.bodyStyle = slot.bodyStyle;
res.entryStyle = slot.entryStyle;
return res;
}
/// Puts \a items into the groups \a groups asks for, in the order it gives them, with
/// whatever it does not mention left under \a fallback at the end. One block per group,
/// all printed the way \a slot asks for.
template <class T, class Name, class Line>
std::vector<HelpBlock>
grouped(const std::vector<T> &items, const std::vector<CommandCatalogue::Group> &groups,
const HelpBlock &slot, const std::string &fallback, Name name, Line line) {
std::vector<HelpBlock> res;
std::vector<bool> taken(items.size(), false);
for (const auto &group : groups) {
HelpBlock block = blockLike(slot, group.name);
for (const auto &wanted : group.members) {
for (size_t i = 0; i < items.size(); ++i) {
if (!taken[i] && name(items[i]) == wanted) {
block.entries.push_back(line(items[i]));
taken[i] = true;
break;
}
}
}
if (!block.entries.empty()) {
res.push_back(std::move(block));
}
}
HelpBlock rest = blockLike(slot, fallback);
for (size_t i = 0; i < items.size(); ++i) {
if (!taken[i]) {
rest.entries.push_back(line(items[i]));
}
}
if (!rest.entries.empty()) {
res.push_back(std::move(rest));
}
return res;
}
/// Runs that print the same way are one run, so that a plain help text comes out of
/// showHelp() in a single write rather than in one per column.
void appendRun(std::vector<HelpFormatter::Run> &out, const TextStyle &style,
const std::string &text) {
if (text.empty()) {
return;
}
if (!out.empty() && out.back().style == style) {
out.back().text += text;
return;
}
out.push_back({style, text});
}
void appendRuns(std::vector<HelpFormatter::Run> &out,
const std::vector<HelpFormatter::Run> &more) {
for (const auto &run : more) {
appendRun(out, run.style, run.text);
}
}
// Broken into as many lines as the room a section body gets, with the breaks written into
// the text.
std::string usage_text(const HelpFormatter &formatter, const Command &command,
const std::vector<std::string> &path,
const std::vector<Option> &inherited, int indent, int text_width) {
std::string head;
for (size_t i = 0; i < path.size(); ++i) {
head += (i ? " " : "") + path[i];
}
// An option that has to be given is not optional information, so it is spelled out
// where a reader looks first rather than left inside "[options]". The hint stays for
// whatever is left, and goes away when nothing is.
// A subcommand's name comes first or not at all, so it is written first here. An
// option before it ends the command path, which is why the other order was the one
// arrangement the parser refuses.
std::vector<std::string> parts;
if (!command.commands().empty()) {
parts.push_back("[commands]");
}
size_t optional_count = 0;
const auto &take = [&](const Option &option) {
if (!spelled(option)) {
return;
}
if (option.isRequired()) {
parts.push_back(formatter.displayed(option, false));
} else {
optional_count++;
}
};
for (const auto &option : command.options()) {
take(option);
}
for (const auto &option : inherited) {
take(option);
}
if (optional_count > 0) {
parts.push_back("[options]");
}
for (const auto &argument : command.arguments()) {
parts.push_back(formatter.displayed(argument));
}
int room = std::max(text_width - indent, min_description);
std::string res = head;
int line_width = console::display_width(head);
for (const auto &part : parts) {
int part_width = console::display_width(part);
if (line_width > 0 && line_width + 1 + part_width > room) {
res += "\n";
line_width = 0;
}
// At the margin the piece goes straight down under the one above. Anywhere else
// it needs the space that separates it from what came before.
res += line_width == 0 ? part : " " + part;
line_width += line_width == 0 ? part_width : 1 + part_width;
}
return res;
}
}
std::string HelpFormatter::displayed(const Command &command) const {
return command.name();
}
// What an argument adds to the right hand column beyond its description. The same for an
// argument of a command and an argument of an option, since a default value is worth as much
// in either place.
static std::string argument_extras(const Argument &argument, const HelpSizes &sizes) {
auto flags = sizes.displayOptions;
std::string res;
if (flags.test_flag(Parser::ShowArgumentExpectedValues) &&
!argument.expectedValues().empty()) {
std::string words;
for (const auto &item : argument.expectedValues()) {
words += (words.empty() ? "" : ", ") + item;
}
res += " [" + words + "]";
}
if (flags.test_flag(Parser::ShowArgumentDefaultValue) && argument.hasDefaultValue()) {
res += " (default: " + argument.defaultValue() + ")";
}
return res;
}
HelpBlock::Entry HelpFormatter::entry(const Argument &argument, const HelpSizes &sizes) const {
return {displayed(argument), argument.description() + argument_extras(argument, sizes)};
}
HelpBlock::Entry HelpFormatter::entry(const Option &option, const HelpSizes &sizes) const {
std::string right = option.description();
for (const auto &argument : option.arguments()) {
right += argument_extras(argument, sizes);
}
if (sizes.displayOptions.test_flag(Parser::ShowOptionIsRequired) && option.isRequired()) {
right += " (required)";
}
return {displayed(option, true), right};
}
HelpBlock::Entry HelpFormatter::entry(const Command &command, const HelpSizes &) const {
return {displayed(command), command.description()};
}
std::string HelpFormatter::usageText(const Command &command,
const std::vector<std::string> &path,
const std::vector<Option> &inherited,
const HelpSizes &sizes) const {
return usage_text(*this, command, path, inherited, sizes.indent, sizes.textWidth);
}
std::vector<HelpBlock> HelpFormatter::blocks(const ParseResult &result,
const HelpSizes &sizes) const {
if (!result.command()) {
return {};
}
const Command &command = *result.command();
const auto &catalogue = command.catalogue();
auto flags = sizes.displayOptions;
// A row at a time, through the rung that makes one, so that a formatter changing what a
// row says does not have to take over this whole function to do it.
auto argument_line = [this, &sizes](const Argument &item) { return entry(item, sizes); };
auto option_line = [this, &sizes](const Option &item) { return entry(item, sizes); };
auto command_line = [this, &sizes](const Command &item) { return entry(item, sizes); };
// Only the ones that can be printed, which is spelled() and why. The help text is not
// the place to find out that a tree holds an option nobody can type.
std::vector<Option> own;
for (const auto &item : command.options()) {
if (spelled(item)) {
own.push_back(item);
}
}
// What the commands above declared recursive is in scope here and is demanded here, so
// it is listed here. Under a heading of its own, since it belongs to the program rather
// than to this command, and since the catalogue's groups were written for this
// command's own options and have nothing to say about these.
std::vector<Option> inherited_options;
for (const auto *option : result.inheritedOptions()) {
if (spelled(*option)) {
inherited_options.push_back(*option);
}
}
std::vector<HelpBlock> out;
// A block with nothing in it is not printed and not handed out, so a command with no
// subcommands says nothing about subcommands rather than showing an empty heading.
const auto push = [&out](HelpBlock block) {
if (!block.isEmpty()) {
out.push_back(std::move(block));
}
};
const auto pushAll = [&out](std::vector<HelpBlock> blocks) {
for (auto &block : blocks) {
out.push_back(std::move(block));
}
};
for (const auto &slot : result.helpLayout().blocks()) {
switch (slot.role) {
case HelpBlock::Prologue: {
auto block = blockLike(slot, {});
block.text = result.prologue();
push(std::move(block));
break;
}
case HelpBlock::Description: {
auto block = blockLike(slot, "Description");
block.text = command.description();
push(std::move(block));
break;
}
case HelpBlock::Usage: {
auto block = blockLike(slot, "Usage");
block.text = usageText(command, result.commandPath(), inherited_options, sizes);
push(std::move(block));
break;
}
case HelpBlock::Arguments: {
pushAll(grouped(
command.arguments(), catalogue.argumentGroups(), slot, "Arguments",
[](const Argument &item) { return item.name(); }, argument_line));
break;
}
// ###QUESTION: a recursive option is listed here on the page of the command
// that declared it and under "Global options" on the pages below, so the same
// spelling sits under two headings depending on which page is being read. That
// is what Cobra does with a persistent flag. The other two answers are to list
// it under "Global options" everywhere, which splits the declaring command's
// list by something a reader there cannot act on, and to drop the second block
// altogether, which is System.CommandLine's and loses the one thing worth
// saying on a subcommand's page: this is not mine, read the program's help.
// Should it be the same heading on both? Four lines here if so, filtering the
// recursive ones out of own and adding them to the block below.
case HelpBlock::Options: {
pushAll(grouped(
own, catalogue.optionGroups(), slot, "Options",
[](const Option &item) { return item.token(); }, option_line));
break;
}
case HelpBlock::InheritedOptions: {
auto block = blockLike(slot, "Global options");
for (const auto &option : inherited_options) {
block.entries.push_back(option_line(option));
}
push(std::move(block));
break;
}
case HelpBlock::Commands: {
pushAll(grouped(
command.commands(), catalogue.commandGroups(), slot, "Commands",
[](const Command &item) { return item.name(); }, command_line));
break;
}