import type { Config } from "@react-native-community/cli-types"; import { Command } from "commander"; import * as path from "node:path"; import { loadContextForCommand, uniquify } from "./context.ts"; import { findExternalCommands } from "./externalCommands.ts"; type CommandOption = Required["options"][number]; function parseDefaultValue( defaultValue: CommandOption["default"], context: Config ): boolean | string | string[] | undefined { const value = typeof defaultValue === "function" ? defaultValue(context) : defaultValue; return typeof value === "number" ? value.toString() : value; } export async function main() { const [, , userCommand] = process.argv; const context = await loadContextForCommand(userCommand); // Commander throws if a command name is registered more than once const allCommands = uniquify( context.commands.concat(findExternalCommands(context)) ); const program = new Command(path.basename(__filename, ".js")); for (const info of allCommands) { const { name, description, detached, func } = info; const command = program.command(name).description(description ?? name); if (detached) { command.action((args, command) => func(command.args, args, context)); } else { command.action((args, command) => func(command.args, context, args)); } // Accessing `options` may be expensive for some commands (e.g., it may // resolve and load other packages). Since only the invoked command's // options are needed to correctly parse `process.argv`, skip this step // for all other commands. if (name !== userCommand) { continue; } const options = info.options ?? []; for (const { name, description, parse, default: defaultValue } of options) { const value = parseDefaultValue(defaultValue, context); if (parse) { command.option(name, description ?? name, parse, value); } else { command.option(name, description, value); } } } program.parse(); }