(args: string[], table: FlagTable)
| 741 | } |
| 742 | |
| 743 | function parseFlags(args: string[], table: FlagTable): ParsedFlags | { error: string } { |
| 744 | const flags: Record<string, string | boolean> = {}; |
| 745 | const positional: string[] = []; |
| 746 | for (let i = 0; i < args.length; i++) { |
| 747 | const arg = args[i]; |
| 748 | if (arg === "--") { |
| 749 | // Everything after `--` is positional. |
| 750 | positional.push(...args.slice(i + 1)); |
| 751 | break; |
| 752 | } |
| 753 | if (arg.startsWith("--")) { |
| 754 | const eq = arg.indexOf("="); |
| 755 | const name = eq === -1 ? arg.slice(2) : arg.slice(2, eq); |
| 756 | const spec = table[name]; |
| 757 | if (!spec) return { error: `unknown option '--${name}'` }; |
| 758 | if (spec.kind === "bool") { |
| 759 | if (eq !== -1) return { error: `option '--${name}' takes no value` }; |
| 760 | flags[name] = true; |
| 761 | continue; |
| 762 | } |
| 763 | // value flag |
| 764 | if (eq !== -1) { |
| 765 | flags[name] = arg.slice(eq + 1); |
| 766 | continue; |
| 767 | } |
| 768 | const next = args[i + 1]; |
| 769 | if (next === undefined) return { error: `option '--${name}' requires a value` }; |
| 770 | flags[name] = next; |
| 771 | i++; |
| 772 | continue; |
| 773 | } |
| 774 | positional.push(arg); |
| 775 | } |
| 776 | return { flags, positional }; |
| 777 | } |
no test coverage detected