| 54 | } |
| 55 | |
| 56 | bool CommandLine::Parse(int argc, char **argv) { |
| 57 | if (argc < 2) { |
| 58 | return false; |
| 59 | } |
| 60 | _currentTarget = argv[1]; |
| 61 | |
| 62 | if (_targets.count(_currentTarget) == 0) { |
| 63 | return false; |
| 64 | } |
| 65 | |
| 66 | _options = &_targets[_currentTarget]; |
| 67 | |
| 68 | _argvs.reserve(argc); |
| 69 | for (int i = 0; i != argc; i++) { |
| 70 | _argvs.emplace_back(argv[i]); |
| 71 | } |
| 72 | |
| 73 | // index = 0 �IJ����dz����� |
| 74 | // index = 1 �IJ���ʱtarget |
| 75 | for (int index = 2; index < argc; index++) { |
| 76 | std::string_view current = _argvs[index]; |
| 77 | if (current.empty()) { |
| 78 | continue; |
| 79 | } |
| 80 | |
| 81 | std::string_view option; |
| 82 | |
| 83 | if (current.starts_with("--")) { |
| 84 | option = current.substr(2); |
| 85 | if (option == "help") { |
| 86 | return false; |
| 87 | } |
| 88 | |
| 89 | auto eqPos = option.find_first_of('='); |
| 90 | if (eqPos != std::string_view::npos) { |
| 91 | if (!_options->_enableRestArgs) { |
| 92 | _errors.emplace_back(util::format("Unknown option {} ,please enable key=value options", current)); |
| 93 | return false; |
| 94 | } |
| 95 | std::string_view value = option.substr(eqPos + 1); |
| 96 | option = option.substr(0, eqPos); |
| 97 | _options->_restArgs.insert({std::string(option), std::string(value)}); |
| 98 | continue; |
| 99 | } |
| 100 | } else if (current.starts_with("-")) { |
| 101 | auto shortOption = current.substr(1); |
| 102 | |
| 103 | if (shortOption == "h") { |
| 104 | return false; |
| 105 | } |
| 106 | |
| 107 | if (_options->_shortMap.count(shortOption) == 0) { |
| 108 | _errors.emplace_back(util::format("Unknown Option {}", current)); |
| 109 | return false; |
| 110 | } |
| 111 | option = _options->_shortMap.find(shortOption)->second; |
| 112 | } else { |
| 113 | return false; |