* Parses the arguments from the command-line. * * @param argc Number of arguments. * @param argv Raw argument values. * * @return True if the parsing was successful, otherwise false. */
| 162 | * @return True if the parsing was successful, otherwise false. |
| 163 | */ |
| 164 | bool ArgHandler::parse(int argc, char** argv) |
| 165 | { |
| 166 | resetArgData(); |
| 167 | |
| 168 | // argc should never be less than 1 |
| 169 | if (argc < 1) |
| 170 | return false; |
| 171 | |
| 172 | // skip the argv[0] as it is the executable name |
| 173 | for (int i = 1; i < argc; ++i) |
| 174 | { |
| 175 | ArgInfo* arg = nullptr; |
| 176 | |
| 177 | // We expect it to be a long option |
| 178 | if (strncmp(argv[i], "--", 2) == 0) |
| 179 | { |
| 180 | std::string longOpt = std::string(argv[i] + 2); |
| 181 | |
| 182 | // -- terminates the argument input in the most cases |
| 183 | if (longOpt.empty()) |
| 184 | break; |
| 185 | |
| 186 | ArgMap::iterator itr = _argMap.find(longOpt); |
| 187 | if (itr == _argMap.end()) |
| 188 | return false; |
| 189 | |
| 190 | arg = (*itr).second; |
| 191 | } |
| 192 | // else it is short option |
| 193 | else if (argv[i][0] == '-') |
| 194 | { |
| 195 | // there should be no more than 1 character after '-' |
| 196 | if (strlen(argv[i]) > 2) |
| 197 | return false; |
| 198 | |
| 199 | ArgMap::iterator itr = _argMap.find(std::string(&argv[i][1], 1)); |
| 200 | if (itr == _argMap.end()) |
| 201 | return false; |
| 202 | |
| 203 | arg = (*itr).second; |
| 204 | } |
| 205 | // Doesn't belong to any argument, it is a raw input |
| 206 | else |
| 207 | { |
| 208 | _rawInputs.push_back(std::string(argv[i])); |
| 209 | continue; |
| 210 | } |
| 211 | |
| 212 | // Option already used |
| 213 | if (arg->_data->used) |
| 214 | return false; |
| 215 | |
| 216 | arg->_data->used = true; |
| 217 | if (arg->_hasInput) |
| 218 | { |
| 219 | // check if we won't access out of argv memory |
| 220 | if (i + 1 >= argc) |
| 221 | return false; |
no test coverage detected