Files
gmail-hook/apps/watcher/src/cli/parse-args.js
T
nsrbandCursor f270f531ea feat(watcher): add agent Gmail CLI with audit and defaults
Provide list/read/summarize plus reason-gated archive, label, draft, and forward-as-draft, with SQLite audit logging and default-mailbox resolution.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-22 10:09:25 +07:00

96 lines
2.4 KiB
JavaScript

/**
* 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)];
}