/** * Minimal shared argv parser for gmail CLI commands. * Supports --flag value, --flag=value, and boolean --flags. */ export function parseArgv(argv, { booleans = [], strings = [], multi = [] } = {}) { const out = { _: [], help: false, }; for (const key of booleans) out[key] = false; for (const key of strings) out[key] = null; for (const key of multi) out[key] = []; for (let i = 0; i < argv.length; i++) { const a = argv[i]; if (a === "--help" || a === "-h") { out.help = true; continue; } if (!a.startsWith("--")) { out._.push(a); continue; } const eq = a.indexOf("="); let name; let rawValue; if (eq >= 0) { name = a.slice(2, eq); rawValue = a.slice(eq + 1); } else { name = a.slice(2); rawValue = undefined; } const camel = name.replace(/-([a-z])/g, (_, c) => c.toUpperCase()); if (booleans.includes(camel) || booleans.includes(name)) { const key = booleans.includes(camel) ? camel : name; out[key] = true; continue; } if (multi.includes(camel) || multi.includes(name)) { const key = multi.includes(camel) ? camel : name; const value = rawValue !== undefined ? rawValue : argv[++i]; if (value == null) continue; out[key].push( ...String(value) .split(",") .map((s) => s.trim()) .filter(Boolean), ); continue; } if (strings.includes(camel) || strings.includes(name)) { const key = strings.includes(camel) ? camel : name; out[key] = rawValue !== undefined ? rawValue : argv[++i]; continue; } // Unknown flag: treat as string if next token looks like a value if (rawValue !== undefined) { out[camel] = rawValue; } else if (argv[i + 1] && !argv[i + 1].startsWith("--")) { out[camel] = argv[++i]; } else { out[camel] = true; } } return out; } export function requireReason(args, action) { const reason = (args.reason || "").trim(); if (!reason) { return { ok: false, error: `--reason is required for ${action}`, }; } return { ok: true, reason }; } export function parseIds(args) { const fromFlag = Array.isArray(args.ids) ? args.ids : []; const fromPositional = args._ || []; const joined = [...fromFlag, ...fromPositional] .flatMap((s) => String(s).split(",")) .map((s) => s.trim()) .filter(Boolean); return [...new Set(joined)]; }