|
| 1 | +import type { GlobalFlags } from './types/flags'; |
| 2 | + |
| 3 | +export interface ParsedArgs { |
| 4 | + commandPath: string[]; |
| 5 | + flags: GlobalFlags; |
| 6 | +} |
| 7 | + |
| 8 | +export function parseArgs(argv: string[]): ParsedArgs { |
| 9 | + const commandPath: string[] = []; |
| 10 | + const flags: GlobalFlags = { |
| 11 | + quiet: false, |
| 12 | + verbose: false, |
| 13 | + noColor: false, |
| 14 | + yes: false, |
| 15 | + dryRun: false, |
| 16 | + help: false, |
| 17 | + }; |
| 18 | + |
| 19 | + let i = 0; |
| 20 | + while (i < argv.length) { |
| 21 | + const arg = argv[i]!; |
| 22 | + |
| 23 | + if (arg === '--help' || arg === '-h') { |
| 24 | + flags.help = true; |
| 25 | + i++; |
| 26 | + continue; |
| 27 | + } |
| 28 | + |
| 29 | + if (arg === '--') { |
| 30 | + i++; |
| 31 | + break; |
| 32 | + } |
| 33 | + |
| 34 | + if (arg.startsWith('--')) { |
| 35 | + const eqIndex = arg.indexOf('='); |
| 36 | + let key: string; |
| 37 | + let value: string | undefined; |
| 38 | + |
| 39 | + if (eqIndex !== -1) { |
| 40 | + key = arg.slice(2, eqIndex); |
| 41 | + value = arg.slice(eqIndex + 1); |
| 42 | + } else { |
| 43 | + key = arg.slice(2); |
| 44 | + } |
| 45 | + |
| 46 | + const camelKey = kebabToCamel(key); |
| 47 | + |
| 48 | + // Boolean flags |
| 49 | + if (['quiet', 'verbose', 'noColor', 'yes', 'dryRun', 'help', 'stream', |
| 50 | + 'subtitles', 'autoLyrics', 'wait', 'noBrowser'].includes(camelKey)) { |
| 51 | + (flags as Record<string, unknown>)[camelKey] = true; |
| 52 | + i++; |
| 53 | + continue; |
| 54 | + } |
| 55 | + |
| 56 | + // Value flags |
| 57 | + if (value === undefined) { |
| 58 | + i++; |
| 59 | + value = argv[i]; |
| 60 | + } |
| 61 | + |
| 62 | + if (value === undefined) { |
| 63 | + throw new Error(`Flag --${key} requires a value.`); |
| 64 | + } |
| 65 | + |
| 66 | + // Repeatable flags |
| 67 | + if (['message', 'tool', 'pronunciation'].includes(camelKey)) { |
| 68 | + const arr = (flags as Record<string, unknown>)[camelKey] as string[] | undefined; |
| 69 | + if (arr) { |
| 70 | + arr.push(value); |
| 71 | + } else { |
| 72 | + (flags as Record<string, unknown>)[camelKey] = [value]; |
| 73 | + } |
| 74 | + } else if (['maxTokens', 'temperature', 'topP', 'speed', 'volume', |
| 75 | + 'pitch', 'sampleRate', 'bitrate', 'channels', 'n', |
| 76 | + 'timeout', 'pollInterval'].includes(camelKey)) { |
| 77 | + (flags as Record<string, unknown>)[camelKey] = Number(value); |
| 78 | + } else { |
| 79 | + (flags as Record<string, unknown>)[camelKey] = value; |
| 80 | + } |
| 81 | + i++; |
| 82 | + continue; |
| 83 | + } |
| 84 | + |
| 85 | + // Positional argument — part of command path |
| 86 | + commandPath.push(arg); |
| 87 | + i++; |
| 88 | + } |
| 89 | + |
| 90 | + return { commandPath, flags }; |
| 91 | +} |
| 92 | + |
| 93 | +function kebabToCamel(str: string): string { |
| 94 | + return str.replace(/-([a-z])/g, (_, c: string) => c.toUpperCase()); |
| 95 | +} |
0 commit comments