GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
GeezerVison is showing cpp.libhunt.com โ clipp Alternatives - C++ CLI | LibHunt clippeasy to use, powerful & expressive command line argument parsing for modern C++ / single header / usage & doc generation
Take the C++ Developer Survey
- About 6 minutes on the tools, libraries and AI you use with C++. You get the results by email.
Take the survey ยป
Popularity
5.7
Growing
Activity
0.0
Stable
Stars
1,323
Watchers
26
Forks
154
Last Commit
DescriptionEasy to use, powerful and expressive command line argument handling for C++11/14/17 contained in a single header file.
Programming language: C++
License: MIT License
Latest version: v1.2.3
clipp alternatives and similar libraries
Based on the "CLI" category.
SaaSHub - Software Alternatives and Reviews
SaaSHub helps you find the best software and product alternatives
Promo
www.saashub.com
* Code Quality Rankings and insights are calculated and provided by Lumnify.
Do you think we are missing an alternative of clipp or a related project? READMEclipp - command line interfaces for modern C++Easy to use, powerful and expressive command line argument handling for C++11/14/17 contained in a single header file.
Quick IntroSimple Use Case โ Simple Setup!Consider this command line interface:
Here is the code that defines the positional value
A More Complex Example:
This CLI has three alternative commands ( Here is the code that defines the interface, generates the man page snippet above and handles the parsing result:
Quick ReferenceBelow are a few examples that should give you an idea for how clipp works. Consider this basic setup with a few variables that we want to set using command line arguments:
OverviewSee the examples section for detailed explanations of each topic. Namespace qualifiers are omitted from all examples for better readability. All entities are defined in Basic Setup
There are two kinds of building blocks for command line interfaces: parameters and groups. Convieniently named factory functions produce parameters or groups with the desired settings applied. Parameters (flag strings, commands, positional values, required flags, repeatable parameters)
The functions above are convenience factories:
Flags + ValuesIf you want parameters to be matched in sequence, you can tie them together using either
Filtering Value ParametersValue parameters use a filter function to test if they are allowed to match an argument string. The default filter
Analogous to Value Parameters With Custom Filters
Groups
auto cli2 = one_of( value("input_file") , command("list") , command("flush") );
Note that surrounding groups are not affected by this, so that
auto cli2 = with_prefix_short_long("-", "--", option("a", "all"), option("b"), ... ); // => -a --all -b
//works also with arbitrary common prefixes: auto cli2 = joinable( option("--xA0"), option("--xB1")); //will also match "--xA0B1" or "--xB1A0"
In production code one would probably use a settings class:
Note that the target must either be:
Generating Documentation (see also here)Docstrings for groups and for parameters can either be set with the member function
Usage Lines:
Detailed Documentation:
Man Pages:
(Error) Event Handlers (see here, and here)Each parameter can have event handler functions attached to it. These are invoked once for each argument that is mapped to the parameter (or once per missing event):
The handler functions can also take an int, which is set to the argument index at which the event occurred first:
Special CasesIf we give
This behavior is fine for most use cases.
But what if we want our program to take any string as a filename, because our filenames might also collide with flag names? We can make the value parameter greedy with
Be very careful with greedy parameters! Parsing Result Analysis
Writing Your Own Convenience FactoriesSometimes it can make your CLI code more expressive and increase maintainability, if you create your own factory functions for making parameters:
ExamplesNote that namespace qualifiers are omitted from all examples for better readability. The repository folder "examples" contains code for most of the following examples.
Options
This will set Coding StylesIf you like it more verbose use
You can also use
|
| joinable flags | valid args |
|---|---|
a, b |
ab, ba, a, b |
-a, -b |
-ab, -ba, -a, -b, -a-b, -b-a |
--a, --b |
--ab, --ba, --a, --b, --a--b, --b--a |
,a, ,b |
,ab, ,ba, ,a, ,b, ,a,b, ,b,a |
Xab, Xcd |
Xabcd, Xcdab, XabXcd, XcdXab, Xab, Xcd |
x:ab, x:cd |
x:abcd, x:cdab, x:abx:cd, x:cdx:ab, x:ab, x:cd |
SYNOPSIS
find <file>... -s <expr> [any|all]
OPTIONS
<file>... input filenames
-s <expr> string to look for
any report as soon as any matches
all report only if all match
vector<string> files;
string expr;
bool ifany = false, ifall = false;
auto cli = (
values("file", files) % "input filenames",
(required("-s") & value("expr", expr)) % "string to look for",
option("any").set(ifany) % "report as soon as any matches" |
option("all").set(ifall) % "report only if all match"
);
If you like it more verbose you can use the function one_of instead of operator |:
auto cli = (
values("file", files) % "input filenames",
(required("-s") & value("expr", expr)) % "string to look for",
one_of( option("any").set(ifany) % "report as soon as any matches",
option("all").set(ifall) % "report only if all match" )
);
SYNOPSIS
format [-o <output file>] [-falign|-fnoalign)]
OPTIONS
-o, --out <file>
output filename
-falign, -fnoalign
control alignment
string outfile = "a.out";
bool align = false;
auto cli = (
(option("-o", "--out") & value("output file", outfile)) % "output filename",
( option("-falign" ).set(align,true) |
option("-fnoalign").set(align,false) ) % "control alignment"
);
Note, that the documentation string is attached to the group of parameters for better readability.
//has the same meaning as the code above
string outfile = "a.out";
bool align = false;
auto cli = (
(option("-o", "--out") & value("output file", outfile)) % "output filename",
with_prefix("-f", option("align" ).set(align,true) |
option("noalign").set(align,false) ) % "control alignment"
);
Usage: format [-o <output file>] [-f(align|noalign)]
auto fmt = doc_formatting{}.merge_alternative_flags_with_common_prefix(true);
cout << usage_lines(cli, "format", fmt) << '\n';
= positional, required flags
SYNOPSIS
make_doc new <filename> [-e <enc>]
OPTIONS
-e, --encoding 'utf8' or 'cp1252', default is UTF-8
std::string fname;
std::string enc = "utf8";
auto cli = (
command("new"),
value("filename", fname),
option("-e", "--encoding") & value("enc", enc).doc("'utf8' or 'cp1252', default is " + enc)
);
SYNOPSIS
image-find help
image-find build (new|add) <file>... [-v] [-b [<size=1024>]] [--init|--no-init]
image-find query <infile> -o <outfile> [-f <format>]
OPTIONS
-v, --verbose
print detailed report
-b, --buffer [<size=1024>]
sets buffer size in KiByte
--init, --no-init
do or don't initialize
-f, --out-format <format>
determine output format
Value handling actions are omitted; see examples/nested_alternatives.cpp for a fully functional demo.
auto cli = (
command("help")
| ( command("build"),
( command("new") | command("add")),
values("file"),
option("-v", "--verbose") % "print detailed report",
(option("-b", "--buffer") & opt_value("size=1024")) % "sets buffer size in KiByte",
( option("--init") | option("--no-init") ) % "do or don't initialize"
)
| ( command("query"),
value("infile"),
required("-o", "--out") & value("outfile"),
(option("-f", "--out-format") & value("format")) % "determine output format"
)
);
Note:
doc_formatting::split_alternatives(bool) //default: true
doc_formatting::alternatives_min_split_size(int) //default: 3
control if the usage is split up into several lines if any group inside an alternative exceeds a given minimum size.
The combination of blocking parameters, alternatives and grouping makes it possible to define interfaces with decision trees/DAGs of arbitrary complexity.
SYNOPSIS
complex_nesting [-v] [-i] (copy|move) [--all] [--replace] [-f] <files>... [-r] [-h]
complex_nesting [-v] [-i] compare (date|content) [-b] [-q] <files>... [-r] [-h]
complex_nesting [-v] [-i] merge (diff|patch) -o <outdir> [--show-conflicts] <files>... [-r] [-h]
complex_nesting [-v] [-i] merge content [--git-style] [-m <marker>] -o <outdir> [--show-conflicts] <files>... [-r] [-h]
complex_nesting [-v] [-i] list <files>... [-r] [-h]
OPTIONS
user interface options:
-v, --verbose show detailed output
-i, --interactive use interactive mode
copy mode:
--all copy all
--replace replace existing files
-f, --force don't ask for confirmation
compare mode:
-b, --binary compare files byte by byte
-q, --quick use heuristics for faster comparison
merge mode:
diff merge using diff
patch merge using patch
content merge based on content
content based merge options:
--git-style emulate git's merge behavior
<marker> merge marker symbol
<outdir> target directory for merge result
--show-conflicts show merge conflicts during run
mode-independent options:
<files>... input files
-r, --recursive descend into subdirectories
-h, --help show help
Actions and target variables are omitted in the code.
auto copyMode = "copy mode:" % (
command("copy") | command("move"),
option("--all") % "copy all",
option("--replace") % "replace existing files",
option("-f", "--force") % "don't ask for confirmation"
);
auto compareMode = "compare mode:" % (
command("compare"),
(command("date") | command("content")),
option("-b", "--binary") % "compare files byte by byte",
option("-q", "--quick") % "use heuristics for faster comparison"
);
auto mergeAlgo = (
command("diff") % "merge using diff" |
command("patch") % "merge using patch" |
( command("content") % "merge based on content",
"content based merge options:" % (
option("--git-style") % "emulate git's merge behavior",
option("-m", "--marker") & value("marker") % "merge marker symbol"
)
)
);
auto mergeMode = "merge mode:" % (
command("merge"),
mergeAlgo,
required("-o") & value("outdir") % "target directory for merge result",
option("--show-conflicts") % "show merge conflicts during run"
);
auto firstOpt = "user interface options:" % (
option("-v", "--verbose") % "show detailed output",
option("-i", "--interactive") % "use interactive mode"
);
auto lastOpt = "mode-independent options:" % (
values("files") % "input files",
option("-r", "--recursive") % "descend into subdirectories",
option("-h", "--help") % "show help"
);
auto cli = (
firstOpt,
copyMode | compareMode | mergeMode | command("list"),
lastOpt
);
if(parse(argc, argv, cli)) {
// program logic...
} else {
auto fmt = doc_formatting{}.doc_column(31);
cout << make_man_page(cli, argv[0], fmt) << '\n';
}
You could of course write down everything as one big expression (docstrings are omitted)...:
auto cli = (
option("-v", "--verbose"),
option("-i", "--interactive"),
(
( (command("copy") | command("move")),
option("--all"), option("--replace"),
option("-f", "--force")
)
| ( command("compare"),
(command("date") | command("content")),
option("-b", "--binary"), option("-q", "--quick")
)
| ( command("merge"),
(
( command("content"),
option("--git-style"),
option("-m", "--marker") & value("marker")
)
| command("diff")
| command("patch")
),
required("-o") & value("outdir"),
option("--show-conflicts")
)
| command("list")
),
values("files"),
option("-r", "--recursive"),
option("-h", "--help")
);
...but it is probably more readable and maintainable if you break up the CLI definition into logical parts.
Note:
doc_formatting::split_alternatives(bool) //default: true
doc_formatting::alternatives_min_split_size(int) //default: 3
control whether the usage is split up into several lines if any group inside an alternative exceeds a given minimum size.
Naval Fate.
Usage:
naval_fate ship new <name>...
naval_fate ship <name> move <x> <y> [--speed= <kn>]
naval_fate ship shoot <x> <y>
naval_fate mine (set|remove) <x> <y> [--moored|--drifting]
naval_fate -h | --help
naval_fate --version
Options:
--speed= <kn> Speed in knots [default: 10].
--moored Moored (anchored) mine.
--drifting Drifting mine.
-h, --help Show this screen.
--version Show version.
This code defines the command line interface, handles the parsing result and generates the above man page snippet.
int x = 0, y = 0;
float speed = 0.0f;
bool drift = true;
vector<string> names;
enum class mode { none, help, shipnew, shipmove, shipshoot, mineset, minerem};
mode selected = mode::none;
//define command line interface
auto coordinates = ( value("x", x), value("y", y) );
auto shipnew = ( command("new").set(selected,mode::shipnew),
values("name", names) );
auto shipmove = (
value("name", names),
command("move").set(selected,mode::shipmove), coordinates,
option("--speed=") & value("kn",speed) % "Speed in knots [default: 10]");
auto shipshoot = ( command("shoot").set(selected,mode::shipshoot),
coordinates );
auto mines = (
command("mine"),
(command("set" ).set(selected,mode::mineset) |
command("remove").set(selected,mode::minerem) ),
coordinates,
(option("--moored" ).set(drift,false) % "Moored (anchored) mine." |
option("--drifting").set(drift,true) % "Drifting mine." )
);
auto navalcli = (
( command("ship"), ( shipnew | shipmove | shipshoot ) )
| mines,
| command("-h", "--help").set(selected,mode::help) % "Show this screen."
| command("--version")([]{ cout << "version 1.0\n"; }) % "Show version."
);
parse(argc, argv, navalcli);
//handle results
switch(m) {
case mode::none:
break;
case mode::help: {
auto fmt = doc_formatting{}
.first_column(2).doc_column(16)
.max_flags_per_param_in_usage(4);
cout << "Naval Fate.\n\nUsage:\n"
<< usage_lines(navalcli, "naval_fate", fmt)
<< "\n\nOptions:\n"
<< documentation(navalcli, fmt) << '\n';
}
break;
}
//...
}
If a parameter doesn't have flags, i.e. it is a value-parameter, a filter function will be used to test if it matches an argument string. The default filter is clipp::match::nonempty which will match any non-empty argument string.
If you want more control over what is matched, you can use some other predefined filters or you can write your own ones (see here).
Usage: exec [-n <times>] [-l <line>...] [-b <ratio>] [-f <term>]
int n = 1;
std::vector<int> lines;
double r = 1.0;
string term, name;
auto cli = (
option("-n", "--repeat") & integer("times", n),
option("-l", "--line") & integers("#", lines),
option("-r", "--ratio) & number("ratio", r),
option("-f", "--find") & word("term", term)
);
auto cli = (
value("x"), //non-empty string
word("x"), //alphanumeric string
number("x"), //string representing integer or floating point number
integer("x") //string representing integral number
);
Note that there are additional functions for
opt_value, opt_word, ...values, words, ...opt_values, opt_words, ...Two kinds of filters are supported right now that can be passed as first argument of value, values, opt_value or opt_values as well as argument of the constructor parameter::parameter(Filter&&)
Predicates (const string&) -> bool
which should return true if and only if an argument is an exact match.
Substring matchers (const string&) -> subrange
which in case of a match also indicate the position and length of the matched substring within a command line argument.
string s;
value( match::length{1,5}, "str", s);
//or using the parameter class directly
auto p = parameter{ match::length{1,5} }
.positional(true).required(true)
.label("str").set(s);
There are a couple of predefined filters in namespace clipp::match, but you can of course write your own ones (see here).
Here is another example that makes sure we don't catch any value starting with "-" as a filename:
auto cli = (
option("-a")
option("-f") & value(match::prefix_not("-"), "filename"),
option("-b")
);
namespace clipp {
namespace match {
//simple predicates
bool none (const string&);
bool any (const string&);
bool nonempty (const string&);
bool alphabetic (const string&);
bool alphanumeric (const string&);
//filters with settings and substring matching
class numbers {
explicit numbers(char decimalPoint = '.', char digitSeparator = ',', char exponentSeparator = 'e');
subrange operator () (const string& arg);
};
class integers {
explicit integers(char digitSeparator = ',');
subrange operator () (const string& arg);
};
class substring {
explicit substring(const string& str);
subrange operator () (const string& arg);
};
class prefix {
explicit prefix(const string& prefix);
subrange operator () (const string& arg);
};
class prefix_not {
explicit prefix_not(const string& prefix);
subrange operator () (const string& arg);
};
class length {
explicit length(size_t exact);
explicit length(size_t min, size_t max);
subrange operator () (const string& arg);
};
} }
By default, the parser tries to identify a command line argument (in that order) as
If no match was found, the parser tries the same list again without any restrictions imposed by blocking (positional) parameters, conflicting alternatives, etc. If this leads to any match, an error will be reported. This way, potential, but illegal matches can be found and, e.g., conflicting alternatives can be reported.
Consider this CLI:
auto cli = ( option("-a"), option("-f") & value("filename"), option("-b") );
If we give -f -b or -b -f -a as command line arguments, an error will be reported, since the value after -f is not optional.
This behavior is fine for most use cases.
But what if we want our program to take any string as a filename, because our filenames might also collide with flag names? We can make the filename value parameter greedy, so that the next string after -f will always be matched with highest priority as soon as -f was given:
auto cli = ( option("-a"), option("-f") & greedy(value("filename")), option("-b") );
or using operator !:
auto cli = ( option("-a"), option("-f") & !value("filename"), option("-b") );
Now, every string coming after an -f will be used as filename.
If we don't want just any kind of match accepted, but still retain a higher priority for a value parameter, we could use a value filter:
auto cli = (
( command("A"),
option("-f") & !value(match::prefix_not("-"), "filename"),
option("-b")
) |
( command("B"),
option("-x")
)
);
This way, the command line arguments A -f B will set the filename to "B" and produce no conflict error between the alternative commands A and B but A -f -b will still give an error.
Note, that there is an inherent decision problem: either we want the filename value to match no matter what, or we won't get proper error handling if someone forgets to specify a filename and gives A -f -b Also, there might be interfaces where we really want to catch something like A -f B as a command conflict.
Not only flags, but arbitrary combinations of flags and values can be made joinable. This feature is especially powerful if combined with repeatable groups. Important: in order for an argument to be matched by such expressions, no parameter requirements must be violated during the matching. Also, no partial argument matches are allowed.
Usage: counter [a|b]...
int as = 0, bs = 0;
auto cli = joinable( repeatable(
option("a").call([&]{++as;}) |
option("b").call([&]{++bs;})
) );
if(parse(argc, argv, cli))
cout << "as: " << as << "\nbs: " << bs << '\n';
else
cout << "Usage:\n" << usage_lines(cli, argv[0]) << '\n';
Valid input includes:
$ ./counter a
$ ./counter b
$ ./counter ab
$ ./counter abba
$ ./counter a b baba
$ ./counter a babba abab abbbbba b a ba a
...
Usage: numbers ([,] [<number>])...
std::vector<double> nums;
auto cli = joinable(repeatable( option(",") , opt_number("number", nums) ));
if(parse(argc, argv, cli)) {
cout << "numbers:\n";
for(auto n : nums) cout << n << '\n';
} else {
cout << "Usage:\n" << usage_lines(cli, argv[0]) << '\n';
}
Valid input includes:
$ ./numbers 1
$ ./numbers 1 2 3
$ ./numbers 1 , 2
$ ./numbers 1 , 2 , 3
$ ./numbers 1, 2, 3
$ ./numbers 1 ,2 ,3
$ ./numbers 1,2
$ ./numbers 1,2,3
$ ./numbers 1.1 , 2
$ ./numbers 1,2.3,4.5
$ ./numbers 1,2,3 4.2 5,6 2 7.1,8.23,9
Warning: Be careful with joinable and repeatable parameters! The resulting command line interface might be a lot less intuitive to use than you think. It can also be hard to get the "grammar" of complex parsing expressions right. The following definition for example, contains a subtle pitfall:
auto cli = joinable(repeatable( option(",") , number("number", nums) ));
// ^^^ non-optional
This will not match arguments like "1,". This is, because, if the repeat group is 'hit' by any of its child parameters, all non-optional parameters must also match within the current 'repeat cycle'. So, if the parser hits the "," it expects to find a number arg as well, because it is blocking (positional) and required. Only after seeing this number can it enter the next repeat cycle. Thus, the argument will not be matched, since joined matches are only valid if no error occured. Making the number optional solves the problem.
Two kinds of filters are supported right now that can be passed as first argument of value, values, opt_value or opt_values as well as argument of the constructor parameter::parameter(Filter&&):
Predicates (const string&) -> bool
which should return true if and only if an argument is an exact match.
Substring matchers (const string&) -> subrange
which in case of a match also indicate the position and length of the matched substring within a command line argument.
Usage: annotate auto | (label <character>)
auto is_char = [](const string& arg) { return arg.size() == 1 && std::isalpha(arg[0]); };
char lbl = ' ';
auto cli = ( command("auto") | ( command("label"), value(is_char, "character", lbl) ) );
Let's write a program that takes strings and lists all tag names (<tag>) contained in them:
Usage: tagnames <string>...
//custom filter
auto tag_name = [] (const string& arg) {
if(arg.size() < 3) return subrange{}; //too short
auto i = arg.find("<");
if(i == string::npos) return subrange{}; //no tag start found
auto j = arg.find(">", i+1);
if(j == string::npos) return subrange{}; //didn't find end of tag
return subrange{i,j-i+1}; //partial match {start, length}
};
std::set<string> tags;
auto cli = joinable(
values(tag_name, "string",
[&](const string& arg){ if(arg[1] != '/') tags.insert(arg);})
);
if(parse(argc, argv, cli)) {
cout << "tag names:\n";
for(const auto& t : tags) cout << t << '\n';
} else {
cout << "Usage:\n" << usage_lines(cli, "tagnames") << '\n';
}
$ ./tagnames "<cee><d><e></e></d></cee>" "<a><bo></bo></a>"
tag names:
<a>
<bo>
<cee>
<d>
<e>
Check, if no flag occurs as prefix of any other flag (identical flags will be ignored):
auto cli = ( /* command line interface definition */);
assert( cli.flags_are_prefix_free() );
Check common prefix of all flags, like for example "-" (or "/" on Windows):
auto cli = ( /* command line interface definition */);
assert( cli.common_flag_prefix() == "-" );
Each parameter can have error handler functions/lambdas/function objects for different fail cases attached to it:
if_repeated is raised each time an argument is mapped to a parameter regardless of that parameter's repeatability settingif_missing is raised if a required parameter has no argument associated with itif_conflicted is raised if two or more arguments are mapped to more than one parameter of a group of alternativesif_blocked is raised if an argument can only be mapped to a parameter that was not reachable at the time (e.g. because a positional value was expected before that parameter or the parameter was in a non-active alternative branch)Usage: send <file> -t <target>... [--http|--ftp]
string filename;
vector<string> targets;
vector<string> wrong;
bool http = true;
auto istarget = match::prefix_not("-");
auto cli = (
value("file", filename)
.if_missing([]{ cout << "You need to provide a source filename!\n"; } )
.if_repeated([](int idx){ cout << "Only one source file allowed! (index " << idx << ")\n"; } )
,
required("-t") & values(istarget, "target", targets)
.if_missing([]{ cout << "You need to provide at least one target filename!\n"; } )
.if_blocked([]{ cout << "Target names must not be given before the source file name!\n"; })
,
option("--http").set(http,true) |
option("--ftp").set(http,false) % "protocol, default is http"
.if_conflicted([]{ cout << "You can only use one protocol at a time!\n"; } )
,
any_other(wrong)
);
if(parse(argc, argv, cli) && wrong.empty()) {
cout << "OK\n";
/* ... */
} else {
for(const auto& arg : wrong) cout << "'" << arg << "' is not a valid argument\n";
cout << "Usage:" << usage_lines(cli,argv[0]) << '\n';
}
An error handler can either have an empty parameter list or take an int which is set to the command line argument index where the error occured first.
The catch-all parameter made by any_other is used to catch command line arguments that are not supported.
The value parameter target will only match command line arguments that do not begin with "-", so that wrongly spelled options cannot be parsed as target value.
auto cli = (
command("make"),
value("file") % "name of file to make",
option("-f", "--force") % "overwrite existing file"
);
//excludes argv[0]
parse(argc, argv, cli);
//if you want to include argv[0]
parse(argv, argv+argc, cli);
parse({"make", "out.txt"}, cli);
auto args = std::vector<std::string> {"make", "out.txt", "-f"};
parse(args, cli);
The parse functions return an object of parsing_result which can be used for detailed analysis and will (explicitly) convert to false if any error occured during parsing.
auto result = parse(argc, argv, cli);
auto doc_label = [](const parameter& p) {
if(!p.flags().empty()) return p.flags().front();
if(!p.label().empty()) return p.label();
return doc_string{"<?>"};
};
cout << "args -> parameter mapping:\n";
for(const auto& m : result) {
os << "#" << m.index() << " " << m.arg() << " -> ";
auto p = m.param();
if(p) {
os << doc_label(*p) << " \t";
if(m.repeat() > 0) {
os << (m.bad_repeat() ? "[bad repeat " : "[repeat ")
<< m.repeat() << "]";
}
if(m.blocked()) os << " [blocked]";
if(m.conflict()) os << " [conflict]";
os << '\n';
}
else {
os << " [unmapped]\n";
}
}
cout << "missing parameters:\n";
for(const auto& m : result.missing()) {
auto p = m.param();
if(p) {
os << doc_label(*p) << " \t";
os << " [missing after " << m.after_index() << "]\n";
}
}
Generate usage lines and documentation from parameters:
auto cli = ( /* command line interface definition */ );
//used default formatting
cout << "Usage:\n" << usage_lines(cli, "progname")
<< "\nOptions:\n" << documentation(cli) << '\n';
... or generate an entire man page in one go:
auto cli = ( /* command line interface definition */ );
cout << make_man_page(cli, "progname")
.prepend_section("DESCRIPTION", " The best thing since sliced bread.")
.append_section("LICENSE", " GPL3");
DESCRIPTION
Builds a database of words from text files.
SYNOPSIS
worddb help
worddb build (new|add) <file>
worddb query -i <infile> [-p]
worddb info space
worddb info statistics (words|chars)
worddb remove (any|all) <regex>
worddb modify [-c] [-u] [-m <size>]
OPTIONS
build commands
new make new database
add append to existing database
query settings
<infile> input file
-p, --pretty-print human friendly output
database info modes
space detailed memory occupation analysis
statistics analysis
words word frequency table
chars character frequency table
remove mode
<regex> regular expression filter
modification operations
-c, --compress compress database in-memory
-u, --unique keep only unique entries
-m, --memlimit max. size in RAM
LICENSE
GPL3
The full code:
auto cli = (
command("help") |
( command("build"),
"build commands" %
( command("new") % "make new database"
| command("add") % "append to existing database"
),
value("file")
) |
( command("query"),
"query settings" %
( required("-i", "--input") & value("infile") % "input file",
option("-p", "--pretty-print") % "human friendly output")
) |
( command("info"),
"database info modes" % (
command("space") % "detailed memory occupation analysis" |
(
command("statistics"),
"statistics analysis" % (
command("words") % "word frequency table" |
command("chars") % "character frequency table"
)
)
)
) |
"remove mode" % (
command("remove"),
"modify" % ( command("any") | command("all") ),
value("regex") % "regular expression filter"
) |
( command("modify"),
"modification operations" % (
option("-c", "--compress") % "compress database in-memory",
option("-u", "--unique") % "keep only unique entries",
option("-m", "--memlimit") % "max. size in RAM" & value("size")
)
)
);
auto fmt = doc_formatting{} .first_column(4) .doc_column(28) .last_column(80);
cout << make_man_page(cli, "worddb", fmt)
.prepend_section("DESCRIPTION", " Builds a database of words from text files.")
.append_section("LICENSE", " GPL3") << '\n';
//all formatting options (with their default values)
auto fmt = doc_formatting{}
.first_column(8) //left border column for text body
.doc_column(20) //column where parameter docstring starts
.last_column(100) //right border column for text body
.indent_size(4) //indent of documentation lines for children of a documented group
.line_spacing(0) //number of empty lines after single documentation lines
.paragraph_spacing(1) //number of empty lines before and after paragraphs
.flag_separator(", ") //between flags of the same parameter
.param_separator(" ") //between parameters
.group_separator(" ") //between groups (in usage)
.alternative_param_separator("|") //between alternative flags
.alternative_group_separator(" | ") //between alternative groups
.surround_group("(", ")") //surround groups with these
.surround_alternatives("(", ")") //surround group of alternatives with these
.surround_alternative_flags("", "") //surround alternative flags with these
.surround_joinable("(", ")") //surround group of joinable flags with these
.surround_optional("[", "]") //surround optional parameters with these
.surround_repeat("", "...") //surround repeatable parameters with these
.surround_value("<", ">") //surround values with these
.empty_label("") //used if parameter has no flags and no label
.max_flags_per_param_in_usage(1) //max. # of flags per parameter in usage
.max_flags_per_param_in_doc(32) //max. # of flags per parameter in detailed documentation
.split_alternatives(true) //split usage into several lines for large alternatives
.alternatives_min_split_size(3) //min. # of parameters for separate usage line
.merge_alternative_flags_with_common_prefix(false) //-ab(cdxy|xy) instead of -abcdxy|-abxy
.merge_joinable_flags_with_common_prefix(true) //-abc instead of -a -b -c
.ignore_newline_chars(false) //ignore '\n' in docstrings
;
cout << "Usage:\n" << usage_lines(cli, "progname", fmt)
<< "\nOptions:\n" << documentation(cli, fmt) << '\n';
//or generate entire man page in one go
cout << make_man_page(cli, "progname", fmt)
.prepend_section("DESCRIPTION", "This program lets you format text.")
.append_section("LICENSE", "GPLv3");
The documentation generator class documentation can also take an additional third constructor argument that allows to filter parameters according to their properties.
int main(int argc, char* argv[]) {
auto cli = (
value("input file"),
option("-r", "--recursive").set(rec).doc("convert files recursively"),
option("-o") & value("output format", fmt),
option("-utf16").set(utf16).doc("use UTF-16 encoding")
);
auto fmt = doc_formatting{}.doc_column(28);
auto filter = param_filter{}.prefix("--");
cout << "Usage:\n" << usage_lines(cli, argv[0]) << "\n\n"
<< "Parameters:\n" << documentation(cli, fmt, filter) << '\n';}
Which results in:
Usage:
convert <input file> [-r] [-o <output format>] [-utf16]
Parameters:
-r, --recursive convert files recursively
Any function/lambda that maps a parameter to a bool can be used as filter predicate. CLIPP also comes with a default parameter filter class:
//all param_filter options (with their default values)
auto filter = param_filter{}
.prefix("") //only parameters with given prefix
.required(tri::either) //required parameters
.blocking(tri::either) //blocking/positional parameters
.repeatable(tri::either) //repeatable parameters
.has_doc(tri::yes) //parameters with/without docstrings
;
which uses a dedicated tristate type:
namespace clipp {
enum class tri { no, yes, either };
}
Well, I didn't find a library that makes building simple command line interfaces simple, yet can also be used to build complex CLIs. I really don't want to write 20 lines of boilerplate just to have 3 simple command line options. I also don't want to drag along monstrosities like boost or Qt for that. Over time, clipp evolved into a domain specific language (in pure C++) that I hope can at least somewhat approach the readability of docopt but can leverage the benefits (toolability, etc.) of C++'s type system.
I like the basic idea, but I don't like redundancy in code, especially if it involves repeating string literals. Docopt generates a command line argument parser from a "man page docstring". After parsing, you have to query a dictionary to get values or check for option presence. That means you either have to mention the same flag names twice (in the docstring and in the query) or you have to use string variables which makes the docstring hard to read and kind of defeats the purpose of docopt. Furthermore, the code tends to be littered with string-to-whatever conversions.
I also wanted the ability to keep everything related to one option/command/value together in the code which I found very useful for programs with lots of command line options. Docopt doesn't let you do that since the interface definition and the code performing any actions is always separated (unless you give up on the "beautiful doc page" idea at the heart of docopt and build your input string to the parser generator piece-by-piece).
I would be delighted to hear from anyone who uses clipp in their project(s). If you find bugs or design flaws or want to suggest improvements please open an issue or submit a pull request.
clipp is still very young, so I probably won't add new features any time soon and rather:
*Note that all licence references and agreements mentioned in the clipp README section above
are relevant to that project's source code only.
Do not miss the trending, libraries, news and articles with our weekly report.