| 17 | } |
| 18 | |
| 19 | bool CommandLine::Parse(int argc, char **argv) { |
| 20 | if (argc < 2) { |
| 21 | return false; |
| 22 | } |
| 23 | _currentTarget = argv[1]; |
| 24 | |
| 25 | if (_targets.count(_currentTarget) == 0) { |
| 26 | return false; |
| 27 | } |
| 28 | |
| 29 | bool isParse = _targets.at(_currentTarget); |
| 30 | _argvs.reserve(argc); |
| 31 | for (int i = 0; i != argc; i++) { |
| 32 | _argvs.emplace_back(argv[i]); |
| 33 | } |
| 34 | |
| 35 | if (!isParse) { |
| 36 | return true; |
| 37 | } |
| 38 | |
| 39 | // index = 0 的参数是程序名 |
| 40 | for (int index = 1; index < argc; index++) { |
| 41 | std::string current = argv[index]; |
| 42 | if (current.empty()) { |
| 43 | continue; |
| 44 | } |
| 45 | // not empty |
| 46 | if (current[0] == '-') { |
| 47 | // 仅仅支持-dir这种形式 |
| 48 | std::string optionName = current.substr(1); |
| 49 | // 如果该参数不存在 |
| 50 | if (_args.count(optionName) == 0) { |
| 51 | return false; |
| 52 | } |
| 53 | CommandLineOption &option = _args[optionName]; |
| 54 | |
| 55 | if (option.Type == CommandLineValueType::Boolean) { |
| 56 | option.Value = "true"; |
| 57 | continue; |
| 58 | } |
| 59 | |
| 60 | std::string optionValue; |
| 61 | optionValue.reserve(128); |
| 62 | |
| 63 | // 该选项之后没有接参数 |
| 64 | // 目前没有支持bool选项的必要 |
| 65 | if (argc <= (index + 1) && !option.RestOfAll) { |
| 66 | return false; |
| 67 | } |
| 68 | |
| 69 | do { |
| 70 | if (argc <= (index + 1)) { |
| 71 | break; |
| 72 | } |
| 73 | |
| 74 | std::string value = argv[++index]; |
| 75 | if (value.empty()) { |
| 76 | continue; |