parseArgs parses an argument list and returns a TRTParsedArgs with the fields set accordingly. Assumes that options is validated. ErrMsg will be set if: - an argument is null - an argument is empty - an argument does not have option (i.e. "-" and "--") - a short argument has more than 1 character - the last argument in the list requires a value
| 141 | //! - a short argument has more than 1 character |
| 142 | //! - the last argument in the list requires a value |
| 143 | TRTParsedArgs parseArgs(int argc, const char* const* argv, const std::vector<TRTOption>& options) |
| 144 | { |
| 145 | TRTParsedArgs parsedArgs; |
| 146 | parsedArgs.values.resize(options.size()); |
| 147 | |
| 148 | for (int i = 1; i < argc; ++i) // index of current command-line argument |
| 149 | { |
| 150 | if (argv[i] == nullptr) |
| 151 | { |
| 152 | return TRTParsedArgs{"Null argument at index " + std::to_string(i)}; |
| 153 | } |
| 154 | |
| 155 | const std::string argStr(argv[i]); |
| 156 | if (argStr.empty()) |
| 157 | { |
| 158 | return TRTParsedArgs{"Empty argument at index " + std::to_string(i)}; |
| 159 | } |
| 160 | |
| 161 | // No starting hyphen means it is a positional argument |
| 162 | if (argStr[0] != '-') |
| 163 | { |
| 164 | parsedArgs.positionalArgs.push_back(argStr); |
| 165 | continue; |
| 166 | } |
| 167 | |
| 168 | if (argStr == "-" || argStr == "--") |
| 169 | { |
| 170 | return TRTParsedArgs{"Argument does not specify an option at index " + std::to_string(i)}; |
| 171 | } |
| 172 | |
| 173 | // If only 1 hyphen, char after is the flag. |
| 174 | TRTOption opt{' ', "", false, ""}; |
| 175 | std::string value; |
| 176 | if (argStr[1] != '-') |
| 177 | { |
| 178 | // Must only have 1 char after the hyphen |
| 179 | if (argStr.size() > 2) |
| 180 | { |
| 181 | return TRTParsedArgs{"Short arg contains more than 1 character at index " + std::to_string(i)}; |
| 182 | } |
| 183 | opt.shortName = argStr[1]; |
| 184 | } |
| 185 | else |
| 186 | { |
| 187 | opt.longName = argStr.substr(2); |
| 188 | |
| 189 | // We need to support --foo=bar syntax, so look for '=' |
| 190 | const size_t eqIndex = opt.longName.find('='); |
| 191 | if (eqIndex < opt.longName.size()) |
| 192 | { |
| 193 | value = opt.longName.substr(eqIndex + 1); |
| 194 | opt.longName = opt.longName.substr(0, eqIndex); |
| 195 | } |
| 196 | } |
| 197 | |
| 198 | const int idx = getTRTOptionIndex(options, opt); |
| 199 | if (idx < 0) |
| 200 | { |
no test coverage detected