* Parses the string input as command line arguments, returns an object where * keys are argument name and values are argument values. * - Assumes the string is a properly formatted list of arguments, where name/value pairs * are separated by spaces and values with spaces are enclosed
(args: string)
| 13 | * Returns: { "-o":"output file", "-c":"configuration", "-v":"m", "--force":undefined } |
| 14 | */ |
| 15 | public static async parseCommandArguments(args: string): Promise<object> { |
| 16 | let dictionary = {}; |
| 17 | |
| 18 | // Regex matches dotnet build parameters: https://docs.microsoft.com/dotnet/core/tools/dotnet-build |
| 19 | // \-\-?[A-Za-z\-]+ Parameter name, may have 1 or 2 dashes. Ex: -o, --verbose |
| 20 | // (?:$|\s+) End of line or whitespace separating param name and value |
| 21 | // (?:[^\s"'\-]+ Param value, anything that's not a whitespace, ", ', or - |
| 22 | // |"[^"]*"|'[^']*') ... or anything enclosed in either " or ' |
| 23 | const matches = args.match(/(\-\-?[A-Za-z\-]+(?:$|\s+)(?:[^\s"'\-]+|"[^"]*"|'[^']*')?)/g); |
| 24 | matches?.forEach(match => { |
| 25 | const whitespaceIndex = match.trim().indexOf(' '); |
| 26 | if (whitespaceIndex >= 0) { |
| 27 | // match is in the format of -paramName "param value" |
| 28 | const paramName = match.substring(0, whitespaceIndex); |
| 29 | const paramValue = match.substring(whitespaceIndex).trim(); |
| 30 | dictionary[paramName] = paramValue; |
| 31 | } else { |
| 32 | // match is only the param name with no value. Ex: --force, --verbose |
| 33 | dictionary[match] = undefined; |
| 34 | } |
| 35 | }); |
| 36 | |
| 37 | return dictionary; |
| 38 | } |
| 39 | |
| 40 | /** |
| 41 | * Looks for an argument in a dictionary of argument name/value pairs. |
no test coverage detected