Files
openclaw/src/cli/program/json-mode.ts
T
2026-07-13 05:05:31 -07:00

46 lines
1.6 KiB
TypeScript

// JSON-mode metadata for Commander commands; distinguishes JSON output from parse-only flags.
import type { Command } from "commander";
import { hasFlag } from "../argv.js";
const jsonModeSymbol = Symbol("openclaw.cli.jsonMode");
type JsonMode = "output" | "parse-only";
type JsonModeCommand = Command & {
[jsonModeSymbol]?: JsonMode;
};
function commandDefinesJsonOption(command: Command): boolean {
return command.options.some((option) => option.long === "--json");
}
function getDeclaredCommandJsonMode(command: Command): JsonMode | null {
for (let current: Command | null = command; current; current = current.parent ?? null) {
const metadata = (current as JsonModeCommand)[jsonModeSymbol];
if (metadata) {
return metadata;
}
if (commandDefinesJsonOption(current)) {
return "output";
}
}
return null;
}
/** Mark a command as having a special JSON mode beyond ordinary JSON output. */
export function setCommandJsonMode(command: Command, mode: JsonMode): Command {
(command as JsonModeCommand)[jsonModeSymbol] = mode;
return command;
}
function getCommandJsonMode(command: Command, argv: string[] = process.argv): JsonMode | null {
if (command.optsWithGlobals<{ json?: unknown }>().json !== true && !hasFlag(argv, "--json")) {
return null;
}
return getDeclaredCommandJsonMode(command);
}
/** Return true only when `--json` selects machine-readable command output. */
export function isCommandJsonOutputMode(command: Command, argv: string[] = process.argv): boolean {
return getCommandJsonMode(command, argv) === "output";
}