CommandUtils.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #include "server/commands/CommandUtils.h"
  2. static bool splitStringIntern(const std::string& rawCommand, std::string& command, std::vector<std::string>& args) {
  3. size_t old = 0;
  4. size_t index = 0;
  5. // parse first argument
  6. while(index < rawCommand.size()) {
  7. if(rawCommand[index] == ' ') {
  8. command = rawCommand.substr(old, index - old);
  9. old = index + 1;
  10. index++;
  11. break;
  12. }
  13. index++;
  14. }
  15. // if the command name is the whole raw command
  16. if(index == rawCommand.size()) {
  17. command = rawCommand.substr(old, index - old);
  18. return false;
  19. }
  20. // parse remainding arguments
  21. while(index < rawCommand.size()) {
  22. if(rawCommand[index] == '"') {
  23. // no space before the quotation mark
  24. if(index != old) {
  25. return true;
  26. }
  27. old = index + 1;
  28. while(true) {
  29. index++;
  30. // quotation mark not closed
  31. if(index >= rawCommand.size()) {
  32. return true;
  33. } else if(rawCommand[index] == '"') {
  34. break;
  35. }
  36. }
  37. // no space after quotation mark
  38. if(index + 1 < rawCommand.size() && rawCommand[index + 1] != ' ') {
  39. return true;
  40. }
  41. args.push_back(rawCommand.substr(old, index - old));
  42. old = index + 2;
  43. } else if(rawCommand[index] == ' ') {
  44. if(index > old && index - old > 0) {
  45. args.push_back(rawCommand.substr(old, index - old));
  46. }
  47. old = index + 1;
  48. }
  49. index++;
  50. }
  51. if(index > old && index - old > 0) {
  52. args.push_back(rawCommand.substr(old, index - old));
  53. }
  54. return false;
  55. }
  56. bool CommandUtils::splitString(const std::string& rawCommand, std::string& command, std::vector<std::string>& args) {
  57. bool b = splitStringIntern(rawCommand, command, args);
  58. if(b) {
  59. args.clear();
  60. command = "";
  61. }
  62. return b;
  63. }