args

所属分类:虚拟/增强现实-VR/AR
开发工具:C++
文件大小:205KB
下载次数:0
上传日期:2023-03-14 04:26:59
上 传 者sh-1993
说明:  一个简单的仅头的C++参数解析器库。被认为是灵活和强大的,并试图兼容...
(A simple header-only C++ argument parser library. Supposed to be flexible and powerful, and attempts to be compatible with the functionality of the Python standard argparse library (though not necessarily the API).)

文件列表:
.buckconfig (162, 2023-03-14)
.tipi (0, 2023-03-14)
.tipi\deps (2, 2023-03-14)
.tipi\opts (0, 2023-03-14)
.travis.yml (5545, 2023-03-14)
.ycm_extra_conf.py (5742, 2023-03-14)
BUCK (338, 2023-03-14)
CHANGELOG (889, 2023-03-14)
CMakeLists.txt (5240, 2023-03-14)
CONTRIBUTING.md (417, 2023-03-14)
Doxyfile (105276, 2023-03-14)
LICENSE (1105, 2023-03-14)
Makefile (1149, 2023-03-14)
appveyor.yml (327, 2023-03-14)
args.hxx (153159, 2023-03-14)
catch.hpp (657891, 2023-03-14)
conanfile.py (419, 2023-03-14)
examples (0, 2023-03-14)
examples\.tipi (0, 2023-03-14)
examples\.tipi\deps (40, 2023-03-14)
examples\BUCK (217, 2023-03-14)
examples\CMakeLists.txt (314, 2023-03-14)
examples\bash_completion.sh (329, 2023-03-14)
examples\completion.cxx (790, 2023-03-14)
examples\gitlike.cxx (5013, 2023-03-14)
meson.build (948, 2023-03-14)
meson_options.txt (169, 2023-03-14)
packaging (0, 2023-03-14)
packaging\pkgconfig.pc.in (186, 2023-03-14)
test.cxx (61067, 2023-03-14)
test (0, 2023-03-14)
test\BUCK (372, 2023-03-14)
test\multiple_inclusion_1.cxx (95, 2023-03-14)
test\multiple_inclusion_2.cxx (46, 2023-03-14)
test\windows_h.cxx (811, 2023-03-14)
... ...

