utils/node_modules/@rushstack/ts-command-line/lib/providers/CommandLineParser.js.map
2024-02-07 01:33:07 -05:00

1 line
17 KiB
Plaintext

{"version":3,"file":"CommandLineParser.js","sourceRoot":"","sources":["../../src/providers/CommandLineParser.ts"],"names":[],"mappings":";AAAA,4FAA4F;AAC5F,2DAA2D;;;;;;AAG3D,oDAA4B;AAI5B,iFAIwC;AACxC,6EAAgG;AAChG,+DAA0D;AA6B1D;;;;;;;;;GASG;AACH,MAAsB,iBAAkB,SAAQ,2DAA4B;IAgB1E,YAAmB,OAAkC;;QACnD,KAAK,EAAE,CAAC;QAJF,cAAS,GAAY,KAAK,CAAC;QAC3B,+BAA0B,GAAY,KAAK,CAAC;QAKlD,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;QACxB,IAAI,CAAC,QAAQ,GAAG,EAAE,CAAC;QACnB,IAAI,CAAC,cAAc,GAAG,IAAI,GAAG,EAA6B,CAAC;QAE3D,IAAI,CAAC,eAAe,GAAG,IAAI,iDAAoB,CAAC;YAC9C,OAAO,EAAE,IAAI;YACb,IAAI,EAAE,IAAI,CAAC,QAAQ,CAAC,YAAY;YAChC,WAAW,EAAE,IAAI,CAAC,QAAQ,CAAC,eAAe;YAC1C,MAAM,EAAE,gBAAM,CAAC,IAAI,CACjB,MAAA,IAAI,CAAC,QAAQ,CAAC,UAAU,mCACtB,oDAAoD,IAAI,CAAC,QAAQ,CAAC,YAAY,eAAe,CAChG;SACF,CAAC,CAAC;QAEH,MAAA,IAAI,CAAC,kBAAkB,oDAAI,CAAC;IAC9B,CAAC;IAED;;OAEG;IACH,IAAW,OAAO;QAChB,OAAO,IAAI,CAAC,QAAQ,CAAC;IACvB,CAAC;IAED;;OAEG;IACI,SAAS,CAAC,MAAyB;QACxC,IAAI,CAAC,IAAI,CAAC,iBAAiB,EAAE;YAC3B,IAAI,CAAC,iBAAiB,GAAG,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC;gBAC1D,OAAO,EAAE,WAAW;gBACpB,IAAI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CAAC,EAAE;YAC7C,+CAA+C;YAC/C,MAAM,IAAI,KAAK,CAAC,oFAAoF,CAAC,CAAC;SACvG;IACH,CAAC;IAED;;;OAGG;IACO,kBAAkB;QAC1B,WAAW;QACX,OAAO,IAAI,CAAC,eAAe,CAAC;IAC9B,CAAC;IAED;;;OAGG;IACO,KAAK,CAAC,SAAS;QACvB,IAAI,IAAI,CAAC,cAAc,EAAE;YACvB,MAAM,IAAI,CAAC,cAAc,CAAC,QAAQ,EAAE,CAAC;SACtC;IACH,CAAC;CACF;AArQD,8CAqQC","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.\n// See LICENSE in the project root for license information.\n\nimport type * as argparse from 'argparse';\nimport colors from 'colors';\n\nimport type { CommandLineAction } from './CommandLineAction';\nimport type { AliasCommandLineAction } from './AliasCommandLineAction';\nimport {\n CommandLineParameterProvider,\n type IRegisterDefinedParametersState,\n type ICommandLineParserData\n} from './CommandLineParameterProvider';\nimport { CommandLineParserExitError, CustomArgumentParser } from './CommandLineParserExitError';\nimport { TabCompleteAction } from './TabCompletionAction';\n\n/**\n * Options for the {@link CommandLineParser} constructor.\n * @public\n */\nexport interface ICommandLineParserOptions {\n /**\n * The name of your tool when invoked from the command line\n */\n toolFilename: string;\n\n /**\n * General documentation that is included in the \"--help\" main page\n */\n toolDescription: string;\n\n /**\n * An optional string to append at the end of the \"--help\" main page. If not provided, an epilog\n * will be automatically generated based on the toolFilename.\n */\n toolEpilog?: string;\n\n /**\n * Set to true to auto-define a tab completion action. False by default.\n */\n enableTabCompletionAction?: boolean;\n}\n\n/**\n * The \"argparse\" library is a relatively advanced command-line parser with features such\n * as word-wrapping and intelligible error messages (that are lacking in other similar\n * libraries such as commander, yargs, and nomnom). Unfortunately, its ruby-inspired API\n * is awkward to use. The abstract base classes CommandLineParser and CommandLineAction\n * provide a wrapper for \"argparse\" that makes defining and consuming arguments quick\n * and simple, and enforces that appropriate documentation is provided for each parameter.\n *\n * @public\n */\nexport abstract class CommandLineParser extends CommandLineParameterProvider {\n /**\n * Reports which CommandLineAction was specified on the command line.\n * @remarks\n * The value will be assigned before onExecute() is invoked.\n */\n public selectedAction: CommandLineAction | undefined;\n\n private readonly _argumentParser: argparse.ArgumentParser;\n private _actionsSubParser: argparse.SubParser | undefined;\n private readonly _options: ICommandLineParserOptions;\n private readonly _actions: CommandLineAction[];\n private readonly _actionsByName: Map<string, CommandLineAction>;\n private _executed: boolean = false;\n private _tabCompleteActionWasAdded: boolean = false;\n\n public constructor(options: ICommandLineParserOptions) {\n super();\n\n this._options = options;\n this._actions = [];\n this._actionsByName = new Map<string, CommandLineAction>();\n\n this._argumentParser = new CustomArgumentParser({\n addHelp: true,\n prog: this._options.toolFilename,\n description: this._options.toolDescription,\n epilog: colors.bold(\n this._options.toolEpilog ??\n `For detailed help about a specific command, use: ${this._options.toolFilename} <command> -h`\n )\n });\n\n this.onDefineParameters?.();\n }\n\n /**\n * Returns the list of actions that were defined for this CommandLineParser object.\n */\n public get actions(): ReadonlyArray<CommandLineAction> {\n return this._actions;\n }\n\n /**\n * Defines a new action that can be used with the CommandLineParser instance.\n */\n public addAction(action: CommandLineAction): void {\n if (!this._actionsSubParser) {\n this._actionsSubParser = this._argumentParser.addSubparsers({\n metavar: '<command>',\n dest: 'action'\n });\n }\n\n action._buildParser(this._actionsSubParser);\n this._actions.push(action);\n this._actionsByName.set(action.actionName, action);\n }\n\n /**\n * Retrieves the action with the specified name. If no matching action is found,\n * an exception is thrown.\n */\n public getAction(actionName: string): CommandLineAction {\n const action: CommandLineAction | undefined = this.tryGetAction(actionName);\n if (!action) {\n throw new Error(`The action \"${actionName}\" was not defined`);\n }\n return action;\n }\n\n /**\n * Retrieves the action with the specified name. If no matching action is found,\n * undefined is returned.\n */\n public tryGetAction(actionName: string): CommandLineAction | undefined {\n return this._actionsByName.get(actionName);\n }\n\n /**\n * The program entry point will call this method to begin parsing command-line arguments\n * and executing the corresponding action.\n *\n * @remarks\n * The returned promise will never reject: If an error occurs, it will be printed\n * to stderr, process.exitCode will be set to 1, and the promise will resolve to false.\n * This simplifies the most common usage scenario where the program entry point doesn't\n * want to be involved with the command-line logic, and will discard the promise without\n * a then() or catch() block.\n *\n * If your caller wants to trap and handle errors, use {@link CommandLineParser.executeWithoutErrorHandling}\n * instead.\n *\n * @param args - the command-line arguments to be parsed; if omitted, then\n * the process.argv will be used\n */\n public async execute(args?: string[]): Promise<boolean> {\n if (this._options.enableTabCompletionAction && !this._tabCompleteActionWasAdded) {\n this.addAction(new TabCompleteAction(this.actions, this.parameters));\n this._tabCompleteActionWasAdded = true;\n }\n\n try {\n await this.executeWithoutErrorHandling(args);\n return true;\n } catch (err) {\n if (err instanceof CommandLineParserExitError) {\n // executeWithoutErrorHandling() handles the successful cases,\n // so here we can assume err has a nonzero exit code\n if (err.message) {\n // eslint-disable-next-line no-console\n console.error(err.message);\n }\n if (!process.exitCode) {\n process.exitCode = err.exitCode;\n }\n } else {\n let message: string = ((err as Error).message || 'An unknown error occurred').trim();\n\n // If the message doesn't already start with \"Error:\" then add a prefix\n if (!/^(error|internal error|warning)\\b/i.test(message)) {\n message = 'Error: ' + message;\n }\n\n // eslint-disable-next-line no-console\n console.error();\n // eslint-disable-next-line no-console\n console.error(colors.red(message));\n\n if (!process.exitCode) {\n process.exitCode = 1;\n }\n }\n\n return false;\n }\n }\n\n /**\n * This is similar to {@link CommandLineParser.execute}, except that execution errors\n * simply cause the promise to reject. It is the caller's responsibility to trap\n */\n public async executeWithoutErrorHandling(args?: string[]): Promise<void> {\n try {\n if (this._executed) {\n // In the future we could allow the same parser to be invoked multiple times\n // with different arguments. We'll do that work as soon as someone encounters\n // a real world need for it.\n throw new Error('execute() was already called for this parser instance');\n }\n this._executed = true;\n\n this._validateDefinitions();\n\n // Register the parameters before we print help or parse the CLI\n const initialState: IRegisterDefinedParametersState = {\n parentParameterNames: new Set()\n };\n this._registerDefinedParameters(initialState);\n\n if (!args) {\n // 0=node.exe, 1=script name\n args = process.argv.slice(2);\n }\n if (this.actions.length > 0) {\n if (args.length === 0) {\n // Parsers that use actions should print help when 0 args are provided. Allow\n // actionless parsers to continue on zero args.\n this._argumentParser.printHelp();\n return;\n }\n // Alias actions may provide a list of default params to add after the action name.\n // Since we don't know which params are required and which are optional, perform a\n // manual search for the action name to obtain the default params and insert them if\n // any are found. We will guess that the action name is the first arg that doesn't\n // start with a hyphen.\n const actionNameIndex: number | undefined = args.findIndex((x) => !x.startsWith('-'));\n if (actionNameIndex !== undefined) {\n const actionName: string = args[actionNameIndex];\n const action: CommandLineAction | undefined = this.tryGetAction(actionName);\n const aliasAction: AliasCommandLineAction | undefined = action as AliasCommandLineAction;\n if (aliasAction?.defaultParameters?.length) {\n const insertIndex: number = actionNameIndex + 1;\n args = args.slice(0, insertIndex).concat(aliasAction.defaultParameters, args.slice(insertIndex));\n }\n }\n }\n\n const data: ICommandLineParserData = this._argumentParser.parseArgs(args);\n\n this._processParsedData(this._options, data);\n\n this.selectedAction = this.tryGetAction(data.action);\n if (this.actions.length > 0 && !this.selectedAction) {\n const actions: string[] = this.actions.map((x) => x.actionName);\n throw new Error(`An action must be specified (${actions.join(', ')})`);\n }\n\n this.selectedAction?._processParsedData(this._options, data);\n await this.onExecute();\n } catch (err) {\n if (err instanceof CommandLineParserExitError) {\n if (!err.exitCode) {\n // non-error exit modeled using exception handling\n if (err.message) {\n // eslint-disable-next-line no-console\n console.log(err.message);\n }\n\n return;\n }\n }\n\n throw err;\n }\n }\n\n /** @internal */\n public _registerDefinedParameters(state: IRegisterDefinedParametersState): void {\n super._registerDefinedParameters(state);\n\n const { parentParameterNames } = state;\n const updatedParentParameterNames: Set<string> = new Set([\n ...parentParameterNames,\n ...this._registeredParameterParserKeysByName.keys()\n ]);\n\n const parentState: IRegisterDefinedParametersState = {\n ...state,\n parentParameterNames: updatedParentParameterNames\n };\n for (const action of this._actions) {\n action._registerDefinedParameters(parentState);\n }\n }\n\n private _validateDefinitions(): void {\n if (this.remainder && this.actions.length > 0) {\n // This is apparently not supported by argparse\n throw new Error('defineCommandLineRemainder() cannot be called for a CommandLineParser with actions');\n }\n }\n\n /**\n * {@inheritDoc CommandLineParameterProvider._getArgumentParser}\n * @internal\n */\n protected _getArgumentParser(): argparse.ArgumentParser {\n // override\n return this._argumentParser;\n }\n\n /**\n * This hook allows the subclass to perform additional operations before or after\n * the chosen action is executed.\n */\n protected async onExecute(): Promise<void> {\n if (this.selectedAction) {\n await this.selectedAction._execute();\n }\n }\n}\n"]}