cli.h 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. //
  2. // cli.h
  3. // tax-manager
  4. //
  5. // Created by Sam Jaffe on 10/8/20.
  6. // Copyright © 2020 Sam Jaffe. All rights reserved.
  7. //
  8. #pragma once
  9. #include <functional>
  10. #include <string>
  11. #include <string_view>
  12. #include <tuple>
  13. #include <unordered_map>
  14. #include <vector>
  15. #include "lambda_cast.h"
  16. namespace cli {
  17. class cli {
  18. public:
  19. using args_t = std::vector<std::string_view>;
  20. using callback = std::function<void(args_t const &)>;
  21. private:
  22. std::unordered_map<std::string, callback> callbacks_;
  23. bool eof_;
  24. public:
  25. cli();
  26. template <typename... Args>
  27. cli & register_callback(std::string const & handle,
  28. std::function<void(Args...)> const & cb);
  29. template <typename F>
  30. cli & register_callback(std::string const & handle, F && cb) {
  31. return register_callback(handle, lambdas::FFL(cb));
  32. }
  33. void run() const;
  34. template <typename T> static T from_string(std::string const &);
  35. };
  36. template <typename... Args, size_t... Is>
  37. void cli_invoke(std::function<void(Args...)> cb, cli::args_t const & args,
  38. std::index_sequence<Is...>) {
  39. using tuple = std::tuple<Args...>;
  40. cb(cli::from_string<std::tuple_element<Is, tuple>>(args[Is])...);
  41. }
  42. template <typename... Args>
  43. cli & cli::register_callback(std::string const & handle,
  44. std::function<void(Args...)> const & cb) {
  45. callbacks_.emplace(handle, [cb](args_t const & args) {
  46. if (sizeof...(Args) > args.size()) return; // TODO: Error message
  47. cli_invoke(cb, args, std::make_index_sequence<sizeof...(Args)>());
  48. });
  49. return *this;
  50. }
  51. }