Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144import { parseArgs } from "node:util";
import { FLAGS, flagsFor, type FlagSpec } from "./flags.ts";import { findCommand } from "../commands/registry.ts";import { isKnownLanguage, LANGUAGE_NAMES } from "../config/data.ts";import type { AnyCommand, ResolvedFlags } from "../commands/types.ts";
export interface ParsedArgv { /** Command word exactly as typed, or `null` when the user gave none. */ command: string | null; /** The registered command, or `null` when the word is not one. */ resolved: AnyCommand | null; /** The ROM path for `"rom"` commands, the extract db path for `"db"` ones. */ path: string; /** Positionals after the ROM path - `text` takes text ids here. */ args: string[]; flags: ResolvedFlags; /** `--help` / `-h` was given. Checked before the ROM is loaded. */ help: boolean;}
type OptionConfig = Record<string, { type: "string" | "boolean"; short?: string }>;
/** * `parseArgs` config built from **every** flag, not one command's set: * tokenising argv must not depend on which command it turns out to be (whether * `--out` swallows the next token depends only on its type). Which flags a * command may use is enforced separately from the parse's token list - see * `firstUnknownOption`. */function optionConfig(flags: readonly FlagSpec[]): OptionConfig { const options: OptionConfig = {}; for (const flag of flags) { options[flag.name] = flag.short === undefined ? { type: flag.type } : { type: flag.type, short: flag.short }; } return options;}
/** * The first option `parseArgs` saw that the command does not accept, as the * user typed it. * * Membership only: the tokens come from `parseArgs`, so `--` (an * `option-terminator`, not an option), `--out -x` (one option token with the * value `-x`) and `--foo=bar` are all already classified the way the standard * says they should be. Nothing here re-scans argv. */function firstUnknownOption( tokens: readonly { kind: string; name?: string; rawName?: string; }[], accepted: readonly FlagSpec[],): string | null { const long = new Set(accepted.map((f) => f.name)); const short = new Set(accepted.flatMap((f) => (f.short === undefined ? [] : [f.short])));
for (const token of tokens) { if (token.kind !== "option") continue; const name = token.name ?? ""; if (name.length === 0) continue; const known = name.length > 1 ? long.has(name) : short.has(name); if (!known) return token.rawName ?? name; } return null;}
/** * Parse `argv` into a command, a ROM path, trailing positionals and flags. * * Throws a plain `Error` for input the user got wrong (unknown option, unknown * `--lang`, a stray positional); the caller turns that into a message plus * exit code 2. * * One permissive parse plus a membership check on its tokens, so that the * standard `--` terminator is not reported as an option and the value of * `--out` is not mistaken for a flag. */export function parseArgv(argv: readonly string[]): ParsedArgv { const { values, positionals, tokens } = parseArgs({ args: [...argv], allowPositionals: true, strict: false, tokens: true, options: optionConfig(FLAGS), });
const command = positionals[0] ?? null; const resolved = command === null ? null : (findCommand(command) ?? null); const accepted = flagsFor(resolved); // Only worth complaining about once we know the command is real: otherwise // the "unknown command" message is the more useful one. if (resolved !== null) { const bad = firstUnknownOption(tokens, accepted); if (bad !== null) throw new Error(`unknown option "${bad}" for "${resolved.name}"`);
// A command that documents no trailing positionals must not quietly accept // them, or a mistyped flag or a forgotten argument goes unnoticed. // Everything after `--` lands here too, which is what the terminator is for. const extra = positionals.slice(2); if (extra.length > 0 && resolved.extraArgs === undefined) { const input = resolved.input === "db" ? "<file.db>" : "<rom.gba>"; throw new Error( `"${resolved.name}" takes no extra arguments, but got: ${extra.join(" ")}\n` + `Usage: fe-rom ${resolved.name} ${input} [options]`, ); } }
const str = (key: string): string | undefined => { const value = values[key]; return typeof value === "string" ? value : undefined; };
// Hoisted so `exactOptionalPropertyTypes` sees a narrowed `string`, not // `string | undefined` re-widened by the second call. const out = str("out"); const range = str("range"); const lang = str("lang"); const actorLevel = str("actor-level"); const actorClassPower = str("actor-class-power"); if (lang !== undefined && !isKnownLanguage(lang)) { throw new Error(`--lang expects one of ${LANGUAGE_NAMES.join(", ")}, got "${lang}"`); }
return { command, resolved, path: positionals[1] ?? "", args: positionals.slice(2), help: values.help === true, flags: { ...(out === undefined ? {} : { out }), ...(range === undefined ? {} : { range }), ...(lang === undefined ? {} : { lang }), ...(actorLevel === undefined ? {} : { actorLevel }), ...(actorClassPower === undefined ? {} : { actorClassPower }), ...(values["actor-promoted"] === true ? { actorPromoted: true } : {}), }, };}