cli.cxx 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. //
  2. // cli.cxx
  3. // tax-manager
  4. //
  5. // Created by Sam Jaffe on 10/8/20.
  6. // Copyright © 2020 Sam Jaffe. All rights reserved.
  7. //
  8. #include "cli.h"
  9. #include <iostream>
  10. namespace {
  11. cli::args_t tokenize(std::string const & search, std::string const & token,
  12. bool ignore_empty = false) {
  13. cli::args_t rval;
  14. size_t i = 0;
  15. for (size_t n = search.find(token); n != std::string::npos;
  16. i = n + 1, n = search.find(token, i)) {
  17. if (i == n && ignore_empty) continue;
  18. rval.emplace_back(&search[i], n - i);
  19. }
  20. rval.emplace_back(&search[i], search.size() - i);
  21. return rval;
  22. }
  23. }
  24. namespace cli {
  25. cli::cli() : callbacks_(), eof_(false) {
  26. register_callback("quit", [this] { eof_ = true; });
  27. }
  28. void cli::run() const {
  29. std::string command;
  30. while (!eof_ && std::getline(std::cin, command).good()) {
  31. auto views = tokenize(command, " ");
  32. command = views.front();
  33. views.erase(views.begin());
  34. if (!callbacks_.count(command)) continue; // TODO: Error message
  35. callbacks_.at(command)(views);
  36. }
  37. }
  38. template <> std::string cli::from_string(std::string const & str) {
  39. return str;
  40. }
  41. template <> int cli::from_string(std::string const & str) {
  42. return std::stoi(str);
  43. }
  44. }