From e43a2c6cbff82a0635fb102146f471f872b43be8 Mon Sep 17 00:00:00 2001 From: Bent Bisballe Nyeng Date: Tue, 4 Jun 2019 10:49:14 +0200 Subject: Add return value to option parsing, to make it possible to bail out if an argument is deemed invalid during parsing. --- example.cpp | 8 ++++++++ getoptpp.hpp | 20 +++++++++++++------- 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/example.cpp b/example.cpp index 73988aa..e273c2f 100644 --- a/example.cpp +++ b/example.cpp @@ -8,27 +8,35 @@ int main(int argc, char* argv[]) { dg::Options opt; opt.add("verbose", no_argument, &verbose_flag, 1, [&]() { std::cout << "verbose: " << verbose_flag << "\n"; + return 0; }); opt.add("brief", no_argument, &verbose_flag, 0, [&]() { std::cout << "brief: " << verbose_flag << "\n"; + return 0; }); opt.add("add", no_argument, 'a', [&]() { std::cout << "add\n"; + return 0; }); opt.add("append", no_argument, 'b', [&]() { std::cout << "append\n"; + return 0; }); opt.add("delete", required_argument, 'd', [&]() { std::cout << "delete: " << optarg << "\n"; + return 0; }); opt.add("create", required_argument, 'c', [&]() { std::cout << "create: " << optarg << "\n"; + return 0; }); opt.add("file", required_argument, 'f', [&]() { std::cout << "file: " << optarg << "\n"; + return 0; }); opt.add("help", no_argument, '?', [&]() { std::cout << "usage stuff\n"; + return 0; }); opt.process(argc, argv); diff --git a/getoptpp.hpp b/getoptpp.hpp index 09323a8..8788dde 100644 --- a/getoptpp.hpp +++ b/getoptpp.hpp @@ -9,7 +9,7 @@ namespace dg { -using Handle = std::function; +using Handle = std::function; class Options { public: @@ -40,7 +40,8 @@ class Options { handles[index] = handle; } - bool process(int argc, char* argv[]) { + int process(int argc, char* argv[]) { + int ret = 0; std::string shortopts; for (auto const & option: options) { if (option.flag != nullptr) { @@ -71,17 +72,22 @@ class Options { if (key == -1) { break; } else if (key == '?') { - return false; + return 1; } else if (key == ':') { - return false; + return 1; } else if (key == 0) { // call flag's handle - handles.at(index)(); + ret = handles.at(index)(); } else { // call option's handle - handles.at(key)(); + ret = handles.at(key)(); } } + + if(ret) { + return ret; + } + for (int i = optind; i < argc; ++i) { args.push_back(argv[i]); } @@ -89,7 +95,7 @@ class Options { // remove terminating option options.pop_back(); assert(options.size() == handles.size()); - return true; + return 0; } const std::vector arguments() const { return args; } -- cgit v1.2.3