Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

cliArgs.ts

76 lines2.2 KB

1export interface ParsedCliArgs {
2 readonly flags: Record<string, string | null>;
3 readonly positionals: string[];
4}
5​
6export interface ParseCliArgsOptions {
7 readonly booleanFlags?: readonly string[];
8}
9​
10/**
11 * Parse CLI-style arguments into flags and positionals.
12 *
13 * Accepts a string (split by whitespace) or a pre-split argv array.
14 * Supports `--key value`, `--key=value`, and `--flag` (boolean) syntax.
15 *
16 * parseCliArgs("")
17 * → { flags: {}, positionals: [] }
18 *
19 * parseCliArgs("--chrome")
20 * → { flags: { chrome: null }, positionals: [] }
21 *
22 * parseCliArgs("--chrome --effort high")
23 * → { flags: { chrome: null, effort: "high" }, positionals: [] }
24 *
25 * parseCliArgs("--effort=high")
26 * → { flags: { effort: "high" }, positionals: [] }
27 *
28 * parseCliArgs(["1.2.3", "--root", "/path", "--github-output"], { booleanFlags: ["github-output"] })
29 * → { flags: { root: "/path", "github-output": null }, positionals: ["1.2.3"] }
30 */
31export function parseCliArgs(
32 args: string | readonly string[],
33 options?: ParseCliArgsOptions,
34): ParsedCliArgs {
35 const tokens =
36 typeof args === "string" ? args.trim().split(/\s+/).filter(Boolean) : Array.from(args);
37 const booleanSet = options?.booleanFlags ? new Set(options.booleanFlags) : undefined;
38​
39 const flags: Record<string, string | null> = {};
40 const positionals: string[] = [];
41​
42 for (let i = 0; i < tokens.length; i++) {
43 const token = tokens[i]!;
44​
45 if (token.startsWith("--")) {
46 const rest = token.slice(2);
47 if (!rest) continue;
48​
49 // Handle --key=value syntax
50 const eqIndex = rest.indexOf("=");
51 if (eqIndex !== -1) {
52 flags[rest.slice(0, eqIndex)] = rest.slice(eqIndex + 1);
53 continue;
54 }
55​
56 // Known boolean flag — never consumes next token
57 if (booleanSet?.has(rest)) {
58 flags[rest] = null;
59 continue;
60 }
61​
62 // Handle --key value or --flag (boolean)
63 const next = tokens[i + 1];
64 if (next !== undefined && !next.startsWith("--")) {
65 flags[rest] = next;
66 i++;
67 } else {
68 flags[rest] = null;
69 }
70 } else {
71 positionals.push(token);
72 }
73 }
74​
75 return { flags, positionals };