(argv, config = {})
| 1 | export function parseArgs(argv, config = {}) { |
| 2 | const valueOptions = new Set(config.valueOptions ?? []); |
| 3 | const booleanOptions = new Set(config.booleanOptions ?? []); |
| 4 | const aliasMap = config.aliasMap ?? {}; |
| 5 | const options = {}; |
| 6 | const positionals = []; |
| 7 | let passthrough = false; |
| 8 | |
| 9 | for (let index = 0; index < argv.length; index += 1) { |
| 10 | const token = argv[index]; |
| 11 | |
| 12 | if (passthrough) { |
| 13 | positionals.push(token); |
| 14 | continue; |
| 15 | } |
| 16 | |
| 17 | if (token === "--") { |
| 18 | passthrough = true; |
| 19 | continue; |
| 20 | } |
| 21 | |
| 22 | if (!token.startsWith("-") || token === "-") { |
| 23 | positionals.push(token); |
| 24 | continue; |
| 25 | } |
| 26 | |
| 27 | if (token.startsWith("--")) { |
| 28 | const [rawKey, inlineValue] = token.slice(2).split("=", 2); |
| 29 | const key = aliasMap[rawKey] ?? rawKey; |
| 30 | |
| 31 | if (booleanOptions.has(key)) { |
| 32 | options[key] = inlineValue === undefined ? true : inlineValue !== "false"; |
| 33 | continue; |
| 34 | } |
| 35 | |
| 36 | if (valueOptions.has(key)) { |
| 37 | const nextValue = inlineValue ?? argv[index + 1]; |
| 38 | if (nextValue === undefined) { |
| 39 | throw new Error(`Missing value for --${rawKey}`); |
| 40 | } |
| 41 | options[key] = nextValue; |
| 42 | if (inlineValue === undefined) { |
| 43 | index += 1; |
| 44 | } |
| 45 | continue; |
| 46 | } |
| 47 | |
| 48 | positionals.push(token); |
| 49 | continue; |
| 50 | } |
| 51 | |
| 52 | const shortKey = token.slice(1); |
| 53 | const key = aliasMap[shortKey] ?? shortKey; |
| 54 | |
| 55 | if (booleanOptions.has(key)) { |
| 56 | options[key] = true; |
| 57 | continue; |
| 58 | } |
| 59 | |
| 60 | if (valueOptions.has(key)) { |
no outgoing calls
no test coverage detected