(argv: string[], options: OptionDef[])
| 80 | * - default: string |
| 81 | */ |
| 82 | export function parseFlags(argv: string[], options: OptionDef[]): GlobalFlags { |
| 83 | const schema = buildSchema(options); |
| 84 | const flags: GlobalFlags = { |
| 85 | quiet: false, |
| 86 | verbose: false, |
| 87 | noColor: false, |
| 88 | yes: false, |
| 89 | dryRun: false, |
| 90 | help: false, |
| 91 | nonInteractive: false, |
| 92 | async: false, |
| 93 | }; |
| 94 | |
| 95 | let i = 0; |
| 96 | while (i < argv.length) { |
| 97 | const arg = argv[i]!; |
| 98 | |
| 99 | if (arg === '--help' || arg === '-h') { flags.help = true; i++; continue; } |
| 100 | if (arg === '--') { break; } |
| 101 | |
| 102 | if (arg.startsWith('--')) { |
| 103 | const eqIdx = arg.indexOf('='); |
| 104 | let key: string; |
| 105 | let value: string | undefined; |
| 106 | |
| 107 | if (eqIdx !== -1) { |
| 108 | key = arg.slice(2, eqIdx); |
| 109 | value = arg.slice(eqIdx + 1); |
| 110 | } else { |
| 111 | key = arg.slice(2); |
| 112 | } |
| 113 | |
| 114 | const camelKey = kebabToCamel(key); |
| 115 | |
| 116 | if (schema.booleans.has(camelKey)) { |
| 117 | (flags as Record<string, unknown>)[camelKey] = true; |
| 118 | i++; |
| 119 | continue; |
| 120 | } |
| 121 | |
| 122 | if (value === undefined) { |
| 123 | i++; |
| 124 | value = argv[i]; |
| 125 | } |
| 126 | |
| 127 | if (value === undefined) throw new Error(`Flag --${key} requires a value.`); |
| 128 | |
| 129 | if (schema.arrays.has(camelKey)) { |
| 130 | const arr = (flags as Record<string, unknown>)[camelKey] as string[] | undefined; |
| 131 | if (arr) arr.push(value); |
| 132 | else (flags as Record<string, unknown>)[camelKey] = [value]; |
| 133 | } else if (schema.numbers.has(camelKey)) { |
| 134 | const numericValue = Number(value); |
| 135 | if (value.trim() === '' || !Number.isFinite(numericValue)) { |
| 136 | throw new Error(`Flag --${key} requires a numeric value, got "${value}".`); |
| 137 | } |
| 138 | (flags as Record<string, unknown>)[camelKey] = numericValue; |
| 139 | } else { |
no test coverage detected