CommandLine.cpp 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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::processCommand(string cmd) {
  39. auto list = split(cmd, " ");
  40. string titleUppercase = uppercase(list[0]);
  41. if (titleUppercase == "HELP") {
  42. cout << "Frp-WebUI Command List" << endl;
  43. for (int i = 0; i < registeredCommandsId; i++) {
  44. cout << registeredCommands[i]->message << " : " << registeredCommands[i]->commandUsage << endl;
  45. }
  46. } else {
  47. bool founded = false;
  48. for (int i = 0; i < registeredCommandsId; i++) {
  49. auto command = registeredCommands[i];
  50. if (uppercase(command->commandName) == titleUppercase) {
  51. command->evaluate(cmd);
  52. founded = true;
  53. break;
  54. }
  55. }
  56. if (!founded) {
  57. cerr << "Command " << list[0] << " not founded, type help to view help." << endl;
  58. }
  59. }
  60. }
  61. void CommandLineWorker::workerLoop() {
  62. char cinReadBuff[1024];
  63. while (true) {
  64. bzero(cinReadBuff, sizeof(cinReadBuff));
  65. cin.getline(cinReadBuff, sizeof(cinReadBuff));
  66. if (cin.eof() || cin.bad() || cin.fail()) {
  67. cout << "Frp-WebUI interactive command disabled during stdin is closed." << endl;
  68. return;
  69. }
  70. string str(cinReadBuff);
  71. if (str.empty()) continue;
  72. this->processCommand(str);
  73. cin.clear();
  74. usleep(1000 * 10);
  75. }
  76. }
  77. } // xc
  78. } // utils