| 1 | #include "cli_utils.h" |
| 2 | |
| 3 | nlohmann::json parse_common_flags(int argc, char *argv[], std::map<std::string, std::optional<std::type_index>> strong_types) |
| 4 | { |
| 5 | nlohmann::json parameters; |
| 6 | |
| 7 | if (argc > 0) |
| 8 | { |
| 9 | for (int i = 0; i < argc; i++) |
| 10 | { |
| 11 | if (i != argc) |
| 12 | { |
| 13 | std::string flag = argv[i]; |
| 14 | |
| 15 | if (flag[0] == '-' && flag[1] == '-') // Detect a flag |
| 16 | { |
| 17 | flag = flag.substr(2, flag.length()); // Remove the "--" |
| 18 | |
| 19 | if (i + 1 == argc) // Check if there is a next element, if not, consider this is a switch |
| 20 | { |
| 21 | parameters[flag] = true; |
| 22 | continue; |
| 23 | } |
| 24 | |
| 25 | std::string value = argv[i + 1]; // Get value |
| 26 | |
| 27 | // Check if the next value is a flag as well. If so, treat as a switch and set it to true |
| 28 | if (value[0] == '-' && value[1] == '-') |
| 29 | { |
| 30 | parameters[flag] = true; |
| 31 | continue; |
| 32 | } |
| 33 | |
| 34 | // Force specified flags to be parsed as the specified type |
| 35 | if (strong_types.count(flag) > 0) |
| 36 | { |
| 37 | if (strong_types[flag] == typeid(std::string)) |
| 38 | { |
| 39 | parameters[flag] = value; |
| 40 | i++; |
| 41 | continue; |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | // Is this a boolean? |
| 46 | if (value == "false" || value == "true") |
| 47 | { |
| 48 | parameters[flag] = (value == "true"); |
| 49 | continue; |
| 50 | } |
| 51 | |
| 52 | try // Attempt to parse it as a number |
| 53 | { |
| 54 | for (char &c : std::string(argv[i + 1])) |
| 55 | if (c < '0' || '9' < c) |
| 56 | if (c != '.' && c != 'e') |
| 57 | if (c != '-') |
| 58 | throw std::runtime_error(""); |
| 59 | |
| 60 | int points_cnt = 0; |
no test coverage detected