summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorBent Bisballe Nyeng <deva@aasimon.org>2019-06-04 10:49:14 +0200
committerBent Bisballe Nyeng <xbbn@mjolner.dk>2019-06-04 10:49:14 +0200
commite43a2c6cbff82a0635fb102146f471f872b43be8 (patch)
tree5c4011705bd044767f9d23d5aad005a8d8240a7d
parentaaf8823da055a804da78e635900aa8d52741c59f (diff)
Add return value to option parsing, to make it possible to bail out if an argument is deemed invalid during parsing.
-rw-r--r--example.cpp8
-rw-r--r--getoptpp.hpp20
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<void()>;
+using Handle = std::function<int()>;
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<std::string> arguments() const { return args; }