# args **This library is considered feature-complete by its creator. It will still receive bug fixes, and good pull requests will be accepted, but no new major functionality or API changes will be added to this codebase.** [![Cpp Standard](https://img.shields.io/badge/C%2B%2B-11-blue.svg)](https://en.wikipedia.org/wiki/C%2B%2B11) [![Travis status](https://travis-ci.org/Taywee/args.svg?branch=master)](https://travis-ci.org/Taywee/args) [![AppVeyor status](https://ci.appveyor.com/api/projects/status/nlnlmpttdjlndyc2?svg=true)](https://ci.appveyor.com/project/Taywee/args) [![Coverage Status](https://coveralls.io/repos/github/Taywee/args/badge.svg?branch=master)](https://coveralls.io/github/Taywee/args?branch=master) [![Read the Docs](https://img.shields.io/readthedocs/pip.svg)](https://taywee.github.io/args) A simple, small, flexible, single-header C++11 argument parsing library. This is designed to appear somewhat similar to Python's argparse, but in C++, with static type checking, and hopefully a lot faster (also allowing fully nestable group logic, where Python's argparse does not). UTF-8 support is limited at best. No normalization is performed, so non-ascii characters are very best kept out of flags, and combined glyphs are probably going to mess up help output if you use them. Most UTF-8 necessary for internationalization should work for most cases, though heavily combinatory UTF alphabets may wreak havoc. This program is MIT-licensed, so you can use the header as-is with no restrictions. I'd appreciate attribution in a README, Man page, or something if you are feeling generous, but all that's required is that you don't remove the license and my name from the header of the args.hxx file in source redistributions (ie. don't pretend that you wrote it). I do welcome additions and updates wherever you feel like contributing code. The API documentation can be found at https://taywee.github.io/args The code can be downloaded at https://github.com/Taywee/args There are also somewhat extensive examples below. You can find the complete test cases at https://github.com/Taywee/args/blob/master/test.cxx, which should very well describe the usage, as it's built to push the boundaries. # What does it do? It: * Lets you handle flags, flag+value, and positional arguments simply and elegantly, with the full help of static typechecking. * Allows you to use your own types in a pretty simple way. * Lets you use count flags, and lists of all argument-accepting types. * Allows full validation of groups of required arguments, though output isn't pretty when something fails group validation. User validation functions are accepted. Groups are fully nestable. * Generates pretty help for you, with some good tweakable parameters. * Lets you customize all prefixes and most separators, allowing you to create an infinite number of different argument syntaxes. * Lets you parse, by default, any type that has a stream extractor operator for it. If this doesn't work for your uses, you can supply a function and parse the string yourself if you like. * Lets you decide not to allow separate-argument value flags or joined ones (like disallowing `--foo bar`, requiring `--foo=bar`, or the inverse, or the same for short options). * Allows you to create subparsers, to reuse arguments for multiple commands and to refactor your command's logic to a function or lambda. * Allows one value flag to take a specific number of values (like `--foo first second`, where --foo slurps both arguments). * Allows you to have value flags only optionally accept values. * Provides autocompletion for bash. # What does it not do? There are tons of things this library does not do! ## It will not ever: * Allow you to intermix multiple different prefix types (eg. `++foo` and `--foo` in the same parser), though shortopt and longopt prefixes can be different. * Allow you to make flags sensitive to order (like gnu find), or make them sensitive to relative ordering with positionals. The only orderings that are order-sensitive are: * Positionals relative to one-another * List positionals or flag values to each of their own respective items * Allow you to use a positional list before any other positionals (the last argument list will slurp all subsequent positional arguments). The logic for allowing this would be a lot more code than I'd like, and would make static checking much more difficult, requiring us to sort std::string arguments and pair them to positional arguments before assigning them, rather than what we currently do, which is assigning them as we go for better simplicity and speed. The library doesn't stop you from trying, but the first positional list will slurp in all following positionals # How do I install it? ```shell sudo make install ``` Or, to install it somewhere special (default is `/usr/local`): ```shell sudo make install DESTDIR=/opt/mydir ``` You can also copy the file into your source tree, if you want to be absolutely sure you keep a stable API between projects. If you prefer other installation methods, many standard ones are available and included, including CMake, conan, buck, and meson. An example CMake file using args is included in the examples directory. ## I also want man pages. ```shell make doc/man sudo make installman ``` This requires Doxygen ## I want the doxygen documentation locally ```shell doxygen Doxyfile ``` Your docs are now in doc/html ## How to depend on it using tipi.build? Simply add the following entry to your `.tipi/deps` file ```json { "taywee/args": { "@": "***.1" } } ``` You can optionally remove the `@` section to *target HEAD* easily. # How do I use it? Create an ArgumentParser, modify its attributes to fit your needs, add arguments through regular argument objects (or create your own), and match them with an args::Matcher object (check its construction details in the doxygen documentation. Then you can either call it with args::ArgumentParser::ParseCLI for the full command line with program name, or args::ArgumentParser::ParseArgs with just the arguments to be parsed. The argument and group variables can then be interpreted as a boolean to see if they've been matched. All variables can be pulled (including the boolean match status for regular args::Flag variables) with args::get. # Group validation is weird. How do I get more helpful output for failed validation? This is unfortunately not possible, given the power of the groups available. For instance, if you have a group validation that works like `(A && B) || (C && (D XOR E))`, how is this library going to be able to determine what exactly when wrong when it fails? It only knows that the entire expression evaluated false, not specifically what the user did wrong (and this is doubled over by the fact that validation operations are ordinary functions without any special meaning to the library). As you are the only one who understands the logic of your program, if you want useful group messages, you have to catch the ValidationError as a special case and check your own groups and spit out messages accordingly. # Is it developed with regression tests? Yes. tests.cxx in the git repository has a set of standard tests (which are still relatively small in number, but I would welcome some expansion here), and thanks to Travis CI and AppVeyor, these tests run with every single push: ```shell % make runtests g++ test.cxx -o test.o -I. -std=c++11 -O2 -c -MMD g++ -o test test.o -std=c++11 -O2 ./test =============================================================================== All tests passed (74 assertions in 15 test cases) % ``` The testing library used is [Catch](https://github.com/philsquared/Catch). # Examples All the code examples here will be complete code examples, with some output. ## Simple example: ```cpp #include #include int main(int argc, char **argv) { args::ArgumentParser parser("This is a test program.", "This goes after the options."); args::HelpFlag help(parser, "help", "Display this help menu", {'h', "help"}); args::CompletionFlag completion(parser, {"complete"}); try { parser.ParseCLI(argc, argv); } catch (const args::Completion& e) { std::cout << e.what(); return 0; } catch (const args::Help&) { std::cout << parser; return 0; } catch (const args::ParseError& e) { std::cerr << e.what() << std::endl; std::cerr << parser; return 1; } return 0; } ``` ```shell % ./test % ./test -h ./test {OPTIONS} This is a test program. OPTIONS: -h, --help Display this help menu This goes after the options. % ``` ## Boolean flags, special group types, different matcher construction: ```cpp #include #include int main(int argc, char **argv) { args::ArgumentParser parser("This is a test program.", "This goes after the options."); args::Group group(parser, "This group is all exclusive:", args::Group::Validators::Xor); args::Flag foo(group, "foo", "The foo flag", {'f', "foo"}); args::Flag bar(group, "bar", "The bar flag", {'b'}); args::Flag baz(group, "baz", "The baz flag", {"baz"}); try { parser.ParseCLI(argc, argv); } catch (args::Help) { std::cout << parser; return 0; } catch (args::ParseError e) { std::cerr << e.what() << std::endl; std::cerr << parser; return 1; } catch (args::ValidationError e) { std::cerr << e.what() << std::endl; std::cerr << parser; return 1; } if (foo) { std::cout << "foo" << std::endl; } if (bar) { std::cout << "bar" << std::endl; } if (baz) { std::cout << "baz" << std::endl; } return 0; } ``` ```shell % ./test Group validation failed somewhere! ./test {OPTIONS} This is a test program. OPTIONS: This group is all exclusive: -f, --foo The foo flag -b The bar flag --baz The baz flag This goes after the options. % ./test -f foo % ./test --foo foo % ./test --foo -f foo % ./test -b bar % ./test --baz baz % ./test --baz -f Group validation failed somewhere! ./test {OPTIONS} This is a test program. ... % ./test --baz -fb Group validation failed somewhere! ./test {OPTIONS} ... % ``` ## Argument flags, Positional arguments, lists ```cpp #include #include int main(int argc, char **argv) { args::ArgumentParser parser("This is a test program.", "This goes after the options."); args::HelpFlag help(parser, "help", "Display this help menu", {'h', "help"}); args::ValueFlag integer(parser, "integer", "The integer flag", {'i'}); args::ValueFlagList characters(parser, "characters", "The character flag", {'c'}); args::Positional foo(parser, "foo", "The foo position"); args::PositionalList numbers(parser, "numbers", "The numbers position list"); try { parser.ParseCLI(argc, argv); } catch (args::Help) { std::cout << parser; return 0; } catch (args::ParseError e) { std::cerr << e.what() << std::endl; std::cerr << parser; return 1; } catch (args::ValidationError e) { std::cerr << e.what() << std::endl; std::cerr << parser; return 1; } if (integer) { std::cout << "i: " << args::get(integer) << std::endl; } if (characters) { for (const auto ch: args::get(characters)) { std::cout << "c: " << ch << std::endl; } } if (foo) { std::cout << "f: " << args::get(foo) << std::endl; } if (numbers) { for (const auto nm: args::get(numbers)) { std::cout << "n: " << nm << std::endl; } } return 0; } ``` ```shell % ./test -h ./test {OPTIONS} [foo] [numbers...] This is a test program. OPTIONS: -h, --help Display this help menu -i integer The integer flag -c characters The character flag foo The foo position numbers The numbers position list "--" can be used to terminate flag options and force all following arguments to be treated as positional options This goes after the options. % ./test -i 5 i: 5 % ./test -i 5.2 Argument 'integer' received invalid value type '5.2' ./test {OPTIONS} [foo] [numbers...] % ./test -c 1 -c 2 -c 3 c: 1 c: 2 c: 3 % % ./test 1 2 3 4 5 6 7 8 9 f: 1 n: 2 n: 3 n: 4 n: 5 n: 6 n: 7 n: 8 n: 9 % ./test 1 2 3 4 5 6 7 8 9 a Argument 'numbers' received invalid value type 'a' ./test {OPTIONS} [foo] [numbers...] This is a test program. ... ``` ## Commands ```cpp #include #include int main(int argc, char **argv) { args::ArgumentParser p("git-like parser"); args::Group commands(p, "commands"); args::Command add(commands, "add", "add file contents to the index"); args::Command commit(commands, "commit", "record changes to the repository"); args::Group arguments(p, "arguments", args::Group::Validators::DontCare, args::Options::Global); args::ValueFlag gitdir(arguments, "path", "", {"git-dir"}); args::HelpFlag h(arguments, "help", "help", {'h', "help"}); args::PositionalList pathsList(arguments, "paths", "files to commit"); try { p.ParseCLI(argc, argv); if (add) { std::cout << "Add"; } else { std::cout << "Commit"; } for (auto &&path : pathsList) { std::cout << ' ' << path; } std::cout << std::endl; } catch (args::Help) { std::cout << p; } catch (args::Error& e) { std::cerr << e.what() << std::endl << p; return 1; } return 0; } ``` ```shell % ./test -h ./test COMMAND [paths...] {OPTIONS} git-like parser OPTIONS: commands add add file contents to the index commit record changes to the repository arguments --git-dir=[path] -h, --help help paths... files "--" can be used to terminate flag options and force all following arguments to be treated as positional options % ./test add 1 2 Add 1 2 ``` ## Refactoring commands ```cpp #include #include "args.hxx" args::Group arguments("arguments"); args::ValueFlag gitdir(arguments, "path", "", {"git-dir"}); args::HelpFlag h(arguments, "help", "help", {'h', "help"}); args::PositionalList pathsList(arguments, "paths", "files to commit"); void CommitCommand(args::Subparser &parser) { args::ValueFlag message(parser, "MESSAGE", "commit message", {'m'}); parser.Parse(); std::cout << "Commit"; for (auto &&path : pathsList) { std::cout << ' ' << path; } std::cout << std::endl; if (message) { std::cout << "message: " << args::get(message) << std::endl; } } int main(int argc, const char **argv) { args::ArgumentParser p("git-like parser"); args::Group commands(p, "commands"); args::Command add(commands, "add", "add file contents to the index", [&](args::Subparser &parser) { parser.Parse(); std::cout << "Add"; for (auto &&path : pathsList) { std::cout << ' ' << path; } std::cout << std::endl; }); args::Command commit(commands, "commit", "record changes to the repository", &CommitCommand); args::GlobalOptions globals(p, arguments); try { p.ParseCLI(argc, argv); } catch (args::Help) { std::cout << p; } catch (args::Error& e) { std::cerr << e.what() << std::endl << p; return 1; } return 0; } ``` ```shell % ./test -h ./test COMMAND [paths...] {OPTIONS} git-like parser OPTIONS: commands add add file contents to the index commit record changes to the repository arguments --git-dir=[path] -h, --help help paths... files "--" can be used to terminate flag options and force all following arguments to be treated as positional options % ./test add 1 2 Add 1 2 % ./test commit -m "my commit message" 1 2 Commit 1 2 message: my commit message ``` # Custom type parsers (here we use std::tuple) ```cpp #include #include std::istream& operator>>(std::istream& is, std::tuple& ints) { is >> std::get<0>(ints); is.get(); is >> std::get<1>(ints); return is; } #include struct DoublesReader { void operator()(const std::string &name, const std::string &value, std::tuple &destination) { size_t commapos = 0; std::get<0>(destination) = std::stod(value, &commapos); std::get<1>(destination) = std::stod(std::string(value, commapos + 1)); } }; int main(int argc, char **argv) { args::ArgumentParser parser("This is a test program."); args::Positional> ints(parser, "INTS", "This takes a pair of integers."); args::Positional, DoublesReader> doubles(parser, "DOUBLES", "This takes a pair of doubles."); try { parser.ParseCLI(argc, argv); } catch (args::Help) { std::cout << parser; return 0; } catch (args::ParseError e) { std::cerr << e.what() << std::endl; std::cerr << parser; return 1; } if (ints) { std::cout << "ints found: " << std::get<0>(args::get(ints)) << " and " << std::get<1>(args::get(ints)) << std::endl; } if (doubles) { std::cout << "doubles found: " << std::get<0>(args::get(doubles)) << " and " << std::get<1>(args::get(doubles)) << std::endl; } return 0; } ``` ```shell % ./test -h Argument could not be matched: 'h' ./test [INTS] [DOUBLES] This is a test program. OPTIONS: INTS This takes a pair of integers. DOUBLES This takes a pair of doubles. % ./test 5 ints found: 5 and 0 % ./test 5,8 ints found: 5 and 8 % ./test 5,8 2.4,8 ints found: 5 and 8 doubles found: 2.4 and 8 % ./test 5,8 2.4, terminate called after throwing an instance of 'std::invalid_argument' what(): stod zsh: abort ./test 5,8 2.4, % ./test 5,8 2.4 terminate called after throwing an instance of 'std::out_of_range' what(): basic_string::basic_string: __pos (which is 4) > this->size() (which is 3) zsh: abort ./test 5,8 2.4 % ./test 5,8 2.4-7 ints found: 5 and 8 doubles found: 2.4 and 7 % ./test 5,8 2.4,-7 ints found: 5 and 8 doubles found: 2.4 and -7 ``` As you can see, with your own types, validation can get a little weird. Make sure to check and throw a parsing error (or whatever error you want to catch) if you can't fully deduce your type. The bui ... ...

近期下载者

相关文件


收藏者