cli.cxx 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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/cli.h"
  9. #include <string_utils/tokenizer.h>
  10. namespace cli {
  11. cli::cli(std::string const & prompt, std::istream &in)
  12. : in_(in), prompt_(prompt), eof_(false) {
  13. register_callback("quit", [this] { eof_ = true; });
  14. register_callback("help", [this] {
  15. for (auto & [k, v] : arguments_) {
  16. std::cout << k;
  17. for (size_t i = 0; i < v; ++i) {
  18. std::cout << " arg" << i;
  19. }
  20. std::cout << "\n";
  21. }
  22. });
  23. }
  24. cli::cli(std::istream &in) : cli("cli::cli :> ", in) {}
  25. bool cli::active() const {
  26. return !eof_ && (std::cout << prompt_).good();
  27. }
  28. void cli::run() const {
  29. std::string command;
  30. while (active() && std::getline(in_, command)) {
  31. auto split = string_utils::EscapedTokenizer(" ", {'"', "\\\""});
  32. auto views = split(command);
  33. command = views.front();
  34. views.erase(views.begin());
  35. if (!callbacks_.count(command)) {
  36. std::cerr << "Unknown command: " << command << "\n";
  37. continue;
  38. }
  39. callbacks_.at(command)(views);
  40. }
  41. }
  42. }