* 解析命令行字符串为数组 * 简单实现,支持引号和转义
(input: string)
| 31 | /** |
| 32 | * 解析命令行字符串为数组 |
| 33 | * 简单实现,支持引号和转义 |
| 34 | */ |
| 35 | function splitCommandLine(input: string): string[] { |
| 36 | const result: string[] = []; |
| 37 | let current = ''; |
| 38 | let inQuote = false; |
| 39 | let quoteChar = ''; |
| 40 | let escaped = false; |
| 41 | |
| 42 | for (const char of input) { |
| 43 | if (escaped) { |
| 44 | current += char; |
| 45 | escaped = false; |
| 46 | continue; |
| 47 | } |
| 48 | |
| 49 | if (char === '\\') { |
| 50 | escaped = true; |
| 51 | continue; |
| 52 | } |
| 53 | |
| 54 | if ((char === '"' || char === "'") && !inQuote) { |
| 55 | inQuote = true; |
| 56 | quoteChar = char; |
| 57 | continue; |
| 58 | } |
| 59 | |
| 60 | if (char === quoteChar && inQuote) { |
| 61 | inQuote = false; |
| 62 | quoteChar = ''; |
| 63 | continue; |
| 64 | } |
| 65 | |
| 66 | if (char === ' ' && !inQuote) { |
| 67 | if (current) { |
| 68 | result.push(current); |
| 69 | current = ''; |
| 70 | } |
| 71 | continue; |
| 72 | } |
| 73 | |
| 74 | current += char; |
| 75 | } |
| 76 | |
| 77 | if (current) { |
| 78 | result.push(current); |
| 79 | } |
| 80 | |
| 81 | return result; |
| 82 | } |
| 83 |