CommandLine.cpp 3.2 KB

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