aboutsummaryrefslogtreecommitdiffstats
path: root/liblfjail/command_map.hh
diff options
context:
space:
mode:
authorLexi Winter <lexi@hemlock.eden.le-fay.org>2025-06-13 10:31:25 +0100
committerLexi Winter <lexi@hemlock.eden.le-fay.org>2025-06-13 10:31:25 +0100
commit722c03e547a1370857878ea7db27be6111aae8b1 (patch)
tree22544bc828275516f6068c9b048cc829672653bf /liblfjail/command_map.hh
parent1202c450ce3bea3a2fa0c8ba369dcc40c2f8626b (diff)
downloadlfjail-722c03e547a1370857878ea7db27be6111aae8b1.tar.gz
lfjail-722c03e547a1370857878ea7db27be6111aae8b1.tar.bz2
move utilities to liblfjail
Diffstat (limited to 'liblfjail/command_map.hh')
-rw-r--r--liblfjail/command_map.hh63
1 files changed, 63 insertions, 0 deletions
diff --git a/liblfjail/command_map.hh b/liblfjail/command_map.hh
new file mode 100644
index 0000000..b9a7dd9
--- /dev/null
+++ b/liblfjail/command_map.hh
@@ -0,0 +1,63 @@
+/*
+ * This source code is released into the public domain.
+ */
+
+#ifndef LFJAIL_COMMAND_MAP_HH
+#define LFJAIL_COMMAND_MAP_HH
+
+/*
+ * 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
+ */
+
+#include <functional>
+#include <iostream>
+#include <string>
+#include <map>
+#include <print>
+
+#include "context.hh"
+#include "string_utils.hh"
+#include "usage_error.hh"
+
+namespace lfjail::command {
+
+using func = std::function<int (context const &, int, char **)>;
+
+// A node in the command hierarchy.
+struct node {
+ // The command name of this node.
+ std::string command;
+
+ // Handler for this node. May be null, which means this node has
+ // sub-commands but isn't a command itself.
+ func handler;
+
+ node(std::string command);
+
+ // Run the handler for this node.
+ int invoke(context const &ctx, int argc, char **argv) const;
+
+ // Create a new node under this one, or return it if it already exists.
+ // If path is empty, return this node.
+ node &create_node(std::string_view path);
+
+ void print_usage(std::string prefix = "") const;
+
+private:
+ std::map<std::string_view, node> commands;
+};
+
+// Get the root command node singleton.
+node &get_root_node();
+
+// Declare a global command and add it to the root node.
+struct command {
+ command(std::string_view path, func fn);
+};
+
+} // namespace lfjail
+
+#endif // !LFJAIL_COMMAND_MAP_HH