tclap 1.6.0
StdOutput.h
Go to the documentation of this file.
1// -*- Mode: c++; c-basic-offset: 4; tab-width: 4; -*-
2
3/******************************************************************************
4 *
5 * file: StdOutput.h
6 *
7 * Copyright (c) 2004, Michael E. Smoot
8 * Copyright (c) 2017, Google LLC
9 * All rights reserved.
10 *
11 * See the file COPYING in the top directory of this distribution for
12 * more information.
13 *
14 * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
17 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
19 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
20 * DEALINGS IN THE SOFTWARE.
21 *
22 *****************************************************************************/
23
24#ifndef TCLAP_STD_OUTPUT_H
25#define TCLAP_STD_OUTPUT_H
26
27#include <tclap/Arg.h>
28#include <tclap/ArgGroup.h>
30#include <tclap/CmdLineOutput.h>
31
32#include <algorithm>
33#include <cctype>
34#include <cstddef>
35#include <format>
36#include <iostream>
37#include <list>
38#include <sstream>
39#include <string>
40#include <utility>
41#include <vector>
42
43namespace TCLAP {
44
49class StdOutput : public CmdLineOutput {
50public:
56 void usage(CmdLineInterface &c) override;
57
63 void version(CmdLineInterface &c) override;
64
71 void failure(CmdLineInterface &c, ArgException &e) override;
72
73protected:
79 void _shortUsage(CmdLineInterface &c, std::ostream &os) const;
80
87 void _longUsage(CmdLineInterface &c, std::ostream &os) const;
88
100 void spacePrint(std::ostream &os, const std::string &s, int maxWidth,
101 int indentSpaces, int secondLineOffset) const;
102
103private:
104 static constexpr int _usageWidth = 75;
105
106 void _partitionGroups(std::list<ArgGroup *> &groups,
107 std::list<ArgGroup *> &exclusiveGroups,
108 std::list<ArgGroup *> &nonExclusiveGroups) const;
109 void _printShortSwitches(std::ostream &os, std::string &switches,
110 std::list<ArgGroup *> &groups) const;
111 void _printLongSwitches(std::ostream &os,
112 std::list<ArgGroup *> &groups) const;
113 void _printShortOptions(std::ostream &os,
114 std::list<ArgGroup *> &groups) const;
115 void _printShortOperands(CmdLineInterface &cmd, std::ostream &os,
116 std::list<ArgGroup *> &groups) const;
117 void _printLabeledGroups(CmdLineInterface &cmd, std::ostream &os,
118 std::list<ArgGroup *> &groups) const;
119 void _printLongOperands(CmdLineInterface &cmd, std::ostream &os,
120 std::list<ArgGroup *> &groups) const;
121 void _printExclusiveLongGroup(CmdLineInterface &cmd, std::ostream &os,
122 ArgGroup &group) const;
123 void _printGroupHeading(CmdLineInterface &cmd, std::ostream &os,
124 const ArgGroup &group) const;
125 void _printLongEntry(std::ostream &os, const Arg &arg, bool required,
126 int indent) const;
127};
128
130 std::cout << std::format("\n{} {} {}\n\n", _cmd.getProgramName(),
131 _cmd.translateMessage("version_label", "version:"),
132 _cmd.getVersion())
133 << std::flush;
134}
135
137 std::cout << std::format(
138 "\n{}\n\n", _cmd.translateMessage("usage_header", "USAGE: "));
139
140 _shortUsage(_cmd, std::cout);
141
142 std::cout << std::format(
143 "\n\n{}\n\n", _cmd.translateMessage("where_header", "Where: "));
144
145 _longUsage(_cmd, std::cout);
146
147 std::cout << '\n' << std::flush;
148}
149
151 std::cerr << std::format(
152 "{} {}\n {}\n\n",
153 _cmd.translateMessage("parse_error_header", "PARSE ERROR:"), e.argId(),
154 e.error());
155
156 if (_cmd.hasHelpAndVersion()) {
157 std::cerr << std::format(
158 "{}\n", _cmd.translateMessage("brief_usage_header", "Brief USAGE: "));
159
160 _shortUsage(_cmd, std::cerr);
161
162 std::cerr << std::format(
163 "\n{}\n {} {}help\n\n",
164 _cmd.translateMessage(
165 "complete_usage_hint",
166 "For complete USAGE and HELP type: "),
168 << std::flush;
169 } else {
170 usage(_cmd);
171 }
172
173 throw ExitException(1);
174}
175
176// TODO: Remove this
177inline void removeChar(std::string &s, char r) {
178 size_t p;
179 while ((p = s.find_first_of(r)) != std::string::npos) {
180 s.erase(p, 1);
181 }
182}
183
184inline bool cmpSwitch(const char &a, const char &b) {
185 int lowa = std::tolower(a);
186 int lowb = std::tolower(b);
187
188 if (lowa == lowb) {
189 return a < b;
190 }
191
192 return lowa < lowb;
193}
194
195namespace internal {
196inline bool IsVisibleShortSwitch(const Arg &arg) {
197 return !(arg.getName() == Arg::ignoreNameString() ||
198 arg.isValueRequired() || arg.getFlag() == "") &&
199 arg.visibleInHelp();
200}
201
202inline bool IsVisibleLongSwitch(const Arg &arg) {
203 return (arg.getName() != Arg::ignoreNameString() &&
204 !arg.isValueRequired() && arg.getFlag() == "" &&
205 arg.visibleInHelp());
206}
207
208inline bool IsVisibleOption(const Arg &arg) {
209 return (arg.getName() != Arg::ignoreNameString() && arg.isValueRequired() &&
210 arg.hasLabel() && arg.visibleInHelp());
211}
212
213inline bool CompareShortID(const Arg *a, const Arg *b) {
214 if (a->getFlag() == "" && b->getFlag() != "") {
215 return false;
216 }
217 if (b->getFlag() == "" && a->getFlag() != "") {
218 return true;
219 }
220
221 return a->shortID() < b->shortID();
222}
223
224// TODO: Fix me not to put --gopt before -f
225inline bool CompareOptions(std::pair<const Arg *, bool> a,
226 std::pair<const Arg *, bool> b) {
227 // First optional, then required
228 if (!a.second && b.second) {
229 return true;
230 }
231 if (a.second && !b.second) {
232 return false;
233 }
234
235 return CompareShortID(a.first, b.first);
236}
237// Group order is presentation order; positional operands use parser order.
238inline ArgGroup *FindArgGroup(const std::list<ArgGroup *> &groups,
239 const Arg *arg) {
240 for (ArgGroup *group : groups)
241 if (std::ranges::find(*group, arg) != group->end()) return group;
242 return nullptr;
243}
244
245inline bool HasVisiblePositional(const ArgGroup &group) {
246 for (const Arg *arg : group)
247 if (!arg->hasLabel() && arg->visibleInHelp()) return true;
248 return false;
249}
250
251inline void PrintExclusiveShortGroup(std::ostream &os, const ArgGroup &group) {
252 os << (group.isRequired() ? " {" : " [");
253 std::vector<Arg *> args;
254 for (Arg *arg : group)
255 if (arg->visibleInHelp()) args.push_back(arg);
256 std::ranges::sort(args, CompareShortID);
257 const char *separator = "";
258 for (const Arg *arg : args) {
259 os << separator << arg->shortID();
260 separator = "|";
261 }
262 os << (group.isRequired() ? '}' : ']');
263}
264} // namespace internal
265
282 std::ostream &os) const {
283 std::list<ArgGroup *> argSets = _cmd.getArgGroups();
284
285 std::ostringstream outp;
286 outp << _cmd.getProgramName() + " ";
287
288 std::string switches = Arg::flagStartString();
289 std::list<ArgGroup *> exclusiveGroups;
290 std::list<ArgGroup *> nonExclusiveGroups;
291 _partitionGroups(argSets, exclusiveGroups, nonExclusiveGroups);
292 _printShortSwitches(outp, switches, nonExclusiveGroups);
293 _printLongSwitches(outp, nonExclusiveGroups);
294
295 // Exclusive groups containing operands are printed with those operands.
296 for (const ArgGroup *group : exclusiveGroups) {
297 if (!internal::HasVisiblePositional(*group))
298 internal::PrintExclusiveShortGroup(outp, *group);
299 }
300
301 _printShortOptions(outp, nonExclusiveGroups);
302 _printShortOperands(_cmd, outp, argSets);
303
304 // if the program name is too long, then adjust the second line offset
305 int secondLineOffset = static_cast<int>(_cmd.getProgramName().length()) + 2;
306 if (secondLineOffset > _usageWidth / 2)
307 secondLineOffset = static_cast<int>(_usageWidth / 2);
308
309 spacePrint(os, outp.str(), _usageWidth, 3, secondLineOffset);
310}
311
312inline void StdOutput::_partitionGroups(
313 std::list<ArgGroup *> &groups, std::list<ArgGroup *> &exclusiveGroups,
314 std::list<ArgGroup *> &nonExclusiveGroups) const {
315 for (ArgGroup *groupPtr : groups) {
316 if (CountVisibleArgs(*groupPtr) <= 0) {
317 continue;
318 }
319
320 if (groupPtr->isExclusive()) {
321 exclusiveGroups.push_back(groupPtr);
322 } else {
323 nonExclusiveGroups.push_back(groupPtr);
324 }
325 }
326
327 // Move "exclusive groups" that have at most a single item to
328 // non-exclusive groups as exclusivit doesn't make sense with a
329 // single option. This can happen if args are hidden in help for
330 // example.
331 for (auto it = exclusiveGroups.begin(); it != exclusiveGroups.end();) {
332 if (CountVisibleArgs(**it) < 2) {
333 nonExclusiveGroups.push_back(*it);
334 it = exclusiveGroups.erase(it);
335 } else {
336 ++it;
337 }
338 }
339}
340
341inline void StdOutput::_printShortSwitches(
342 std::ostream &os, std::string &switches,
343 std::list<ArgGroup *> &groups) const {
344 bool hasShortSwitches = false;
345
346 // First short switches (needs to be special because they are all
347 // stuck together).
348 for (ArgGroup *groupPtr : groups) {
349 for (Arg *argPtr : *groupPtr) {
350 if (internal::IsVisibleShortSwitch(*argPtr)) {
351 switches += argPtr->getFlag();
352 hasShortSwitches = true;
353 }
354 }
355
356 std::ranges::sort(switches, cmpSwitch);
357 }
358
359 if (hasShortSwitches) os << " [" << switches << ']';
360}
361
362inline void StdOutput::_printLongSwitches(std::ostream &os,
363 std::list<ArgGroup *> &groups) const {
364 // Now do long switches (e.g., --version, but no -v)
365 std::vector<Arg *> longSwitches;
366 for (ArgGroup *groupPtr : groups) {
367 for (Arg *argPtr : *groupPtr) {
368 Arg &arg = *argPtr;
369 if (internal::IsVisibleLongSwitch(arg)) {
370 longSwitches.push_back(&arg);
371 }
372 }
373 }
374
375 std::ranges::sort(longSwitches, internal::CompareShortID);
376 for (const Arg *arg : longSwitches) {
377 os << " [" << arg->shortID() << ']';
378 }
379}
380
381inline void StdOutput::_printShortOptions(std::ostream &os,
382 std::list<ArgGroup *> &groups) const {
383 // Next do options, we sort them later by optional first.
384 std::vector<std::pair<const Arg *, bool> > options;
385 for (ArgGroup *groupPtr : groups) {
386 for (Arg *argPtr : *groupPtr) {
387 Arg &arg = *argPtr;
388 int visible = CountVisibleArgs(*groupPtr);
389 bool required = arg.isRequired();
390 if (internal::IsVisibleOption(arg)) {
391 if (visible == 1 && groupPtr->isRequired()) {
392 required = true;
393 }
394
395 options.emplace_back(&arg, required);
396 }
397 }
398 }
399
400 std::ranges::sort(options, internal::CompareOptions);
401 for (const auto &[argPtr, required] : options) {
402 const Arg &arg = *argPtr;
403 os << (required ? " " : " [");
404 os << arg.shortID();
405 os << (required ? "" : "]");
406 }
407}
408
409inline void StdOutput::_printShortOperands(
410 CmdLineInterface &cmd, std::ostream &os,
411 std::list<ArgGroup *> &groups) const {
412 // Positional order must match the order in which the parser consumes argv.
413 const std::list<Arg *> operands = cmd.getArgList();
414 std::list<ArgGroup *> shown;
415 for (const Arg *argPtr : operands) {
416 const Arg &arg = *argPtr;
417 if (arg.hasLabel() || !arg.isValueRequired() || !arg.visibleInHelp())
418 continue;
419 ArgGroup *group = internal::FindArgGroup(groups, &arg);
420 if (group && group->isExclusive() && CountVisibleArgs(*group) > 1) {
421 if (std::ranges::find(shown, group) == shown.end()) {
422 internal::PrintExclusiveShortGroup(os, *group);
423 shown.push_back(group);
424 }
425 continue;
426 }
427 bool required = arg.isRequired() ||
428 (group && group->isRequired() && CountVisibleArgs(*group) == 1);
429 os << (required ? " " : " [") << arg.shortID() << (required ? "" : "]");
430 }
431}
432
434 std::ostream &os) const {
435 std::string message = _cmd.getMessage();
436 std::list<ArgGroup *> argSets = _cmd.getArgGroups();
437
438 _printLabeledGroups(_cmd, os, argSets);
439 _printLongOperands(_cmd, os, argSets);
440
441 if (!message.empty()) {
442 spacePrint(os, message, _usageWidth, 3, 0);
443 }
444
445 os.flush();
446}
447
448inline void StdOutput::_printLabeledGroups(
449 CmdLineInterface &cmd, std::ostream &os,
450 std::list<ArgGroup *> &groups) const {
451 for (ArgGroup *groupPtr : groups) {
452 ArgGroup &argGroup = *groupPtr;
453
454 int visible = CountVisibleArgs(argGroup);
455 bool exclusive = visible > 1 && argGroup.isExclusive();
456 if (exclusive && internal::HasVisiblePositional(argGroup)) continue;
457 bool forceRequired = visible == 1 && argGroup.isRequired();
458 if (exclusive) {
459 _printGroupHeading(cmd, os, argGroup);
460 }
461
462 for (Arg *argPtr : argGroup) {
463 Arg &arg = *argPtr;
464 if (!arg.visibleInHelp()) {
465 continue;
466 }
467
468 if (!arg.hasLabel()) {
469 continue;
470 }
471
472 bool required = arg.isRequired() || forceRequired;
473 _printLongEntry(os, arg, required, exclusive ? 6 : 3);
474 }
475 }
476}
477
478inline void StdOutput::_printLongOperands(CmdLineInterface &cmd,
479 std::ostream &os,
480 std::list<ArgGroup *> &groups) const {
481 const std::list<Arg *> operands = cmd.getArgList();
482 std::list<ArgGroup *> shown;
483 for (const Arg *argPtr : operands) {
484 const Arg &arg = *argPtr;
485 if (arg.hasLabel() || !arg.visibleInHelp()) continue;
486 ArgGroup *group = internal::FindArgGroup(groups, &arg);
487 if (group && group->isExclusive() && CountVisibleArgs(*group) > 1) {
488 if (std::ranges::find(shown, group) != shown.end()) continue;
489 shown.push_back(group);
490 _printExclusiveLongGroup(cmd, os, *group);
491 continue;
492 }
493 const bool required = arg.isRequired() ||
494 (group && group->isRequired() && CountVisibleArgs(*group) == 1);
495 _printLongEntry(os, arg, required, 3);
496 }
497}
498
499inline void StdOutput::_printExclusiveLongGroup(CmdLineInterface &cmd,
500 std::ostream &os,
501 ArgGroup &group) const {
502 _printGroupHeading(cmd, os, group);
503 for (const Arg *member : group) {
504 if (!member->visibleInHelp()) continue;
505 // Preserve longID() before the virtual isRequired() call.
506 spacePrint(os, member->longID(), _usageWidth, 6, 3);
507 spacePrint(os, member->getDescription(member->isRequired()),
508 _usageWidth, 8, 0);
509 os << '\n';
510 }
511}
512
513inline void StdOutput::_printGroupHeading(CmdLineInterface &cmd,
514 std::ostream &os,
515 const ArgGroup &group) const {
516 spacePrint(os,
517 group.isRequired()
518 ? cmd.translateMessage("one_of_group", "One of:")
519 : cmd.translateMessage("either_of_group", "Either of:"),
520 _usageWidth, 3, 0);
521}
522
523inline void StdOutput::_printLongEntry(std::ostream &os, const Arg &arg,
524 bool required, int indent) const {
525 spacePrint(os, arg.longID(), _usageWidth, indent, 3);
526 spacePrint(os, arg.getDescription(required), _usageWidth, indent + 2, 0);
527 os << '\n';
528}
529
530namespace {
531inline void fmtPrintLine(std::ostream &os, const std::string &text,
532 int maxWidth, int indentSpaces, int secondLineOffset) {
533 const std::string breakCharacters(" ,|");
534 // String indentation uses unsigned counts; clamp negative geometry first.
535 indentSpaces = std::max(indentSpaces, 0);
536 secondLineOffset = std::max(secondLineOffset, 0);
537 size_t availableWidth = std::max(maxWidth - indentSpaces, 0);
538 std::string indentString(indentSpaces, ' ');
539 size_t lineStart = 0;
540 size_t lineEnd = 0;
541 size_t textLength = text.length();
542 for (;;) {
543 if (textLength - lineStart <= availableWidth) {
544 // Rest of string fits on line, just print the remainder
545 os << indentString << text.substr(lineStart) << std::endl;
546 return;
547 }
548
549 // Keep the last delimiter that fits within the available width.
550 size_t nextBreak = lineEnd;
551 while (nextBreak - lineStart <= availableWidth &&
552 nextBreak != std::string::npos) {
553 lineEnd = nextBreak;
554 nextBreak = text.find_first_of(breakCharacters, lineEnd + 1);
555 }
556
557 if (lineEnd == lineStart) {
558 // Split a long word. A zero width must still consume one byte;
559 // subtracting from zero would underflow the unsigned width.
560 lineEnd =
561 availableWidth > 0 ? lineStart + availableWidth - 1 : lineStart;
562 }
563
564 if (text[lineEnd] != ' ') {
565 // Include delimiter before line break, unless it's a space
566 lineEnd++;
567 }
568
569 os << indentString << text.substr(lineStart, lineEnd - lineStart)
570 << '\n';
571
572 // Avoid printing extra white space at start of a line
573 for (; text[lineEnd] == ' '; lineEnd++) {
574 }
575 lineStart = lineEnd;
576
577 if (secondLineOffset != 0) {
578 // Adjust offset for following lines
579 indentString.insert(indentString.end(), secondLineOffset, ' ');
580 // Clamp the remaining width to prevent unsigned underflow.
581 availableWidth -=
582 std::min(availableWidth, static_cast<size_t>(secondLineOffset));
583 secondLineOffset = 0;
584 }
585 }
586}
587} // namespace
588
589inline void StdOutput::spacePrint(std::ostream &os, const std::string &s,
590 int maxWidth, int indentSpaces,
591 int secondLineOffset) const {
592 std::stringstream ss(s);
593 std::string line;
594 std::getline(ss, line);
595 fmtPrintLine(os, line, maxWidth, indentSpaces, secondLineOffset);
596 indentSpaces += secondLineOffset;
597
598 while (std::getline(ss, line)) {
599 fmtPrintLine(os, line, maxWidth, indentSpaces, 0);
600 }
601}
602
603} // namespace TCLAP
604
605#endif // TCLAP_STD_OUTPUT_H
A simple class that defines and argument exception.
std::string argId() const
Returns the argument id.
std::string error() const
Returns the error text.
ArgGroup is the base class for implementing groups of arguments that are mutually exclusive (it repla...
Definition ArgGroup.h:42
virtual bool isExclusive() const =0
Returns true if this argument group is exclusive.
virtual bool isRequired() const =0
Returns true if this argument group is required.
A virtual base class that defines the essential data for all arguments.
Definition Arg.h:69
static std::string flagStartString()
Definition Arg.h:266
static std::string nameStartString()
Definition Arg.h:275
static std::string ignoreNameString()
The name used to identify the ignore rest argument.
Definition Arg.h:280
The base class that manages the command line definition and passes along the parsing to the appropria...
virtual std::string getVersion() const =0
Returns the version string.
virtual std::string getMessage() const =0
Returns the message string.
virtual bool hasHelpAndVersion() const =0
Indicates whether or not the help and version switches were created automatically.
virtual std::string translateMessage(const std::string &messageId, const std::string &fallback) const =0
Translates a built-in message using the current translator.
virtual std::string getProgramName() const =0
Returns the program name string.
virtual std::list< ArgGroup * > getArgGroups()=0
Returns the list of ArgGroups.
The interface that any output object must implement.
Thrown when TCLAP thinks the program should exit.
A class that isolates any output from the CmdLine object so that it may be easily modified.
Definition StdOutput.h:49
void failure(CmdLineInterface &c, ArgException &e) override
Prints (to stderr) an error message, short usage Can be overridden to produce alternative behavior.
Definition StdOutput.h:150
void usage(CmdLineInterface &c) override
Prints the usage to stdout.
Definition StdOutput.h:136
void spacePrint(std::ostream &os, const std::string &s, int maxWidth, int indentSpaces, int secondLineOffset) const
This function inserts line breaks and indents long strings according the params input.
Definition StdOutput.h:589
void _shortUsage(CmdLineInterface &c, std::ostream &os) const
Writes a brief usage message with short args.
Definition StdOutput.h:281
void _longUsage(CmdLineInterface &c, std::ostream &os) const
Writes a longer usage message with long and short args, provides descriptions and prints message.
Definition StdOutput.h:433
void version(CmdLineInterface &c) override
Prints the version to stdout.
Definition StdOutput.h:129
Definition Arg.h:54
int CountVisibleArgs(const ArgGroup &g)
Definition ArgGroup.h:248
void removeChar(std::string &s, char r)
Definition StdOutput.h:177
bool cmpSwitch(const char &a, const char &b)
Definition StdOutput.h:184