aboutsummaryrefslogtreecommitdiffstats
path: root/nihil.cli/command_map.cc
blob: c656c62170bd906ad75d78afcc17aa6b3b6df513 (plain) (blame)
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
/*
 * This source code is released into the public domain.
 */

module;

#include <cstdio>
#include <functional>
#include <iostream>
#include <map>
#include <ranges>
#include <string>
#include <utility>

#include <unistd.h>

module nihil.cli;

/*
 * command_map represents a hierarchical list of commands.  At each level,
 * a command is mapped to a handler, which can either be a function, in
 * which case we execute the function, or another command_map, in which
 * case we invoke the new map
 */

namespace nihil {

/*
 * The string tree we store our commands in.  This is sort of like a very
 * basic hierarchical std::map.  Keys are provided as a range of values,
 * typically from argv.
 */

struct command_tree_node final {
	command_tree_node()
		: _this_word("")
	{
	}

	command_tree_node(std::string_view this_word)
		: _this_word(this_word)
	{
	}

	command_tree_node(std::string_view this_word,
			  command value)
		: _this_word(this_word)
		, _value(std::move(value))
	{
	}

	/*
	 * Return a child node, or NULL if the child doesn't exist.
	 */
	auto get_child(this command_tree_node const &self,
		       std::string_view child)
		-> command_tree_node const *
	{
		if (auto it = self.children.find(std::string(child));
		    it != self.children.end())
			return &it->second;

		return nullptr;
	}

	auto get_child(this command_tree_node &self,
		       std::string_view child)
		-> command_tree_node *
	{
		if (auto it = self.children.find(std::string(child));
		    it != self.children.end())
			return &it->second;

		return nullptr;
	}

	/*
	 * Return a child node if it exists, or insert a new empty node.
	 */
	auto get_or_create_child(this command_tree_node &self,
				 std::string_view child)
		-> command_tree_node *
	{
		if (auto ptr = self.get_child(child); ptr != nullptr)
			return ptr;

		auto [it, ok] = self.children.emplace(
					child, command_tree_node(child));
		return &it->second;
	}

	/*
	 * Return this node's value.
	 */
	auto value(this command_tree_node const &self)
		-> std::optional<command> const &
	{
		return self._value;
	}

	/*
	 * Set this node's value.
	 */
	auto value(this command_tree_node &self, command value) -> void
	{
		self._value = std::move(value);
	}

	/*
	 * Print this node's children in a form useful to humans.
	 */
	auto print_commands(this command_tree_node const &self,
			    std::string_view prefix) -> void
	{
		for (auto &&[name, node] : self.children) {
			std::print("  {} {}\n", prefix, name);
		}
	}

private:
	std::string _this_word;
	std::optional<command> _value;
	std::unordered_map<std::string, command_tree_node> children;
};

struct command_tree {
	/*
	 * Add a node to the tree.  Returns false if the node already exists.
	 */
	auto insert(this command_tree &self,
		    std::ranges::range auto &&path,
		    command value)
		-> bool
	{
		auto *this_node = &self._root_node;

		// Find the node for this key.
		for (auto &&next : path) {
			auto this_word = std::string_view(next);
			this_node = this_node->get_or_create_child(this_word);
		}

		if (this_node->value()) {
			// The value already exists.
			return false;
		}

		// Set the new value.
		this_node->value(std::move(value));
		return true;
	}

	/*
	 * Find a node in the tree.  Unlike insert(), iteration stops when
	 * we find any node with a value.
	 */
	auto find(this command_tree const &self, int &argc, char **&argv)
		-> std::optional<command>
	{
		auto *this_node = &self._root_node;

		// Assume the caller already stripped the program name from
		// argv.  This is usually the case since they would have
		// called getopt().

		// Store the command bits we got so far, so we can print them
		// in the usage error if needed.
		auto path = std::string();

		while (argv[0] != nullptr) {
			auto next = std::string_view(argv[0]);

			auto *next_node = this_node->get_child(next);

			if (next_node == nullptr) {
				// The node doesn't exist, so this command is
				// not valid.  Print a list of valid commands.
				std::print(std::cerr,
					   "{}: unknown command: {} {}\n",
					   ::getprogname(), path, next);
				std::print(std::cerr,
					   "{}: expected one of:\n",
					   ::getprogname());

				this_node->print_commands(path);
				return {};
			}

			this_node = next_node;

			if (this_node->value())
				// This node has a value, so return it.
				return {this_node->value()};

			if (!path.empty())
				path += ' ';
			path += next;
			--argc;
			++argv;
		}

		// We didn't find a value, so the key was incomplete.
		std::print(std::cerr, "{}: {} command; expected:\n",
			   ::getprogname(),
			   path.empty() ? "missing" : "incomplete");
		this_node->print_commands(path);

		return {};
	}

private:
	command_tree_node _root_node;
};

/*
 * The global command map.
 */
auto get_commands() -> command_tree & {
	static auto commands = command_tree();
	return commands;
}

auto register_command(std::string_view path, command *cmd) noexcept -> void
try {
	auto &commands = get_commands();
	if (commands.insert(path | std::views::split(' '), *cmd) == false) {
		std::printf("command registration failed\n");
		std::abort();
	}
} catch (...) {
	std::printf("command registration failed\n");
	std::abort();
}

auto dispatch_command(int argc, char **argv) -> int
{
	auto &commands = get_commands();

	// The caller should have stripped argv[0] already.  find() will
	// strip all the remaining elements except the last, which means
	// argv[0] will be set to something reasonable for the next call
	// to getopt().

	auto node = commands.find(argc, argv);

	if (!node)
		// find() already printed the error message
		return 1;

	// Reset getopt here for the command to use.
	optreset = 1;
	optind = 1;

	// Calling setprogname() makes error messages more relevant.
	auto cprogname = std::format("{} {}", ::getprogname(),
				     node->path());
	::setprogname(cprogname.c_str());

	return node->invoke(argc, argv);
}

void print_usage(std::string_view)
{
//	get_root_node().print_usage(std::string(prefix));
}

} // namespace nihil