CommandLine.cpp 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. //
  2. // Created by xcbosa on 2023/1/31.
  3. //
  4. #include "CommandLine.h"
  5. #include "strop.h"
  6. #include <unistd.h>
  7. namespace xc {
  8. namespace utils {
  9. static CommandLineCommand *registeredCommands[1024];
  10. static int registeredCommandsId(0);
  11. CommandLineCommand::CommandLineCommand(string name, string usage, string message) {
  12. this->commandName = name;
  13. this->commandUsage = usage;
  14. this->message = message;
  15. assert(registeredCommandsId < 1024);
  16. registeredCommands[registeredCommandsId++] = this;
  17. cout << "[CommandLineCommand] Registered " << commandName << endl;
  18. }
  19. CommandLineStringCommand::CommandLineStringCommand(string commandName, string commandUsage, string message, int argCnt, function<void (vector<string>)> handler):
  20. CommandLineCommand(commandName, commandUsage, message) {
  21. this->argCnt = argCnt;
  22. this->handler = handler;
  23. }
  24. void CommandLineStringCommand::evaluate(string userInputLine) const {
  25. auto list = split(userInputLine, " ");
  26. vector<string> result;
  27. for (int i = 1; i < list.size(); i++) {
  28. string copied = list[i];
  29. trim(copied);
  30. result.push_back(copied);
  31. }
  32. if (result.size() != this->argCnt) {
  33. cerr << "Usage: " << this->commandUsage << endl;
  34. } else {
  35. this->handler(result);
  36. }
  37. }
  38. void CommandLineWorker::workerLoop() {
  39. char cinReadBuff[1024];
  40. while (true) {
  41. bzero(cinReadBuff, sizeof(cinReadBuff));
  42. cin.getline(cinReadBuff, sizeof(cinReadBuff));
  43. string str(cinReadBuff);
  44. if (str.empty()) continue;
  45. auto list = split(str, " ");
  46. string titleUppercase = uppercase(list[0]);
  47. if (titleUppercase == "HELP") {
  48. cout << "Frp-WebUI Command List" << endl;
  49. for (int i = 0; i < registeredCommandsId; i++) {
  50. cout << registeredCommands[i]->message << " : " << registeredCommands[i]->commandUsage << endl;
  51. }
  52. } else {
  53. bool founded = false;
  54. for (int i = 0; i < registeredCommandsId; i++) {
  55. auto command = registeredCommands[i];
  56. if (uppercase(command->commandName) == titleUppercase) {
  57. command->evaluate(str);
  58. founded = true;
  59. break;
  60. }
  61. }
  62. if (!founded) {
  63. cerr << "Command " << list[0] << " not founded, type help to view help." << endl;
  64. }
  65. }
  66. cin.clear();
  67. usleep(1000 * 10);
  68. }
  69. }
  70. } // xc
  71. } // utils