|
|
@@ -0,0 +1,60 @@
|
|
|
+//
|
|
|
+// cli.h
|
|
|
+// tax-manager
|
|
|
+//
|
|
|
+// Created by Sam Jaffe on 10/8/20.
|
|
|
+// Copyright © 2020 Sam Jaffe. All rights reserved.
|
|
|
+//
|
|
|
+
|
|
|
+#pragma once
|
|
|
+
|
|
|
+#include <functional>
|
|
|
+#include <string>
|
|
|
+#include <string_view>
|
|
|
+#include <unordered_map>
|
|
|
+#include <vector>
|
|
|
+
|
|
|
+#include "lambda_cast.h"
|
|
|
+
|
|
|
+namespace cli {
|
|
|
+
|
|
|
+class cli {
|
|
|
+public:
|
|
|
+ using args_t = std::vector<std::string_view>;
|
|
|
+ using callback = std::function<void(args_t const &)>;
|
|
|
+
|
|
|
+private:
|
|
|
+ std::unordered_map<std::string, callback> callbacks_;
|
|
|
+ bool eof_;
|
|
|
+
|
|
|
+public:
|
|
|
+ cli();
|
|
|
+ template <typename... Args>
|
|
|
+ cli & register_callback(std::string const & handle,
|
|
|
+ std::function<void(Args...)> const & cb);
|
|
|
+ template <typename F>
|
|
|
+ cli & register_callback(std::string const & handle, F && cb) {
|
|
|
+ return register_callback(handle, lambdas::FFL(cb));
|
|
|
+ }
|
|
|
+ void run() const;
|
|
|
+ template <typename T> static T from_string(std::string const &);
|
|
|
+};
|
|
|
+
|
|
|
+template <typename... Args, size_t... Is>
|
|
|
+void cli_invoke(std::function<void(Args...)> cb, cli::args_t const & args,
|
|
|
+ std::index_sequence<Is...>) {
|
|
|
+ using tuple = std::tuple<Args...>;
|
|
|
+ cb(cli::from_string<std::tuple_element<Is, tuple>>(args[Is])...);
|
|
|
+}
|
|
|
+
|
|
|
+template <typename... Args>
|
|
|
+cli & cli::register_callback(std::string const & handle,
|
|
|
+ std::function<void(Args...)> const & cb) {
|
|
|
+ callbacks_.emplace(handle, [cb](args_t const & args) {
|
|
|
+ if (sizeof...(Args) > args.size()) return; // TODO: Error message
|
|
|
+ cli_invoke(cb, args, std::make_index_sequence<sizeof...(Args)>());
|
|
|
+ });
|
|
|
+ return *this;
|
|
|
+}
|
|
|
+
|
|
|
+}
|