cli.h 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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 <unordered_map>
  13. #include <vector>
  14. #include "lambda_cast.h"
  15. namespace cli {
  16. class cli {
  17. public:
  18. using args_t = std::vector<std::string_view>;
  19. using callback = std::function<void(args_t const &)>;
  20. private:
  21. std::unordered_map<std::string, callback> callbacks_;
  22. bool eof_;
  23. public:
  24. cli();
  25. template <typename... Args>
  26. cli & register_callback(std::string const & handle,
  27. std::function<void(Args...)> const & cb);
  28. template <typename F>
  29. cli & register_callback(std::string const & handle, F && cb) {
  30. return register_callback(handle, lambdas::FFL(cb));
  31. }
  32. void run() const;
  33. template <typename T> static T from_string(std::string const &);
  34. };
  35. template <typename... Args, size_t... Is>
  36. void cli_invoke(std::function<void(Args...)> cb, cli::args_t const & args,
  37. std::index_sequence<Is...>) {
  38. using tuple = std::tuple<Args...>;
  39. cb(cli::from_string<std::tuple_element<Is, tuple>>(args[Is])...);
  40. }
  41. template <typename... Args>
  42. cli & cli::register_callback(std::string const & handle,
  43. std::function<void(Args...)> const & cb) {
  44. callbacks_.emplace(handle, [cb](args_t const & args) {
  45. if (sizeof...(Args) > args.size()) return; // TODO: Error message
  46. cli_invoke(cb, args, std::make_index_sequence<sizeof...(Args)>());
  47. });
  48. return *this;
  49. }
  50. }