167 lines
6.9 KiB
TypeScript
167 lines
6.9 KiB
TypeScript
import type { CliParsedArgs, OutputOptions } from "./types.js";
|
||
|
||
import { commandFlags, GLOBAL_FLAGS, localCommandFlags, type FlagKind } from "./command-metadata.js";
|
||
import { usageError } from "./errors.js";
|
||
|
||
function explicitBoolean(value: string | undefined): boolean | undefined {
|
||
if (value === undefined) return undefined;
|
||
if (value.toLowerCase() === "true" || value === "1") return true;
|
||
if (value.toLowerCase() === "false" || value === "0") return false;
|
||
}
|
||
|
||
// Space-separated numeric tokens may be positional IDs. Numeric booleans use =0/=1.
|
||
function separatedBoolean(value: string | undefined): boolean | undefined {
|
||
return value && /^(true|false)$/i.test(value) ? explicitBoolean(value) : undefined;
|
||
}
|
||
|
||
function findContext(raw: string[], areaOverride?: string): { area?: string; action?: string } {
|
||
let area = areaOverride;
|
||
let action: string | undefined;
|
||
for (let i = 0; i < raw.length; i++) {
|
||
const arg = raw[i];
|
||
if (arg === "--") break;
|
||
if (arg.startsWith("-") && arg !== "-") {
|
||
const key = arg.replace(/^-+/, "").split("=")[0];
|
||
const flags = commandFlags(area, action);
|
||
const kind = flags[key] || flags[Object.keys(flags).find(k => k.toLowerCase() === key.toLowerCase()) || ""];
|
||
if (!arg.includes("=") && ((kind === "value" && raw[i + 1] && !raw[i + 1].startsWith("-")) || (kind !== "value" && separatedBoolean(raw[i + 1]) !== undefined))) i++;
|
||
continue;
|
||
}
|
||
if (!area) area = arg.toLowerCase();
|
||
else { action = arg.toLowerCase(); break; }
|
||
}
|
||
return { area, action };
|
||
}
|
||
|
||
function distance(left: string, right: string): number {
|
||
let previous = Array.from({ length: right.length + 1 }, (_, i) => i);
|
||
for (let i = 0; i < left.length; i++) {
|
||
const row = [i + 1];
|
||
for (let j = 0; j < right.length; j++) row.push(Math.min(row[j] + 1, previous[j + 1] + 1, previous[j] + Number(left[i] !== right[j])));
|
||
previous = row;
|
||
}
|
||
return previous[right.length];
|
||
}
|
||
|
||
/** Read just the global JSON switch, even when strict parsing will fail. */
|
||
export function isJsonRequested(raw: string[]): boolean {
|
||
let enabled = false;
|
||
for (let i = 0; i < raw.length; i++) {
|
||
const arg = raw[i];
|
||
if (arg === "--") break;
|
||
if (/^--(?:json|j)(?:=|$)/i.test(arg) || /^-j$/i.test(arg)) {
|
||
const inline = arg.includes("=") ? arg.slice(arg.indexOf("=") + 1) : undefined;
|
||
enabled = (inline !== undefined ? explicitBoolean(inline) : separatedBoolean(raw[i + 1])) ?? true;
|
||
}
|
||
}
|
||
return enabled;
|
||
}
|
||
|
||
export function parseArgs(rawArgs: string[], areaOverride?: string): CliParsedArgs {
|
||
const options: Record<string, string | boolean | number> = Object.create(null);
|
||
const positional: string[] = [];
|
||
const context = findContext(rawArgs, areaOverride);
|
||
const flags = commandFlags(context.area, context.action);
|
||
const localFlags = localCommandFlags(context.area, context.action);
|
||
|
||
for (let i = 0; i < rawArgs.length; i++) {
|
||
const arg = rawArgs[i];
|
||
if (arg === "--") { positional.push(...rawArgs.slice(i + 1)); break; }
|
||
if (!arg.startsWith("-") || arg === "-") { positional.push(arg); continue; }
|
||
|
||
const body = arg.replace(/^-+/, "");
|
||
const eqIdx = body.indexOf("=");
|
||
const inputKey = eqIdx === -1 ? body : body.slice(0, eqIdx);
|
||
const key = Object.hasOwn(flags, inputKey) ? inputKey : Object.keys(flags).find(k => k.toLowerCase() === inputKey.toLowerCase());
|
||
if (!key) {
|
||
const nearest = Object.keys(flags).sort((a, b) => distance(inputKey, a) - distance(inputKey, b))[0];
|
||
const suggestion = nearest && distance(inputKey, nearest) <= Math.max(1, Math.floor(inputKey.length / 3)) ? `。是否想用 --${nearest}?` : "";
|
||
throw usageError(`未知选项: ${arg.split("=")[0]}${suggestion}`);
|
||
}
|
||
const globalPrefix = positional.length === 0 && Object.hasOwn(GLOBAL_FLAGS, key);
|
||
const kind: FlagKind = globalPrefix ? GLOBAL_FLAGS[key] : flags[key];
|
||
const inline = eqIdx === -1 ? undefined : body.slice(eqIdx + 1);
|
||
const next = rawArgs[i + 1];
|
||
let value: string | boolean;
|
||
if (kind === "boolean") {
|
||
if (inline !== undefined) {
|
||
const parsed = explicitBoolean(inline);
|
||
if (parsed === undefined) throw usageError(`选项 --${key} 需要布尔值 true/false 或 1/0`);
|
||
value = parsed;
|
||
} else if (separatedBoolean(next) !== undefined) {
|
||
value = separatedBoolean(next)!;
|
||
i++;
|
||
} else value = true;
|
||
} else if (inline !== undefined) {
|
||
if (!inline.length) throw usageError(`选项 --${key} 缺少值`);
|
||
value = kind === "boolean-or-value" ? explicitBoolean(inline) ?? inline : inline;
|
||
} else if (next !== undefined && next !== "--" && (!next.startsWith("-") || /^-\d+(?:\.\d+)?$/.test(next))) {
|
||
value = kind === "boolean-or-value" ? separatedBoolean(next) ?? next : next;
|
||
i++;
|
||
} else if (kind === "boolean-or-value") value = true;
|
||
else throw usageError(`选项 --${key} 缺少值`);
|
||
|
||
options[key] = value;
|
||
// Preserve command-specific short names; global short names also get their semantic key.
|
||
const globalNames: Record<string, string> = { h: "help", "?": "help", j: "json", v: "version", V: "version", c: "corp", o: "outputFile" };
|
||
if (globalNames[key] && (globalPrefix || !Object.hasOwn(localFlags, key) || key === "j" || key === "o" || key === "V")) options[globalNames[key]] = value;
|
||
}
|
||
return { area: positional[0]?.toLowerCase(), action: positional[1]?.toLowerCase(), args: positional.slice(2), positional, options, raw: rawArgs };
|
||
}
|
||
|
||
export function stringOption(
|
||
options: Record<string, unknown>,
|
||
keys: string[],
|
||
fallback?: string
|
||
): string | undefined {
|
||
for (const k of keys) {
|
||
if (!Object.hasOwn(options, k)) continue;
|
||
const val = options[k];
|
||
if (typeof val === "string" && val.length > 0) return val;
|
||
}
|
||
return fallback;
|
||
}
|
||
|
||
export function booleanOption(
|
||
options: Record<string, unknown>,
|
||
keys: string[],
|
||
fallback: boolean = false
|
||
): boolean {
|
||
for (const k of keys) {
|
||
if (!Object.hasOwn(options, k)) continue;
|
||
const val = options[k];
|
||
if (typeof val === "boolean") return val;
|
||
if (typeof val === "string") {
|
||
const lower = val.toLowerCase();
|
||
if (lower === "true" || lower === "1") return true;
|
||
if (lower === "false" || lower === "0") return false;
|
||
}
|
||
}
|
||
return fallback;
|
||
}
|
||
|
||
export function numberOption(
|
||
options: Record<string, unknown>,
|
||
keys: string[],
|
||
fallback?: number
|
||
): number | undefined {
|
||
for (const k of keys) {
|
||
if (!Object.hasOwn(options, k)) continue;
|
||
const val = options[k];
|
||
if (typeof val === "number" && !Number.isNaN(val)) return val;
|
||
if (typeof val === "string") {
|
||
const parsed = Number(val);
|
||
if (!Number.isNaN(parsed)) return parsed;
|
||
}
|
||
}
|
||
return fallback;
|
||
}
|
||
|
||
export function outputOptions(options: Record<string, unknown>): OutputOptions {
|
||
return {
|
||
allowFull: booleanOption(options, ["full", "allow-full", "allowFull"]),
|
||
outputFile: stringOption(options, ["output-file", "outputFile", "o"]),
|
||
summary: booleanOption(options, ["summary"]),
|
||
};
|
||
}
|