summaryrefslogtreecommitdiff
path: root/getoptpp.hpp
blob: cd7469b4e68c3656cd99f767670a2173f5592af1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#pragma once
#include <cassert>
#include <functional>
#include <vector>
#include <unordered_map>
#include <getopt.h>

namespace dg {

using Handle = std::function<void()>;

class Options {
	public:
		Options();
		
		void add(std::string const & name, int has_arg, int val, Handle handle);
		void add(std::string const & name, int has_arg, int* flag, int val, Handle handle);
		
		void process(int argc, char* argv[]);
		
	private:
		std::size_t num_flags;
		std::vector<option> options;
		std::unordered_map<int, Handle> handles;
};

Options::Options()
	: num_flags{}
	, options{}
	, handles{} {
}

void Options::add(std::string const & name, int has_arg, int val, Handle handle) {
	add(name, has_arg, nullptr, val, handle);
}

void Options::add(std::string const & name, int has_arg, int* flag, int val, Handle handle) {
	options.emplace_back();
	auto& option = options.back();
	option.name = name.c_str();
	option.has_arg = has_arg;
	option.flag = flag;
	option.val = val;
	
	int index = val;
	if (flag != nullptr) {
		index = num_flags++;
	}
	handles[index] = handle;
}

void Options::process(int argc, char* argv[]) {
	std::string shortopts;
	for (auto const & option: options) {
		if (option.flag != nullptr) {
			continue;
		}
		shortopts += static_cast<char>(option.val);
		
		switch (option.has_arg) {
			case no_argument:
				break;
			case required_argument:
				shortopts += ":";
				break;
			case optional_argument:
				shortopts += "::";
				break;
		}
	}
	
	// add termination option
	options.push_back({0, 0, 0, 0});
	
	// handle arguments
	while (true) {
		int index{0};
		int key = getopt_long(argc, argv, shortopts.c_str(), options.data(), &index);
		
		if (key == -1) {
			break;
		} else if (key == 0) {
			// call flag's handle
			handles.at(index)();
		} else {
			// call option's handle
			handles.at(key)();
		}
	}
	
	// remove terminating option
	options.pop_back();
	assert(options.size() == handles.size());
}

}