aboutsummaryrefslogtreecommitdiffstats
path: root/nihil.cli/command.cc
diff options
context:
space:
mode:
authorLexi Winter <lexi@le-fay.org>2025-06-29 00:42:31 +0100
committerLexi Winter <lexi@le-fay.org>2025-06-29 00:42:31 +0100
commitd24315268c11d435bb9accbce87b7f46dda6ed3e (patch)
tree66589cb6a15fa74d4b09683105c583e4a5c222b4 /nihil.cli/command.cc
parent7741a9698d29f79aca3e47495dcdf87c7a712f42 (diff)
downloadnihil-d24315268c11d435bb9accbce87b7f46dda6ed3e.tar.gz
nihil-d24315268c11d435bb9accbce87b7f46dda6ed3e.tar.bz2
cli: improve command dispatch a bit
Diffstat (limited to 'nihil.cli/command.cc')
-rw-r--r--nihil.cli/command.cc51
1 files changed, 51 insertions, 0 deletions
diff --git a/nihil.cli/command.cc b/nihil.cli/command.cc
new file mode 100644
index 0000000..475cad0
--- /dev/null
+++ b/nihil.cli/command.cc
@@ -0,0 +1,51 @@
+/*
+ * This source code is released into the public domain.
+ */
+
+module;
+
+#include <expected>
+#include <functional>
+#include <iostream>
+#include <print>
+#include <string>
+
+// For EX_USAGE. While <sysexits.h> is deprecated, there's no other standard
+// exit code for 'usage error'; some programs use 2 (common on Linux), but
+// 2 is also used for many other exit codes.
+#include <sysexits.h>
+
+module nihil.cli;
+
+import nihil.error;
+import :registry;
+
+namespace nihil {
+
+command::command(std::string_view path, std::string_view usage,
+ command_function_t handler)
+ : command_node(path)
+ , m_usage(usage)
+ , m_handler(std::move(handler))
+{
+ register_command(this);
+}
+
+auto command::usage(this command const &self) noexcept -> std::string_view
+{
+ return self.m_usage;
+}
+
+auto command::invoke(int argc, char **argv) const
+ -> std::expected<int, error>
+{
+ try {
+ return std::invoke(m_handler, argc, argv);
+ } catch (usage_error const &err) {
+ std::print(std::cerr, "{}\n", err.what());
+ std::print(std::cerr, "usage: {} {}", path(), usage());
+ return EX_USAGE;
+ }
+}
+
+} // namespace nihil