node_modules ignore

This commit is contained in:
oier committed 2025-05-08 23:43:47 +02:00
1 parent e19d52f172
commit 4574544c9f
65041 files changed
+10593536

No files matched your search

@@ -0,0 +1,60 @@
import { CommandLineAction } from './CommandLineAction';
import type { ICommandLineParserData, IRegisterDefinedParametersState } from './CommandLineParameterProvider';
import type { ICommandLineParserOptions } from './CommandLineParser';
/**
* Options for the AliasCommandLineAction constructor.
* @public
*/
export interface IAliasCommandLineActionOptions {
/**
* The name of your tool when invoked from the command line. Used for generating help text.
*/
toolFilename: string;
/**
* The name of the alias. For example, if the tool is called "example",
* then the "build" alias might be invoked as: "example build -q --some-other-option"
*/
aliasName: string;
/**
* A list of default parameters to pass to the target action.
*/
defaultParameters?: string[];
/**
* The action that this alias invokes.
*/
targetAction: CommandLineAction;
}
/**
* Represents a sub-command that is part of the CommandLineParser command line.
* The sub-command is an alias for another existing action.
*
* The alias name should be comprised of lower case words separated by hyphens
* or colons. The name should include an English verb (e.g. "deploy"). Use a
* hyphen to separate words (e.g. "upload-docs").
*
* @public
*/
export declare class AliasCommandLineAction extends CommandLineAction {
/**
* The action that this alias invokes.
*/
readonly targetAction: CommandLineAction;
/**
* A list of default arguments to pass to the target action.
*/
readonly defaultParameters: ReadonlyArray<string>;
private _parameterKeyMap;
constructor(options: IAliasCommandLineActionOptions);
/** @internal */
_registerDefinedParameters(state: IRegisterDefinedParametersState): void;
/**
* {@inheritdoc CommandLineParameterProvider._processParsedData}
* @internal
*/
_processParsedData(parserOptions: ICommandLineParserOptions, data: ICommandLineParserData): void;
/**
* Executes the target action.
*/
protected onExecute(): Promise<void>;
}
//# sourceMappingURL=AliasCommandLineAction.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"AliasCommandLineAction.d.ts","sourceRoot":"","sources":["../../src/providers/AliasCommandLineAction.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAMxD,OAAO,KAAK,EAAE,sBAAsB,EAAE,+BAA+B,EAAE,MAAM,gCAAgC,CAAC;AAC9G,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,qBAAqB,CAAC;AAErE;;;GAGG;AACH,MAAM,WAAW,8BAA8B;IAC7C;;OAEG;IACH,YAAY,EAAE,MAAM,CAAC;IAErB;;;OAGG;IACH,SAAS,EAAE,MAAM,CAAC;IAElB;;OAEG;IACH,iBAAiB,CAAC,EAAE,MAAM,EAAE,CAAC;IAE7B;;OAEG;IACH,YAAY,EAAE,iBAAiB,CAAC;CACjC;AAED;;;;;;;;;GASG;AACH,qBAAa,sBAAuB,SAAQ,iBAAiB;IAC3D;;OAEG;IACH,SAAgB,YAAY,EAAE,iBAAiB,CAAC;IAEhD;;OAEG;IACH,SAAgB,iBAAiB,EAAE,aAAa,CAAC,MAAM,CAAC,CAAC;IAEzD,OAAO,CAAC,gBAAgB,CAAkC;gBAEvC,OAAO,EAAE,8BAA8B;IAoB1D,gBAAgB;IACT,0BAA0B,CAAC,KAAK,EAAE,+BAA+B,GAAG,IAAI;IA4E/E;;;OAGG;IACI,kBAAkB,CAAC,aAAa,EAAE,yBAAyB,EAAE,IAAI,EAAE,sBAAsB,GAAG,IAAI;IAmBvG;;OAEG;cACa,SAAS,IAAI,OAAO,CAAC,IAAI,CAAC;CAG3C"}
@@ -0,0 +1,168 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.AliasCommandLineAction = void 0;
const argparse = __importStar(require("argparse"));
const CommandLineAction_1 = require("./CommandLineAction");
const BaseClasses_1 = require("../parameters/BaseClasses");
/**
* Represents a sub-command that is part of the CommandLineParser command line.
* The sub-command is an alias for another existing action.
*
* The alias name should be comprised of lower case words separated by hyphens
* or colons. The name should include an English verb (e.g. "deploy"). Use a
* hyphen to separate words (e.g. "upload-docs").
*
* @public
*/
class AliasCommandLineAction extends CommandLineAction_1.CommandLineAction {
constructor(options) {
const toolFilename = options.toolFilename;
const targetActionName = options.targetAction.actionName;
const defaultParametersString = (options.defaultParameters || []).join(' ');
const summary = `An alias for "${toolFilename} ${targetActionName}${defaultParametersString ? ` ${defaultParametersString}` : ''}".`;
super({
actionName: options.aliasName,
summary,
documentation: `${summary} For more information on the aliased command, use ` +
`"${toolFilename} ${targetActionName} --help".`
});
this._parameterKeyMap = new Map();
this.targetAction = options.targetAction;
this.defaultParameters = options.defaultParameters || [];
}
/** @internal */
_registerDefinedParameters(state) {
/* override */
// All parameters are going to be defined by the target action. Re-use the target action parameters
// for this action.
for (const parameter of this.targetAction.parameters) {
const { kind, longName, shortName } = parameter;
let aliasParameter;
const nameOptions = {
parameterLongName: longName,
parameterShortName: shortName
};
switch (kind) {
case BaseClasses_1.CommandLineParameterKind.Choice:
aliasParameter = this.defineChoiceParameter({
...nameOptions,
...parameter,
alternatives: [...parameter.alternatives]
});
break;
case BaseClasses_1.CommandLineParameterKind.ChoiceList:
aliasParameter = this.defineChoiceListParameter({
...nameOptions,
...parameter,
alternatives: [...parameter.alternatives]
});
break;
case BaseClasses_1.CommandLineParameterKind.Flag:
aliasParameter = this.defineFlagParameter({ ...nameOptions, ...parameter });
break;
case BaseClasses_1.CommandLineParameterKind.Integer:
aliasParameter = this.defineIntegerParameter({ ...nameOptions, ...parameter });
break;
case BaseClasses_1.CommandLineParameterKind.IntegerList:
aliasParameter = this.defineIntegerListParameter({ ...nameOptions, ...parameter });
break;
case BaseClasses_1.CommandLineParameterKind.String:
aliasParameter = this.defineStringParameter({ ...nameOptions, ...parameter });
break;
case BaseClasses_1.CommandLineParameterKind.StringList:
aliasParameter = this.defineStringListParameter({ ...nameOptions, ...parameter });
break;
default:
throw new Error(`Unsupported parameter kind: ${kind}`);
}
// We know the parserKey is defined because the underlying _defineParameter method sets it,
// and all parameters that we have access to have already been defined.
this._parameterKeyMap.set(aliasParameter._parserKey, parameter._parserKey);
}
// We also need to register the remainder parameter if the target action has one. The parser
// key for this parameter is constant.
if (this.targetAction.remainder) {
this.defineCommandLineRemainder(this.targetAction.remainder);
this._parameterKeyMap.set(argparse.Const.REMAINDER, argparse.Const.REMAINDER);
}
// Finally, register the parameters with the parser. We need to make sure that the target action
// is registered, since we need to re-use its parameters, and ambiguous parameters are discovered
// during registration. This will no-op if the target action is already registered.
this.targetAction._registerDefinedParameters(state);
super._registerDefinedParameters(state);
// We need to re-map the ambiguous parameters after they are defined by calling
// super._registerDefinedParameters()
for (const [ambiguousParameterName, parserKey] of this._ambiguousParameterParserKeysByName) {
const targetParserKey = this.targetAction._ambiguousParameterParserKeysByName.get(ambiguousParameterName);
// If we have a mapping for the specified key, then use it. Otherwise, use the key as-is.
if (targetParserKey) {
this._parameterKeyMap.set(parserKey, targetParserKey);
}
}
}
/**
* {@inheritdoc CommandLineParameterProvider._processParsedData}
* @internal
*/
_processParsedData(parserOptions, data) {
// Re-map the parsed data to the target action's parameters and execute the target action processor.
const targetData = {
action: this.targetAction.actionName,
aliasAction: data.action,
aliasDocumentation: this.documentation
};
for (const [key, value] of Object.entries(data)) {
// If we have a mapping for the specified key, then use it. Otherwise, use the key as-is.
// Skip over the action key though, since we've already re-mapped it to "aliasAction"
if (key === 'action') {
continue;
}
const targetKey = this._parameterKeyMap.get(key);
targetData[targetKey !== null && targetKey !== void 0 ? targetKey : key] = value;
}
this.targetAction._processParsedData(parserOptions, targetData);
}
/**
* Executes the target action.
*/
async onExecute() {
await this.targetAction._executeAsync();
}
}
exports.AliasCommandLineAction = AliasCommandLineAction;
//# sourceMappingURL=AliasCommandLineAction.js.map
@@ -0,0 +1 @@
{"version":3,"file":"AliasCommandLineAction.js","sourceRoot":"","sources":["../../src/providers/AliasCommandLineAction.ts"],"names":[],"mappings":";AAAA,4FAA4F;AAC5F,2DAA2D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAE3D,mDAAqC;AAErC,2DAAwD;AACxD,2DAImC;AA+BnC;;;;;;;;;GASG;AACH,MAAa,sBAAuB,SAAQ,qCAAiB;IAa3D,YAAmB,OAAuC;QACxD,MAAM,YAAY,GAAW,OAAO,CAAC,YAAY,CAAC;QAClD,MAAM,gBAAgB,GAAW,OAAO,CAAC,YAAY,CAAC,UAAU,CAAC;QACjE,MAAM,uBAAuB,GAAW,CAAC,OAAO,CAAC,iBAAiB,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QACpF,MAAM,OAAO,GAAW,iBAAiB,YAAY,IAAI,gBAAgB,GACvE,uBAAuB,CAAC,CAAC,CAAC,IAAI,uBAAuB,EAAE,CAAC,CAAC,CAAC,EAC5D,IAAI,CAAC;QAEL,KAAK,CAAC;YACJ,UAAU,EAAE,OAAO,CAAC,SAAS;YAC7B,OAAO;YACP,aAAa,EACX,GAAG,OAAO,oDAAoD;gBAC9D,IAAI,YAAY,IAAI,gBAAgB,WAAW;SAClD,CAAC,CAAC;QAhBG,qBAAgB,GAAwB,IA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EAAE,CAAC;YAC3F,MAAM,eAAe,GACnB,IAAI,CAAC,YAAY,CAAC,mCAAmC,CAAC,GAAG,CAAC,sBAAsB,CAAC,CAAC;YAEpF,yFAAyF;YACzF,IAAI,eAAe,EAAE,CAAC;gBACpB,IAAI,CAAC,gBAAgB,CAAC,GAAG,CAAC,SAAS,EAAE,eAAe,CAAC,CAAC;YACxD,CAAC;QACH,CAAC;IACH,CAAC;IAED;;;OAGG;IACI,kBAAkB,CAAC,aAAwC,EAAE,IAA4B;QAC9F,oGAAoG;QACpG,MAAM,UAAU,GAA2B;YACzC,MAAM,EAAE,IAAI,CAAC,YAAY,CAAC,UAAU;YACpC,WAAW,EAAE,IAAI,CAAC,MAAM;YACxB,kBAAkB,EAAE,IAAI,CAAC,aAAa;SACvC,CAAC;QACF,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC;YAChD,yFAAyF;YACzF,qFAAqF;YACrF,IAAI,GAAG,KAAK,QAAQ,EAAE,CAAC;gBACrB,SAAS;YACX,CAAC;YACD,MAAM,SAAS,GAAuB,IAAI,CAAC,gBAAgB,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;YACrE,UAAU,CAAC,SAAS,aAAT,SAAS,cAAT,SAAS,GAAI,GAAG,CAAC,GAAG,KAAK,CAAC;QACvC,CAAC;QACD,IAAI,CAAC,YAAY,CAAC,kBAAkB,CAAC,aAAa,EAAE,UAAU,CAAC,CAAC;IAClE,CAAC;IAED;;OAEG;IACO,KAAK,CAAC,SAAS;QACvB,MAAM,IAAI,CAAC,YAAY,CAAC,aAAa,EAAE,CAAC;IAC1C,CAAC;CACF;AA3ID,wDA2IC","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 * as argparse from 'argparse';\n\nimport { CommandLineAction } from './CommandLineAction';\nimport {\n CommandLineParameterKind,\n type CommandLineParameterBase,\n type CommandLineParameter\n} from '../parameters/BaseClasses';\nimport type { ICommandLineParserData, IRegisterDefinedParametersState } from './CommandLineParameterProvider';\nimport type { ICommandLineParserOptions } from './CommandLineParser';\n\n/**\n * Options for the AliasCommandLineAction constructor.\n * @public\n */\nexport interface IAliasCommandLineActionOptions {\n /**\n * The name of your tool when invoked from the command line. Used for generating help text.\n */\n toolFilename: string;\n\n /**\n * The name of the alias. For example, if the tool is called \"example\",\n * then the \"build\" alias might be invoked as: \"example build -q --some-other-option\"\n */\n aliasName: string;\n\n /**\n * A list of default parameters to pass to the target action.\n */\n defaultParameters?: string[];\n\n /**\n * The action thLine truncated
@@ -0,0 +1,69 @@
import type * as argparse from 'argparse';
import { CommandLineParameterProvider } from './CommandLineParameterProvider';
/**
* Options for the CommandLineAction constructor.
* @public
*/
export interface ICommandLineActionOptions {
/**
* The name of the action. For example, if the tool is called "example",
* then the "build" action might be invoked as: "example build -q --some-other-option"
*/
actionName: string;
/**
* A quick summary that is shown on the main help page, which is displayed
* by the command "example --help"
*/
summary: string;
/**
* A detailed description that is shown on the action help page, which is displayed
* by the command "example build --help", e.g. for actionName="build".
*/
documentation: string;
}
/**
* Represents a sub-command that is part of the CommandLineParser command line.
* Applications should create subclasses of CommandLineAction corresponding to
* each action that they want to expose.
*
* The action name should be comprised of lower case words separated by hyphens
* or colons. The name should include an English verb (e.g. "deploy"). Use a
* hyphen to separate words (e.g. "upload-docs"). A group of related commands
* can be prefixed with a colon (e.g. "docs:generate", "docs:deploy",
* "docs:serve", etc).
*
* @public
*/
export declare abstract class CommandLineAction extends CommandLineParameterProvider {
/** {@inheritDoc ICommandLineActionOptions.actionName} */
readonly actionName: string;
/** {@inheritDoc ICommandLineActionOptions.summary} */
readonly summary: string;
/** {@inheritDoc ICommandLineActionOptions.documentation} */
readonly documentation: string;
private _argumentParser;
constructor(options: ICommandLineActionOptions);
/**
* This is called internally by CommandLineParser.addAction()
* @internal
*/
_buildParser(actionsSubParser: argparse.SubParser): void;
/**
* Invoked by CommandLineParser.onExecute().
* @internal
*/
_executeAsync(): Promise<void>;
/**
* {@inheritDoc CommandLineParameterProvider._getArgumentParser}
* @internal
*/
_getArgumentParser(): argparse.ArgumentParser;
/**
* Your subclass should implement this hook to perform the operation.
*
* @remarks
* In a future release, this function will be renamed to onExecuteAsync
*/
protected abstract onExecute(): Promise<void>;
}
//# sourceMappingURL=CommandLineAction.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"CommandLineAction.d.ts","sourceRoot":"","sources":["../../src/providers/CommandLineAction.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,KAAK,QAAQ,MAAM,UAAU,CAAC;AAE1C,OAAO,EAAE,4BAA4B,EAAE,MAAM,gCAAgC,CAAC;AAG9E;;;GAGG;AACH,MAAM,WAAW,yBAAyB;IACxC;;;OAGG;IACH,UAAU,EAAE,MAAM,CAAC;IAEnB;;;OAGG;IACH,OAAO,EAAE,MAAM,CAAC;IAEhB;;;OAGG;IACH,aAAa,EAAE,MAAM,CAAC;CACvB;AAOD;;;;;;;;;;;;GAYG;AACH,8BAAsB,iBAAkB,SAAQ,4BAA4B;IAC1E,yDAAyD;IACzD,SAAgB,UAAU,EAAE,MAAM,CAAC;IAEnC,sDAAsD;IACtD,SAAgB,OAAO,EAAE,MAAM,CAAC;IAEhC,4DAA4D;IAC5D,SAAgB,aAAa,EAAE,MAAM,CAAC;IAEtC,OAAO,CAAC,eAAe,CAAsC;gBAE1C,OAAO,EAAE,yBAAyB;IAiBrD;;;OAGG;IACI,YAAY,CAAC,gBAAgB,EAAE,QAAQ,CAAC,SAAS,GAAG,IAAI;IAwB/D;;;OAGG;IACI,aAAa,IAAI,OAAO,CAAC,IAAI,CAAC;IAIrC;;;OAGG;IACI,kBAAkB,IAAI,QAAQ,CAAC,cAAc;IAUpD;;;;;OAKG;IACH,SAAS,CAAC,QAAQ,CAAC,SAAS,IAAI,OAAO,CAAC,IAAI,CAAC;CAC9C"}
@@ -0,0 +1,82 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
Object.defineProperty(exports, "__esModule", { value: true });
exports.CommandLineAction = void 0;
const CommandLineParameterProvider_1 = require("./CommandLineParameterProvider");
const CommandLineParserExitError_1 = require("./CommandLineParserExitError");
/**
* Example: "do-something"
*/
const ACTION_NAME_REGEXP = /^[a-z][a-z0-9]*([-:][a-z0-9]+)*$/;
/**
* Represents a sub-command that is part of the CommandLineParser command line.
* Applications should create subclasses of CommandLineAction corresponding to
* each action that they want to expose.
*
* The action name should be comprised of lower case words separated by hyphens
* or colons. The name should include an English verb (e.g. "deploy"). Use a
* hyphen to separate words (e.g. "upload-docs"). A group of related commands
* can be prefixed with a colon (e.g. "docs:generate", "docs:deploy",
* "docs:serve", etc).
*
* @public
*/
class CommandLineAction extends CommandLineParameterProvider_1.CommandLineParameterProvider {
constructor(options) {
super();
if (!ACTION_NAME_REGEXP.test(options.actionName)) {
throw new Error(`Invalid action name "${options.actionName}". ` +
`The name must be comprised of lower-case words optionally separated by hyphens or colons.`);
}
this.actionName = options.actionName;
this.summary = options.summary;
this.documentation = options.documentation;
this._argumentParser = undefined;
}
/**
* This is called internally by CommandLineParser.addAction()
* @internal
*/
_buildParser(actionsSubParser) {
var _a;
this._argumentParser = actionsSubParser.addParser(this.actionName, {
help: this.summary,
description: this.documentation
});
// Monkey-patch the error handling for the action parser
this._argumentParser.exit = (status, message) => {
throw new CommandLineParserExitError_1.CommandLineParserExitError(status, message);
};
const originalArgumentParserErrorFn = this._argumentParser.error.bind(this._argumentParser);
this._argumentParser.error = (err) => {
// Ensure the ParserExitError bubbles up to the top without any special processing
if (err instanceof CommandLineParserExitError_1.CommandLineParserExitError) {
throw err;
}
originalArgumentParserErrorFn(err);
};
(_a = this.onDefineParameters) === null || _a === void 0 ? void 0 : _a.call(this);
}
/**
* Invoked by CommandLineParser.onExecute().
* @internal
*/
_executeAsync() {
return this.onExecute();
}
/**
* {@inheritDoc CommandLineParameterProvider._getArgumentParser}
* @internal
*/
_getArgumentParser() {
// override
if (!this._argumentParser) {
// We will improve this in the future
throw new Error('The CommandLineAction must be added to a CommandLineParser before it can be used');
}
return this._argumentParser;
}
}
exports.CommandLineAction = CommandLineAction;
//# sourceMappingURL=CommandLineAction.js.map
@@ -0,0 +1 @@
{"version":3,"file":"CommandLineAction.js","sourceRoot":"","sources":["../../src/providers/CommandLineAction.ts"],"names":[],"mappings":";AAAA,4FAA4F;AAC5F,2DAA2D;;;AAI3D,iFAA8E;AAC9E,6EAA0E;AA0B1E;;GAEG;AACH,MAAM,kBAAkB,GAAW,kCAAkC,CAAC;AAEtE;;;;;;;;;;;;GAYG;AACH,MAAsB,iBAAkB,SAAQ,2DAA4B;IAY1E,YAAmB,OAAkC;QACnD,KAAK,EAAE,CAAC;QAER,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,EAAE,CAAC;YACjD,MAAM,IAAI,KAAK,CACb,wBAAwB,OAAO,CAAC,UAAU,KAAK;gBAC7C,2FAA2F,CAC9F,CAAC;QACJ,CAAC;QAED,IAAI,CAAC,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC;QACrC,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;QAC/B,IAAI,CAAC,aAAa,GAAG,OAAO,CAAC,aAAa,CAAC;QAE3C,IAAI,CAAC,eAAe,GAAG,SAAS,CAAC;IACnC,CAAC;IAED;;;OAGG;IACI,YAAY,CAAC,gBAAoC;;QACtD,IAAI,CAAC,eAAe,GAAG,gBAAgB,CAAC,SAAS,CAAC,IAAI,CAAC,UAAU,EAAE;YACjE,IAAI,EAAE,IAAI,CAAC,OAAO;YAClB,WAAW,EAAE,IAAI,CAAC,aAAa;SAChC,CAAC,CAAC;QAEH,wDAAwD;QACxD,IAAI,CAAC,eAAe,CAAC,IAAI,GAAG,CAAC,MAAc,EAAE,OAAe,EAAE,EAAE;YAC9D,MAAM,IAAI,uDAA0B,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QACxD,CAAC,CAAC;QACF,MAAM,6BAA6B,GAAkC,IAAI,CAAC,eAAe,CAAC,KAAK,CAAC,IAAI,CAClG,IAAI,CAAC,eAAe,CACrB,CAAC;QACF,IAAI,CAAC,eAAe,CAAC,KAAK,GAAG,CAAC,GAAmB,EAAE,EAAE;YACnD,kFAAkF;YAClF,IAAI,GAAG,YAAY,uDAA0B,EAAE,CAAC;gBAC9C,MAAM,GAAG,CAAC;YACZ,CAAC;YACD,6BAA6B,CAAC,GAAG,CAAC,CAAC;QACrC,CAAC,CAAC;QAEF,MAAA,IAAI,CAAC,kBAAkB,oDAAI,CAAC;IAC9B,CAAC;IAED;;;OAGG;IACI,aAAa;QAClB,OAAO,IAAI,CAAC,SAAS,EAAE,CAAC;IAC1B,CAAC;IAED;;;OAGG;IACI,kBAAkB;QACvB,WAAW;QACX,IAAI,CAAC,IAAI,CAAC,eAAe,EAAE,CAAC;YAC1B,qCAAqC;YACrC,MAAM,IAAI,KAAK,CAAC,kFAAkF,CAAC,CAAC;QACtG,CAAC;QAED,OAAO,IAAI,CAAC,eAAe,CAAC;IAC9B,CAAC;CASF;AAtFD,8CAsFC","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';\n\nimport { CommandLineParameterProvider } from './CommandLineParameterProvider';\nimport { CommandLineParserExitError } from './CommandLineParserExitError';\n\n/**\n * Options for the CommandLineAction constructor.\n * @public\n */\nexport interface ICommandLineActionOptions {\n /**\n * The name of the action. For example, if the tool is called \"example\",\n * then the \"build\" action might be invoked as: \"example build -q --some-other-option\"\n */\n actionName: string;\n\n /**\n * A quick summary that is shown on the main help page, which is displayed\n * by the command \"example --help\"\n */\n summary: string;\n\n /**\n * A detailed description that is shown on the action help page, which is displayed\n * by the command \"example build --help\", e.g. for actionName=\"build\".\n */\n documentation: string;\n}\n\n/**\n * Example: \"do-something\"\n */\nconst ACTION_NAME_REGEXP: RegExp = /^[a-z][a-z0-9]*([-:][a-z0-9]+)*$/;\n\n/**\n * Represents a sub-command that is part of the CommandLineParser command line.\n * Applications should create subclasses of CommandLineAction corresponding to\n * each action that they want to expose.\n *\n * The action name should be comprised of lower case words separated by hyphens\n * or colons. The name should include an English verb (e.g. \"deploy\"). Use a\n * hyphen to separate words (e.g. \"upload-docs\"). A group of related commands\n * can be prefixed with a colon (e.g. \"docs:generate\", \"docs:deploy\",\n * \"docs:serve\", etc).\n *\n * @public\n */\nexport abstract class CommandLineAction extends CommandLineParameterProvider {\n /** {@inheritDoc ICommandLineActionOptions.actionName} */\n public readonly actionName: string;\n\n /** {@inheritDoc ICommandLineActionOptions.summary} */\n public readonly summary: string;\n\n /** {@inheritDoc ICommandLineActionOptions.documentation} */\n public readonly documentation: string;\n\n private _argumentParser: argparse.ArgumentParser | undefined;\n\n public constructor(options: ICommandLineActionOptions) {\n super();\n\n if (!ACTION_NAME_REGEXP.test(options.actionName)) {\n throw new Error(\n `Invalid action name \"${options.actionName}\". ` +\n `The name must be comprised of lower-case words optionally separated by hyphens or colons.`\n );\n }\n\n this.actionName = options.actionName;\n this.summary = options.summary;\n this.documentation = options.documentation;\n\n this._argumentParser = undefined;\n }\n\n /**\n * This is called internally by CommandLineParser.addAction()\n * @internal\n */\n public _buildParser(actionsSubParser: argparse.SubParser): void {\n this._argumentParser = actionsSubParser.addParser(this.actionName, {\n help: this.summary,\n description: this.documentation\n });\n\n // Monkey-patch the error handling for the action parser\n this._argumentParser.exit = (status: number, message: string) => {\n throw new CommandLineParserExitError(status, message);\n };\n const originalArgumentParserErrorFn: (err: Error | string) => void = this._argumentParser.error.bind(\n this._argumentParser\n );\n this.Line truncated
@@ -0,0 +1,332 @@
import * as argparse from 'argparse';
import type { ICommandLineChoiceDefinition, ICommandLineChoiceListDefinition, ICommandLineIntegerDefinition, ICommandLineIntegerListDefinition, ICommandLineFlagDefinition, ICommandLineStringDefinition, ICommandLineStringListDefinition, ICommandLineRemainderDefinition } from '../parameters/CommandLineDefinition';
import type { ICommandLineParserOptions } from './CommandLineParser';
import { type CommandLineParameterBase, type CommandLineParameter } from '../parameters/BaseClasses';
import { CommandLineChoiceParameter, type IRequiredCommandLineChoiceParameter } from '../parameters/CommandLineChoiceParameter';
import { CommandLineChoiceListParameter } from '../parameters/CommandLineChoiceListParameter';
import { CommandLineIntegerParameter, type IRequiredCommandLineIntegerParameter } from '../parameters/CommandLineIntegerParameter';
import { CommandLineIntegerListParameter } from '../parameters/CommandLineIntegerListParameter';
import { CommandLineFlagParameter } from '../parameters/CommandLineFlagParameter';
import { CommandLineStringParameter, type IRequiredCommandLineStringParameter } from '../parameters/CommandLineStringParameter';
import { CommandLineStringListParameter } from '../parameters/CommandLineStringListParameter';
import { CommandLineRemainder } from '../parameters/CommandLineRemainder';
/**
* The result containing the parsed parameter long name and scope. Returned when calling
* {@link CommandLineParameterProvider.parseScopedLongName}.
*
* @public
*/
export interface IScopedLongNameParseResult {
/**
* The long name parsed from the scoped long name, e.g. "--my-scope:my-parameter" -\> "--my-parameter"
*/
longName: string;
/**
* The scope parsed from the scoped long name or undefined if no scope was found,
* e.g. "--my-scope:my-parameter" -\> "my-scope"
*/
scope: string | undefined;
}
/**
* An object containing the state of the
*
* @internal
*/
export interface IRegisterDefinedParametersState {
/**
* A set of all defined parameter names registered by parent {@link CommandLineParameterProvider}
* objects.
*/
parentParameterNames: Set<string>;
}
/**
* This is the argparse result data object
* @internal
*/
export interface ICommandLineParserData {
action: string;
aliasAction?: string;
aliasDocumentation?: string;
[key: string]: any;
}
/**
* This is the common base class for CommandLineAction and CommandLineParser
* that provides functionality for defining command-line parameters.
*
* @public
*/
export declare abstract class CommandLineParameterProvider {
private static _keyCounter;
/** @internal */
readonly _ambiguousParameterParserKeysByName: Map<string, string>;
/** @internal */
protected readonly _registeredParameterParserKeysByName: Map<string, string>;
private readonly _parameters;
private readonly _parametersByLongName;
private readonly _parametersByShortName;
private readonly _parameterGroupsByName;
private _parametersHaveBeenRegistered;
private _parametersHaveBeenProcessed;
private _remainder;
/** @internal */
constructor();
/**
* Returns a collection of the parameters that were defined for this object.
*/
get parameters(): ReadonlyArray<CommandLineParameterBase>;
/**
* Informs the caller if the argparse data has been processed into parameters.
*/
get parametersProcessed(): boolean;
/**
* If {@link CommandLineParameterProvider.defineCommandLineRemainder} was called,
* this object captures any remaining command line arguments after the recognized portion.
*/
get remainder(): CommandLineRemainder | undefined;
/**
* Defines a command-line parameter whose value must be a string from a fixed set of
* allowable choices (similar to an enum).
*
* @remarks
* Example of a choice parameter:
* ```
* example-tool --log-level warn
* ```
*/
defineChoiceParameter<TChoice extends string = string>(definition: ICommandLineChoiceDefinition<TChoice> & {
required: false | undefined;
defaultValue: undefined;
}): CommandLineChoiceParameter<TChoice>;
/**
* {@inheritdoc CommandLineParameterProvider.(defineChoiceParameter:1)}
*/
defineChoiceParameter<TChoice extends string = string>(definition: ICommandLineChoiceDefinition<TChoice> & {
required: true;
}): IRequiredCommandLineChoiceParameter<TChoice>;
/**
* {@inheritdoc CommandLineParameterProvider.(defineChoiceParameter:1)}
*/
defineChoiceParameter<TChoice extends string = string>(definition: ICommandLineChoiceDefinition<TChoice> & {
defaultValue: TChoice;
}): IRequiredCommandLineChoiceParameter<TChoice>;
/**
* {@inheritdoc CommandLineParameterProvider.(defineChoiceParameter:1)}
*/
defineChoiceParameter<TChoice extends string = string>(definition: ICommandLineChoiceDefinition<TChoice>): CommandLineChoiceParameter<TChoice>;
/**
* Returns the CommandLineChoiceParameter with the specified long name.
* @remarks
* This method throws an exception if the parameter is not defined.
*/
getChoiceParameter(parameterLongName: string, parameterScope?: string): CommandLineChoiceParameter;
/**
* Defines a command-line parameter whose value must be a string from a fixed set of
* allowable choices (similar to an enum). The parameter can be specified multiple times to
* build a list.
*
* @remarks
* Example of a choice list parameter:
* ```
* example-tool --allow-color red --allow-color green
* ```
*/
defineChoiceListParameter<TChoice extends string = string>(definition: ICommandLineChoiceListDefinition<TChoice>): CommandLineChoiceListParameter<TChoice>;
/**
* Returns the CommandLineChoiceListParameter with the specified long name.
* @remarks
* This method throws an exception if the parameter is not defined.
*/
getChoiceListParameter(parameterLongName: string, parameterScope?: string): CommandLineChoiceListParameter;
/**
* Defines a command-line switch whose boolean value is true if the switch is provided,
* and false otherwise.
*
* @remarks
* Example usage of a flag parameter:
* ```
* example-tool --debug
* ```
*/
defineFlagParameter(definition: ICommandLineFlagDefinition): CommandLineFlagParameter;
/**
* Returns the CommandLineFlagParameter with the specified long name.
* @remarks
* This method throws an exception if the parameter is not defined.
*/
getFlagParameter(parameterLongName: string, parameterScope?: string): CommandLineFlagParameter;
/**
* Defines a command-line parameter whose argument is an integer.
*
* @remarks
* Example usage of an integer parameter:
* ```
* example-tool --max-attempts 5
* ```
*/
defineIntegerParameter(definition: ICommandLineIntegerDefinition & {
required: false | undefined;
defaultValue: undefined;
}): CommandLineIntegerParameter;
/**
* {@inheritdoc CommandLineParameterProvider.(defineIntegerParameter:1)}
*/
defineIntegerParameter(definition: ICommandLineIntegerDefinition & {
required: true;
}): IRequiredCommandLineIntegerParameter;
/**
* {@inheritdoc CommandLineParameterProvider.(defineIntegerParameter:1)}
*/
defineIntegerParameter(definition: ICommandLineIntegerDefinition & {
defaultValue: number;
}): IRequiredCommandLineIntegerParameter;
/**
* {@inheritdoc CommandLineParameterProvider.(defineIntegerParameter:1)}
*/
defineIntegerParameter(definition: ICommandLineIntegerDefinition): CommandLineIntegerParameter;
/**
* Returns the CommandLineIntegerParameter with the specified long name.
* @remarks
* This method throws an exception if the parameter is not defined.
*/
getIntegerParameter(parameterLongName: string, parameterScope?: string): CommandLineIntegerParameter;
/**
* Defines a command-line parameter whose argument is an integer. The parameter can be specified
* multiple times to build a list.
*
* @remarks
* Example usage of an integer list parameter:
* ```
* example-tool --avoid 4 --avoid 13
* ```
*/
defineIntegerListParameter(definition: ICommandLineIntegerListDefinition): CommandLineIntegerListParameter;
/**
* Returns the CommandLineIntegerParameter with the specified long name.
* @remarks
* This method throws an exception if the parameter is not defined.
*/
getIntegerListParameter(parameterLongName: string, parameterScope?: string): CommandLineIntegerListParameter;
/**
* Defines a command-line parameter whose argument is a single text string.
*
* @remarks
* Example usage of a string parameter:
* ```
* example-tool --message "Hello, world!"
* ```
*/
defineStringParameter(definition: ICommandLineStringDefinition & {
required: false | undefined;
defaultValue: undefined;
}): CommandLineStringParameter;
/**
* {@inheritdoc CommandLineParameterProvider.(defineStringParameter:1)}
*/
defineStringParameter(definition: ICommandLineStringDefinition & {
required: true;
}): IRequiredCommandLineStringParameter;
/**
* {@inheritdoc CommandLineParameterProvider.(defineStringParameter:1)}
*/
defineStringParameter(definition: ICommandLineStringDefinition & {
defaultValue: string;
}): IRequiredCommandLineStringParameter;
/**
* {@inheritdoc CommandLineParameterProvider.(defineStringParameter:1)}
*/
defineStringParameter(definition: ICommandLineStringDefinition): CommandLineStringParameter;
/**
* Returns the CommandLineStringParameter with the specified long name.
* @remarks
* This method throws an exception if the parameter is not defined.
*/
getStringParameter(parameterLongName: string, parameterScope?: string): CommandLineStringParameter;
/**
* Defines a command-line parameter whose argument is a single text string. The parameter can be
* specified multiple times to build a list.
*
* @remarks
* Example usage of a string list parameter:
* ```
* example-tool --add file1.txt --add file2.txt --add file3.txt
* ```
*/
defineStringListParameter(definition: ICommandLineStringListDefinition): CommandLineStringListParameter;
/**
* Defines a rule that captures any remaining command line arguments after the recognized portion.
*
* @remarks
* This feature is useful for commands that pass their arguments along to an external tool, relying on
* that tool to perform validation. (It could also be used to parse parameters without any validation
* or documentation, but that is not recommended.)
*
* Example of capturing the remainder after an optional flag parameter.
* ```
* example-tool --my-flag this is the remainder
* ```
*
* In the "--help" documentation, the remainder rule will be represented as "...".
*/
defineCommandLineRemainder(definition: ICommandLineRemainderDefinition): CommandLineRemainder;
/**
* Returns the CommandLineStringListParameter with the specified long name.
* @remarks
* This method throws an exception if the parameter is not defined.
*/
getStringListParameter(parameterLongName: string, parameterScope?: string): CommandLineStringListParameter;
/**
* Generates the command-line help text.
*/
renderHelpText(): string;
/**
* Generates the command-line usage text.
*/
renderUsageText(): string;
/**
* Returns a object which maps the long name of each parameter in this.parameters
* to the stringified form of its value. This is useful for logging telemetry, but
* it is not the proper way of accessing parameters or their values.
*/
getParameterStringMap(): Record<string, string>;
/**
* Returns an object with the parsed scope (if present) and the long name of the parameter.
*/
parseScopedLongName(scopedLongName: string): IScopedLongNameParseResult;
/** @internal */
_registerDefinedParameters(state: IRegisterDefinedParametersState): void;
/**
* @deprecated - Define parameters in the constructor
*/
protected onDefineParameters?(): void;
/**
* Retrieves the argparse object.
* @internal
*/
protected abstract _getArgumentParser(): argparse.ArgumentParser;
/**
* This is called internally by {@link CommandLineParser.executeAsync}
* @internal
*/
_preParse(): void;
/**
* This is called internally by {@link CommandLineParser.executeAsync} before `printUsage` is called
* @internal
*/
_postParse(): void;
/**
* This is called internally by {@link CommandLineParser.executeAsync}
* @internal
*/
_processParsedData(parserOptions: ICommandLineParserOptions, data: ICommandLineParserData): void;
/** @internal */
protected _defineParameter(parameter: CommandLineParameter): void;
/** @internal */
protected _defineAmbiguousParameter(name: string): string;
/** @internal */
protected _registerParameter(parameter: CommandLineParameter, useScopedLongName: boolean, ignoreShortName: boolean): void;
protected _registerAmbiguousParameter(name: string, parserKey: string): void;
private _generateKey;
private _getParameter;
private _throwParserExitError;
}
//# sourceMappingURL=CommandLineParameterProvider.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"CommandLineParameterProvider.d.ts","sourceRoot":"","sources":["../../src/providers/CommandLineParameterProvider.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,QAAQ,MAAM,UAAU,CAAC;AAErC,OAAO,KAAK,EACV,4BAA4B,EAC5B,gCAAgC,EAChC,6BAA6B,EAC7B,iCAAiC,EACjC,0BAA0B,EAC1B,4BAA4B,EAC5B,gCAAgC,EAChC,+BAA+B,EAChC,MAAM,qCAAqC,CAAC;AAC7C,OAAO,KAAK,EAAE,yBAA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E/E;;OAEG;IACH,SAAS,CAAC,kBAAkB,CAAC,IAAI,IAAI;IAErC;;;OAGG;IACH,SAAS,CAAC,QAAQ,CAAC,kBAAkB,IAAI,QAAQ,CAAC,cAAc;IAEhE;;;OAGG;IACI,SAAS,IAAI,IAAI;IAMxB;;;OAGG;IACI,UAAU,IAAI,IAAI;IAMzB;;;OAGG;IACI,kBAAkB,CAAC,aAAa,EAAE,yBAAyB,EAAE,IAAI,EAAE,sBAAsB,GAAG,IAAI;IA2GvG,gBAAgB;IAChB,SAAS,CAAC,gBAAgB,CAAC,SAAS,EAAE,oBAAoB,GAAG,IAAI;IAiCjE,gBAAgB;IAChB,SAAS,CAAC,yBAAyB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM;IAkBzD,gBAAgB;IAChB,SAAS,CAAC,kBAAkB,CAC1B,SAAS,EAAE,oBAAoBLine truncated
@@ -0,0 +1,707 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.CommandLineParameterProvider = void 0;
const argparse = __importStar(require("argparse"));
const BaseClasses_1 = require("../parameters/BaseClasses");
const CommandLineChoiceParameter_1 = require("../parameters/CommandLineChoiceParameter");
const CommandLineChoiceListParameter_1 = require("../parameters/CommandLineChoiceListParameter");
const CommandLineIntegerParameter_1 = require("../parameters/CommandLineIntegerParameter");
const CommandLineIntegerListParameter_1 = require("../parameters/CommandLineIntegerListParameter");
const CommandLineFlagParameter_1 = require("../parameters/CommandLineFlagParameter");
const CommandLineStringParameter_1 = require("../parameters/CommandLineStringParameter");
const CommandLineStringListParameter_1 = require("../parameters/CommandLineStringListParameter");
const CommandLineRemainder_1 = require("../parameters/CommandLineRemainder");
const Constants_1 = require("../Constants");
const CommandLineParserExitError_1 = require("./CommandLineParserExitError");
const SCOPE_GROUP_NAME = 'scope';
const LONG_NAME_GROUP_NAME = 'longName';
const POSSIBLY_SCOPED_LONG_NAME_REGEXP = /^--((?<scope>[a-z0-9]+(-[a-z0-9]+)*):)?(?<longName>[a-z0-9]+((-[a-z0-9]+)+)?)$/;
/**
* This is the common base class for CommandLineAction and CommandLineParser
* that provides functionality for defining command-line parameters.
*
* @public
*/
class CommandLineParameterProvider {
/** @internal */
// Third party code should not inherit subclasses or call this constructor
constructor() {
this._parameters = [];
this._parametersByLongName = new Map();
this._parametersByShortName = new Map();
this._parameterGroupsByName = new Map();
this._ambiguousParameterParserKeysByName = new Map();
this._registeredParameterParserKeysByName = new Map();
this._parametersHaveBeenRegistered = false;
this._parametersHaveBeenProcessed = false;
}
/**
* Returns a collection of the parameters that were defined for this object.
*/
get parameters() {
return this._parameters;
}
/**
* Informs the caller if the argparse data has been processed into parameters.
*/
get parametersProcessed() {
return this._parametersHaveBeenProcessed;
}
/**
* If {@link CommandLineParameterProvider.defineCommandLineRemainder} was called,
* this object captures any remaining command line arguments after the recognized portion.
*/
get remainder() {
return this._remainder;
}
defineChoiceParameter(definition) {
const parameter = new CommandLineChoiceParameter_1.CommandLineChoiceParameter(definition);
this._defineParameter(parameter);
return parameter;
}
/**
* Returns the CommandLineChoiceParameter with the specified long name.
* @remarks
* This method throws an exception if the parameter is not defined.
*/
getChoiceParameter(parameterLongName, parameterScope) {
return this._getParameter(parameterLongName, BaseClasses_1.CommandLineParameterKind.Choice, parameterScope);
}
/**
* Defines a command-line parameter whose value must be a string from a fixed set of
* allowable choices (similar to an enum). The parameter can be specified multiple times to
* build a list.
*
* @remarks
* Example of a choice list parameter:
* ```
* example-tool --allow-color red --allow-color green
* ```
*/
defineChoiceListParameter(definition) {
const parameter = new CommandLineChoiceListParameter_1.CommandLineChoiceListParameter(definition);
this._defineParameter(parameter);
return parameter;
}
/**
* Returns the CommandLineChoiceListParameter with the specified long name.
* @remarks
* This method throws an exception if the parameter is not defined.
*/
getChoiceListParameter(parameterLongName, parameterScope) {
return this._getParameter(parameterLongName, BaseClasses_1.CommandLineParameterKind.ChoiceList, parameterScope);
}
/**
* Defines a command-line switch whose boolean value is true if the switch is provided,
* and false otherwise.
*
* @remarks
* Example usage of a flag parameter:
* ```
* example-tool --debug
* ```
*/
defineFlagParameter(definition) {
const parameter = new CommandLineFlagParameter_1.CommandLineFlagParameter(definition);
this._defineParameter(parameter);
return parameter;
}
/**
* Returns the CommandLineFlagParameter with the specified long name.
* @remarks
* This method throws an exception if the parameter is not defined.
*/
getFlagParameter(parameterLongName, parameterScope) {
return this._getParameter(parameterLongName, BaseClasses_1.CommandLineParameterKind.Flag, parameterScope);
}
defineIntegerParameter(definition) {
const parameter = new CommandLineIntegerParameter_1.CommandLineIntegerParameter(definition);
this._defineParameter(parameter);
return parameter;
}
/**
* Returns the CommandLineIntegerParameter with the specified long name.
* @remarks
* This method throws an exception if the parameter is not defined.
*/
getIntegerParameter(parameterLongName, parameterScope) {
return this._getParameter(parameterLongName, BaseClasses_1.CommandLineParameterKind.Integer, parameterScope);
}
/**
* Defines a command-line parameter whose argument is an integer. The parameter can be specified
* multiple times to build a list.
*
* @remarks
* Example usage of an integer list parameter:
* ```
* example-tool --avoid 4 --avoid 13
* ```
*/
defineIntegerListParameter(definition) {
const parameter = new CommandLineIntegerListParameter_1.CommandLineIntegerListParameter(definition);
this._defineParameter(parameter);
return parameter;
}
/**
* Returns the CommandLineIntegerParameter with the specified long name.
* @remarks
* This method throws an exception if the parameter is not defined.
*/
getIntegerListParameter(parameterLongName, parameterScope) {
return this._getParameter(parameterLongName, BaseClasses_1.CommandLineParameterKind.IntegerList, parameterScope);
}
defineStringParameter(definition) {
const parameter = new CommandLineStringParameter_1.CommandLineStringParameter(definition);
this._defineParameter(parameter);
return parameter;
}
/**
* Returns the CommandLineStringParameter with the specified long name.
* @remarks
* This method throws an exception if the parameter is not defined.
*/
getStringParameter(parameterLongName, parameterScope) {
return this._getParameter(parameterLongName, BaseClasses_1.CommandLineParameterKind.String, parameterScope);
}
/**
* Defines a command-line parameter whose argument is a single text string. The parameter can be
* specified multiple times to build a list.
*
* @remarks
* Example usage of a string list parameter:
* ```
* example-tool --add file1.txt --add file2.txt --add file3.txt
* ```
*/
defineStringListParameter(definition) {
const parameter = new CommandLineStringListParameter_1.CommandLineStringListParameter(definition);
this._defineParameter(parameter);
return parameter;
}
/**
* Defines a rule that captures any remaining command line arguments after the recognized portion.
*
* @remarks
* This feature is useful for commands that pass their arguments along to an external tool, relying on
* that tool to perform validation. (It could also be used to parse parameters without any validation
* or documentation, but that is not recommended.)
*
* Example of capturing the remainder after an optional flag parameter.
* ```
* example-tool --my-flag this is the remainder
* ```
*
* In the "--help" documentation, the remainder rule will be represented as "...".
*/
defineCommandLineRemainder(definition) {
if (this._remainder) {
throw new Error('defineRemainingArguments() has already been called for this provider');
}
this._remainder = new CommandLineRemainder_1.CommandLineRemainder(definition);
return this._remainder;
}
/**
* Returns the CommandLineStringListParameter with the specified long name.
* @remarks
* This method throws an exception if the parameter is not defined.
*/
getStringListParameter(parameterLongName, parameterScope) {
return this._getParameter(parameterLongName, BaseClasses_1.CommandLineParameterKind.StringList, parameterScope);
}
/**
* Generates the command-line help text.
*/
renderHelpText() {
const initialState = {
parentParameterNames: new Set()
};
this._registerDefinedParameters(initialState);
return this._getArgumentParser().formatHelp();
}
/**
* Generates the command-line usage text.
*/
renderUsageText() {
const initialState = {
parentParameterNames: new Set()
};
this._registerDefinedParameters(initialState);
return this._getArgumentParser().formatUsage();
}
/**
* Returns a object which maps the long name of each parameter in this.parameters
* to the stringified form of its value. This is useful for logging telemetry, but
* it is not the proper way of accessing parameters or their values.
*/
getParameterStringMap() {
const parameterMap = {};
for (const parameter of this.parameters) {
const parameterName = parameter.scopedLongName || parameter.longName;
switch (parameter.kind) {
case BaseClasses_1.CommandLineParameterKind.Flag:
case BaseClasses_1.CommandLineParameterKind.Choice:
case BaseClasses_1.CommandLineParameterKind.String:
case BaseClasses_1.CommandLineParameterKind.Integer:
parameterMap[parameterName] = JSON.stringify(parameter.value);
break;
case BaseClasses_1.CommandLineParameterKind.StringList:
case BaseClasses_1.CommandLineParameterKind.IntegerList:
case BaseClasses_1.CommandLineParameterKind.ChoiceList:
const arrayValue = parameter.values;
parameterMap[parameterName] = arrayValue ? arrayValue.join(',') : '';
break;
}
}
return parameterMap;
}
/**
* Returns an object with the parsed scope (if present) and the long name of the parameter.
*/
parseScopedLongName(scopedLongName) {
const result = POSSIBLY_SCOPED_LONG_NAME_REGEXP.exec(scopedLongName);
if (!result || !result.groups) {
throw new Error(`The parameter long name "${scopedLongName}" is not valid.`);
}
return {
longName: `--${result.groups[LONG_NAME_GROUP_NAME]}`,
scope: result.groups[SCOPE_GROUP_NAME]
};
}
/** @internal */
_registerDefinedParameters(state) {
if (this._parametersHaveBeenRegistered) {
// We prevent new parameters from being defined after the first call to _registerDefinedParameters,
// so we can already ensure that all parameters were registered.
return;
}
// First, loop through all parameters with short names. If there are any duplicates, disable the short names
// since we can't prefix scopes to short names in order to deduplicate them. The duplicate short names will
// be reported as errors if the user attempts to use them.
const parametersWithDuplicateShortNames = new Set();
for (const [shortName, shortNameParameters] of this._parametersByShortName.entries()) {
if (shortNameParameters.length > 1) {
for (const parameter of shortNameParameters) {
this._defineAmbiguousParameter(shortName);
parametersWithDuplicateShortNames.add(parameter);
}
}
}
// Then, loop through all parameters and register them. If there are any duplicates, ensure that they have
// provided a scope and register them with the scope. The duplicate long names will be reported as an error
// if the user attempts to use them.
for (const longNameParameters of this._parametersByLongName.values()) {
const useScopedLongName = longNameParameters.length > 1;
for (const parameter of longNameParameters) {
if (useScopedLongName) {
if (!parameter.parameterScope) {
throw new Error(`The parameter "${parameter.longName}" is defined multiple times with the same long name. ` +
'Parameters with the same long name must define a scope.');
}
this._defineAmbiguousParameter(parameter.longName);
}
const ignoreShortName = parametersWithDuplicateShortNames.has(parameter);
this._registerParameter(parameter, useScopedLongName, ignoreShortName);
}
}
// Register the existing parameters as ambiguous parameters. These are generally provided by the
// parent action.
const { parentParameterNames } = state;
for (const parentParameterName of parentParameterNames) {
this._defineAmbiguousParameter(parentParameterName);
}
// We also need to loop through the defined ambiguous parameters and register them. These will be reported
// as errors if the user attempts to use them.
for (const [ambiguousParameterName, parserKey] of this._ambiguousParameterParserKeysByName) {
// Only register the ambiguous parameter if it hasn't already been registered. We will still handle these
// already-registered parameters as ambiguous, but by avoiding registering again, we will defer errors
// until the user actually attempts to use the parameter.
if (!this._registeredParameterParserKeysByName.has(ambiguousParameterName)) {
this._registerAmbiguousParameter(ambiguousParameterName, parserKey);
}
}
// Need to add the remainder parameter last
if (this._remainder) {
const argparseOptions = {
help: this._remainder.description,
nargs: argparse.Const.REMAINDER,
metavar: '"..."'
};
this._getArgumentParser().addArgument(argparse.Const.REMAINDER, argparseOptions);
}
this._parametersHaveBeenRegistered = true;
}
/**
* This is called internally by {@link CommandLineParser.executeAsync}
* @internal
*/
_preParse() {
var _a;
for (const parameter of this._parameters) {
(_a = parameter._preParse) === null || _a === void 0 ? void 0 : _a.call(parameter);
}
}
/**
* This is called internally by {@link CommandLineParser.executeAsync} before `printUsage` is called
* @internal
*/
_postParse() {
var _a;
for (const parameter of this._parameters) {
(_a = parameter._postParse) === null || _a === void 0 ? void 0 : _a.call(parameter);
}
}
/**
* This is called internally by {@link CommandLineParser.executeAsync}
* @internal
*/
_processParsedData(parserOptions, data) {
var _a;
if (!this._parametersHaveBeenRegistered) {
throw new Error('Parameters have not been registered');
}
if (this._parametersHaveBeenProcessed) {
throw new Error('Command Line Parser Data was already processed');
}
// Search for any ambiguous parameters and throw an error if any are found
for (const [parameterName, parserKey] of this._ambiguousParameterParserKeysByName) {
if (data[parserKey]) {
// When the parser key matches the actually registered parameter, we know that this is an ambiguous
// parameter sourced from the parent action or tool
if (this._registeredParameterParserKeysByName.get(parameterName) === parserKey) {
this._throwParserExitError(parserOptions, data, 1, `Ambiguous option: "${parameterName}".`);
}
// Determine if the ambiguous parameter is a short name or a long name, since the process of finding
// the non-ambiguous name is different for each.
const duplicateShortNameParameters = this._parametersByShortName.get(parameterName);
if (duplicateShortNameParameters) {
// We also need to make sure we get the non-ambiguous long name for the parameter, since it is
// possible for that the long name is ambiguous as well.
const nonAmbiguousLongNames = [];
for (const parameter of duplicateShortNameParameters) {
const matchingLongNameParameters = this._parametersByLongName.get(parameter.longName);
if (!(matchingLongNameParameters === null || matchingLongNameParameters === void 0 ? void 0 : matchingLongNameParameters.length)) {
// This should never happen
throw new Error(`Unable to find long name parameters for ambiguous short name parameter "${parameterName}".`);
}
// If there is more than one matching long name parameter, then we know that we need to use the
// scoped long name for the parameter. The scoped long name should always be provided.
if (matchingLongNameParameters.length > 1) {
if (!parameter.scopedLongName) {
// This should never happen
throw new Error(`Unable to find scoped long name for ambiguous short name parameter "${parameterName}".`);
}
nonAmbiguousLongNames.push(parameter.scopedLongName);
}
else {
nonAmbiguousLongNames.push(parameter.longName);
}
}
// Throw an error including the non-ambiguous long names for the parameters that have the ambiguous
// short name, ex.
// Error: Ambiguous option "-p" could match "--param1", "--param2"
this._throwParserExitError(parserOptions, data, 1, `Ambiguous option: "${parameterName}" could match ${nonAmbiguousLongNames.join(', ')}.`);
}
const duplicateLongNameParameters = this._parametersByLongName.get(parameterName);
if (duplicateLongNameParameters) {
const nonAmbiguousLongNames = duplicateLongNameParameters.map((p) => {
// The scoped long name should always be provided
if (!p.scopedLongName) {
// This should never happen
throw new Error(`Unable to find scoped long name for ambiguous long name parameter "${parameterName}".`);
}
return p.scopedLongName;
});
// Throw an error including the non-ambiguous scoped long names for the parameters that have the
// ambiguous long name, ex.
// Error: Ambiguous option: "--param" could match --scope1:param, --scope2:param
this._throwParserExitError(parserOptions, data, 1, `Ambiguous option: "${parameterName}" could match ${nonAmbiguousLongNames.join(', ')}.`);
}
// This shouldn't happen, but we also shouldn't allow the user to use the ambiguous parameter
this._throwParserExitError(parserOptions, data, 1, `Ambiguous option: "${parameterName}".`);
}
}
// Fill in the values for the parameters
for (const parameter of this._parameters) {
const value = data[parameter._parserKey];
parameter._setValue(value);
(_a = parameter._validateValue) === null || _a === void 0 ? void 0 : _a.call(parameter);
}
if (this.remainder) {
this.remainder._setValue(data[argparse.Const.REMAINDER]);
}
this._parametersHaveBeenProcessed = true;
}
/** @internal */
_defineParameter(parameter) {
if (this._parametersHaveBeenRegistered) {
throw new Error('Parameters have already been registered for this provider');
}
// Generate and set the parser key at definition time
parameter._parserKey = this._generateKey();
this._parameters.push(parameter);
// Collect all parameters with the same long name. We will perform conflict resolution at registration.
let longNameParameters = this._parametersByLongName.get(parameter.longName);
if (!longNameParameters) {
longNameParameters = [];
this._parametersByLongName.set(parameter.longName, longNameParameters);
}
longNameParameters.push(parameter);
// Collect all parameters with the same short name. We will perform conflict resolution at registration.
if (parameter.shortName) {
let shortNameParameters = this._parametersByShortName.get(parameter.shortName);
if (!shortNameParameters) {
shortNameParameters = [];
this._parametersByShortName.set(parameter.shortName, shortNameParameters);
}
shortNameParameters.push(parameter);
}
}
/** @internal */
_defineAmbiguousParameter(name) {
if (this._parametersHaveBeenRegistered) {
throw new Error('Parameters have already been registered for this provider');
}
// Only generate a new parser key if the ambiguous parameter hasn't been defined yet,
// either as an existing parameter or as another ambiguous parameter
let existingParserKey = this._registeredParameterParserKeysByName.get(name) ||
this._ambiguousParameterParserKeysByName.get(name);
if (!existingParserKey) {
existingParserKey = this._generateKey();
}
this._ambiguousParameterParserKeysByName.set(name, existingParserKey);
return existingParserKey;
}
/** @internal */
_registerParameter(parameter, useScopedLongName, ignoreShortName) {
var _a, _b, _c;
const { shortName, longName, scopedLongName, description, kind, required, environmentVariable, parameterGroup, undocumentedSynonyms, _parserKey: parserKey } = parameter;
const names = [];
if (shortName && !ignoreShortName) {
names.push(shortName);
}
// Use the original long name unless otherwise requested
if (!useScopedLongName) {
names.push(longName);
}
// Add the scoped long name if it exists
if (scopedLongName) {
names.push(scopedLongName);
}
let finalDescription = description;
const supplementaryNotes = [];
parameter._getSupplementaryNotes(supplementaryNotes);
if (supplementaryNotes.length > 0) {
// If they left the period off the end of their sentence, then add one.
if (finalDescription.match(/[a-z0-9]"?\s*$/i)) {
finalDescription = finalDescription.trimEnd() + '.';
}
// Append the supplementary text
finalDescription += ' ' + supplementaryNotes.join(' ');
}
let choices;
let action;
let type;
switch (kind) {
case BaseClasses_1.CommandLineParameterKind.Choice: {
choices = Array.from(parameter.alternatives);
break;
}
case BaseClasses_1.CommandLineParameterKind.ChoiceList: {
choices = Array.from(parameter.alternatives);
action = 'append';
break;
}
case BaseClasses_1.CommandLineParameterKind.Flag:
action = 'storeTrue';
break;
case BaseClasses_1.CommandLineParameterKind.Integer:
type = 'int';
break;
case BaseClasses_1.CommandLineParameterKind.IntegerList:
type = 'int';
action = 'append';
break;
case BaseClasses_1.CommandLineParameterKind.String:
break;
case BaseClasses_1.CommandLineParameterKind.StringList:
action = 'append';
break;
}
// NOTE: Our "environmentVariable" feature takes precedence over argparse's "defaultValue",
// so we have to reimplement that feature.
const argparseOptions = {
help: finalDescription,
dest: parserKey,
metavar: parameter.argumentName,
required,
choices,
action,
type
};
const argumentParser = this._getArgumentParser();
let argumentGroup;
if (parameterGroup) {
argumentGroup = this._parameterGroupsByName.get(parameterGroup);
if (!argumentGroup) {
let parameterGroupName;
if (typeof parameterGroup === 'string') {
parameterGroupName = parameterGroup;
}
else if (parameterGroup === Constants_1.SCOPING_PARAMETER_GROUP) {
parameterGroupName = 'scoping';
}
else {
throw new Error('Unexpected parameter group: ' + parameterGroup);
}
argumentGroup = argumentParser.addArgumentGroup({
title: `Optional ${parameterGroupName} arguments`
});
this._parameterGroupsByName.set(parameterGroup, argumentGroup);
}
}
else {
argumentGroup = argumentParser;
}
const argparseArgument = argumentGroup.addArgument(names, argparseOptions);
if (required && environmentVariable) {
// Add some special-cased logic to handle required parameters with environment variables
const originalPreParse = (_a = parameter._preParse) === null || _a === void 0 ? void 0 : _a.bind(parameter);
parameter._preParse = () => {
originalPreParse === null || originalPreParse === void 0 ? void 0 : originalPreParse();
// Set the value as non-required before parsing. We'll validate it explicitly
argparseArgument.required = false;
};
const originalPostParse = (_b = parameter._postParse) === null || _b === void 0 ? void 0 : _b.bind(parameter);
parameter._postParse = () => {
// Reset the required value to make the usage text correct
argparseArgument.required = true;
originalPostParse === null || originalPostParse === void 0 ? void 0 : originalPostParse();
};
function throwMissingParameterError() {
argumentParser.error(`Argument "${longName}" is required`);
}
const originalValidateValue = (_c = parameter._validateValue) === null || _c === void 0 ? void 0 : _c.bind(parameter);
// For these values, we have to perform explicit validation because they're requested
// as required, but we disabled argparse's required flag to allow the environment variable
// to potentially fill the value.
switch (kind) {
case BaseClasses_1.CommandLineParameterKind.Choice:
case BaseClasses_1.CommandLineParameterKind.Integer:
case BaseClasses_1.CommandLineParameterKind.String:
parameter._validateValue = function () {
if (this.value === undefined || this.value === null) {
throwMissingParameterError();
}
originalValidateValue === null || originalValidateValue === void 0 ? void 0 : originalValidateValue();
};
break;
case BaseClasses_1.CommandLineParameterKind.ChoiceList:
case BaseClasses_1.CommandLineParameterKind.IntegerList:
case BaseClasses_1.CommandLineParameterKind.StringList:
parameter._validateValue = function () {
if (this.values.length === 0) {
throwMissingParameterError();
}
originalValidateValue === null || originalValidateValue === void 0 ? void 0 : originalValidateValue();
};
break;
}
}
if (undocumentedSynonyms === null || undocumentedSynonyms === void 0 ? void 0 : undocumentedSynonyms.length) {
argumentGroup.addArgument(undocumentedSynonyms, {
...argparseOptions,
help: argparse.Const.SUPPRESS
});
}
// Register the parameter names so that we can detect ambiguous parameters
for (const name of [...names, ...(undocumentedSynonyms || [])]) {
this._registeredParameterParserKeysByName.set(name, parserKey);
}
}
_registerAmbiguousParameter(name, parserKey) {
this._getArgumentParser().addArgument(name, {
dest: parserKey,
// We don't know if this argument takes parameters or not, so we need to accept any number of args
nargs: '*',
// Ensure that the argument is not shown in the help text, since these parameters are only included
// to inform the user that ambiguous parameters are present
help: argparse.Const.SUPPRESS
});
}
_generateKey() {
return 'key_' + (CommandLineParameterProvider._keyCounter++).toString();
}
_getParameter(parameterLongName, expectedKind, parameterScope) {
// Support the parameter long name being prefixed with the scope
const { scope, longName } = this.parseScopedLongName(parameterLongName);
parameterLongName = longName;
parameterScope = scope || parameterScope;
const parameters = this._parametersByLongName.get(parameterLongName);
if (!parameters) {
throw new Error(`The parameter "${parameterLongName}" is not defined`);
}
let parameter = parameters.find((p) => p.parameterScope === parameterScope);
if (!parameter) {
if (parameterScope !== undefined) {
throw new Error(`The parameter "${parameterLongName}" with scope "${parameterScope}" is not defined.`);
}
if (parameters.length !== 1) {
throw new Error(`The parameter "${parameterLongName}" is ambiguous. You must specify a scope.`);
}
parameter = parameters[0];
}
if (parameter.kind !== expectedKind) {
throw new Error(`The parameter "${parameterLongName}" is of type "${BaseClasses_1.CommandLineParameterKind[parameter.kind]}"` +
` whereas the caller was expecting "${BaseClasses_1.CommandLineParameterKind[expectedKind]}".`);
}
return parameter;
}
_throwParserExitError(parserOptions, data, errorCode, message) {
// Write out the usage text to make it easier for the user to find the correct parameter name
const targetActionName = data.aliasAction || data.action || '';
const errorPrefix = `Error: ${parserOptions.toolFilename}` +
// Handle aliases, actions, and actionless parameter providers
`${targetActionName ? ' ' : ''}${targetActionName}: error: `;
// eslint-disable-next-line no-console
console.log(this.renderUsageText());
throw new CommandLineParserExitError_1.CommandLineParserExitError(errorCode, `${errorPrefix}${message.trimStart().trimEnd()}\n`);
}
}
exports.CommandLineParameterProvider = CommandLineParameterProvider;
CommandLineParameterProvider._keyCounter = 0;
//# sourceMappingURL=CommandLineParameterProvider.js.map
@@ -0,0 +1 @@
{"version":3,"file":"CommandLineParameterProvider.js","sourceRoot":"","sources":["../../src/providers/CommandLineParameterProvider.ts"],"names":[],"mappings":";AAAA,4FAA4F;AAC5F,2DAA2D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAE3D,mDAAqC;AAarC,2DAKmC;AACnC,yFAGkD;AAClD,iGAA8F;AAC9F,2FAGmD;AACnD,mGAAgG;AAChG,qFAAkF;AAClF,yFAGkD;AAClD,iGAA8F;AAC9F,6EAA0E;AAC1E,4CAAuD;AACvD,6EAA0E;AA6C1E,MAAM,gBAAgB,GAAW,OAAO,CAAC;AACzC,MAAM,oBAAoB,GAAW,UAAU,CAAC;AAChD,MAAM,gCAAgC,GACpC,gFAAgF,CAAC;AAanF;;;;;GAKG;AACH,MAAsB,4BAA4B;IAmBhD,gBAAgB;IAChB,0EAA0E;IAC1E;QACE,IAAI,CAAC,WAAW,GAAG,EAAE,CAAC;QACtB,IAAI,CAAC,qBAAqB,GAAG,IAAI,GAAG,EAAE,CAAC;QACvC,IAAI,CAAC,sBAAsB,GAAG,IAAI,GAAG,EAAE,CAAC;QACxC,IAAI,CAAC,sBAAsB,GAAG,IAAI,GAAG,EAAE,CAAC;QACxC,IAAI,CAAC,mCAAmC,GAAG,IAAI,GAAG,EAAE,CAAC;QACrD,IAAI,CAAC,oCAAoC,GAAG,IAAI,GAAG,EAAE,CAAC;QACtD,IAAI,CAAC,6BAA6B,GAAG,KAAK,CAAC;QAC3C,IAAI,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AC7E,QAAQ,SAAS,CAAC,IAAI,EAAE,CAAC;gBACvB,KAAK,sCAAwB,CAAC,IAAI,CAAC;gBACnC,KAAK,sCAAwB,CAAC,MAAM,CAAC;gBACrC,KAAK,sCAAwB,CAAC,MAAM,CAAC;gBACrC,KAAK,sCAAwB,CAAC,OAAO;oBACnC,YAAY,CAAC,aAAa,CAAC,GAAG,IAAI,CAAC,SAAS,CAExC,SAKD,CAAC,KAAK,CACR,CAAC;oBACF,MAAM;gBACR,KAAK,sCAAwB,CAAC,UAAU,CAAC;gBACzC,KAAK,sCAAwB,CAAC,WAAW,CAAC;gBAC1C,KAAK,sCAAwB,CAAC,UAAU;oBACtC,MAAM,UAAU,GACd,SAID,CAAC,MAAM,CAAC;oBACT,YAAY,CAAC,aAAa,CAAC,GAAG,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;oBACrE,MAAM;YACV,CAAC;QACH,CAAC;QACD,OAAO,YAAY,CAAC;IACtB,CAAC;IAED;;OAEG;IACI,mBAAmB,CAAC,cAAsB;QAC/C,MAAM,MAAM,GAA2B,gCAAgC,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;QAC7F,IAAI,CAAC,MAAM,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC;YAC9B,MAAM,IAAI,KAAK,CAAC,4BAA4B,cAAc,iBAAiB,CAAC,CAAC;QAC/E,CAAC;QACD,OAAO;YACL,QAAQ,EAAE,KAAK,MAAM,CAAC,MAAM,CAAC,oBAAoB,CAAC,EAAE;YACpD,KAAK,EAAE,MAAM,CAAC,MAAM,CAAC,gBAAgB,CAAC;SACvC,CAAC;IACJ,CAAC;IAED,gBAAgB;IACT,0BAA0B,CAAC,KAAsC;QACtE,IAAI,IAAI,CAALine truncated
@@ -0,0 +1,115 @@
import type * as argparse from 'argparse';
import type { CommandLineAction } from './CommandLineAction';
import { CommandLineParameterProvider, type IRegisterDefinedParametersState } from './CommandLineParameterProvider';
/**
* Options for the {@link CommandLineParser} constructor.
* @public
*/
export interface ICommandLineParserOptions {
/**
* The name of your tool when invoked from the command line
*/
toolFilename: string;
/**
* General documentation that is included in the "--help" main page
*/
toolDescription: string;
/**
* An optional string to append at the end of the "--help" main page. If not provided, an epilog
* will be automatically generated based on the toolFilename.
*/
toolEpilog?: string;
/**
* Set to true to auto-define a tab completion action. False by default.
*/
enableTabCompletionAction?: boolean;
}
/**
* The "argparse" library is a relatively advanced command-line parser with features such
* as word-wrapping and intelligible error messages (that are lacking in other similar
* libraries such as commander, yargs, and nomnom). Unfortunately, its ruby-inspired API
* is awkward to use. The abstract base classes CommandLineParser and CommandLineAction
* provide a wrapper for "argparse" that makes defining and consuming arguments quick
* and simple, and enforces that appropriate documentation is provided for each parameter.
*
* @public
*/
export declare abstract class CommandLineParser extends CommandLineParameterProvider {
/**
* Reports which CommandLineAction was specified on the command line.
* @remarks
* The value will be assigned before onExecute() is invoked.
*/
selectedAction: CommandLineAction | undefined;
private readonly _argumentParser;
private _actionsSubParser;
private readonly _options;
private readonly _actions;
private readonly _actionsByName;
private _executed;
private _tabCompleteActionWasAdded;
constructor(options: ICommandLineParserOptions);
/**
* Returns the list of actions that were defined for this CommandLineParser object.
*/
get actions(): ReadonlyArray<CommandLineAction>;
/**
* Defines a new action that can be used with the CommandLineParser instance.
*/
addAction(action: CommandLineAction): void;
/**
* Retrieves the action with the specified name. If no matching action is found,
* an exception is thrown.
*/
getAction(actionName: string): CommandLineAction;
/**
* Retrieves the action with the specified name. If no matching action is found,
* undefined is returned.
*/
tryGetAction(actionName: string): CommandLineAction | undefined;
/**
* The program entry point will call this method to begin parsing command-line arguments
* and executing the corresponding action.
*
* @remarks
* The returned promise will never reject: If an error occurs, it will be printed
* to stderr, process.exitCode will be set to 1, and the promise will resolve to false.
* This simplifies the most common usage scenario where the program entry point doesn't
* want to be involved with the command-line logic, and will discard the promise without
* a then() or catch() block.
*
* If your caller wants to trap and handle errors, use {@link CommandLineParser.executeWithoutErrorHandlingAsync}
* instead.
*
* @param args - the command-line arguments to be parsed; if omitted, then
* the process.argv will be used
*/
executeAsync(args?: string[]): Promise<boolean>;
/**
* @deprecated Use {@link CommandLineParser.executeAsync} instead.
*/
execute(args?: string[]): Promise<boolean>;
/**
* This is similar to {@link CommandLineParser.executeAsync}, except that execution errors
* simply cause the promise to reject. It is the caller's responsibility to trap
*/
executeWithoutErrorHandlingAsync(args?: string[]): Promise<void>;
/**
* @deprecated Use {@link CommandLineParser.executeWithoutErrorHandlingAsync} instead.
*/
executeWithoutErrorHandling(args?: string[]): Promise<void>;
/** @internal */
_registerDefinedParameters(state: IRegisterDefinedParametersState): void;
private _validateDefinitions;
/**
* {@inheritDoc CommandLineParameterProvider._getArgumentParser}
* @internal
*/
protected _getArgumentParser(): argparse.ArgumentParser;
/**
* This hook allows the subclass to perform additional operations before or after
* the chosen action is executed.
*/
protected onExecute(): Promise<void>;
}
//# sourceMappingURL=CommandLineParser.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"CommandLineParser.d.ts","sourceRoot":"","sources":["../../src/providers/CommandLineParser.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,KAAK,QAAQ,MAAM,UAAU,CAAC;AAG1C,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAE7D,OAAO,EACL,4BAA4B,EAC5B,KAAK,+BAA+B,EAErC,MAAM,gCAAgC,CAAC;AAKxC;;;GAGG;AACH,MAAM,WAAW,yBAAyB;IACxC;;OAEG;IACH,YAAY,EAAE,MAAM,CAAC;IAErB;;OAEG;IACH,eAAe,EAAE,MAAM,CAAC;IAExB;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IAEpB;;OAEG;IACH,yBAAyB,CAAC,EAAE,OAAO,CAAC;CACrC;AAED;;;;;;;;;GASG;AACH,8BAAsB,iBAAkB,SAAQ,4BAA4B;IAC1E;;;;OAIG;IACI,cAAc,EAAE,iBAAi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0,0 +1,283 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
Object.defineProperty(exports, "__esModule", { value: true });
exports.CommandLineParser = void 0;
const terminal_1 = require("@rushstack/terminal");
const CommandLineParameterProvider_1 = require("./CommandLineParameterProvider");
const CommandLineParserExitError_1 = require("./CommandLineParserExitError");
const TabCompletionAction_1 = require("./TabCompletionAction");
const TypeUuidLite_1 = require("../TypeUuidLite");
/**
* The "argparse" library is a relatively advanced command-line parser with features such
* as word-wrapping and intelligible error messages (that are lacking in other similar
* libraries such as commander, yargs, and nomnom). Unfortunately, its ruby-inspired API
* is awkward to use. The abstract base classes CommandLineParser and CommandLineAction
* provide a wrapper for "argparse" that makes defining and consuming arguments quick
* and simple, and enforces that appropriate documentation is provided for each parameter.
*
* @public
*/
class CommandLineParser extends CommandLineParameterProvider_1.CommandLineParameterProvider {
constructor(options) {
var _a, _b;
super();
this._executed = false;
this._tabCompleteActionWasAdded = false;
this._options = options;
this._actions = [];
this._actionsByName = new Map();
this._argumentParser = new CommandLineParserExitError_1.CustomArgumentParser({
addHelp: true,
prog: this._options.toolFilename,
description: this._options.toolDescription,
epilog: terminal_1.Colorize.bold((_a = this._options.toolEpilog) !== null && _a !== void 0 ? _a : `For detailed help about a specific command, use: ${this._options.toolFilename} <command> -h`)
});
(_b = this.onDefineParameters) === null || _b === void 0 ? void 0 : _b.call(this);
}
/**
* Returns the list of actions that were defined for this CommandLineParser object.
*/
get actions() {
return this._actions;
}
/**
* Defines a new action that can be used with the CommandLineParser instance.
*/
addAction(action) {
if (!this._actionsSubParser) {
this._actionsSubParser = this._argumentParser.addSubparsers({
metavar: '<command>',
dest: 'action'
});
}
action._buildParser(this._actionsSubParser);
this._actions.push(action);
this._actionsByName.set(action.actionName, action);
}
/**
* Retrieves the action with the specified name. If no matching action is found,
* an exception is thrown.
*/
getAction(actionName) {
const action = this.tryGetAction(actionName);
if (!action) {
throw new Error(`The action "${actionName}" was not defined`);
}
return action;
}
/**
* Retrieves the action with the specified name. If no matching action is found,
* undefined is returned.
*/
tryGetAction(actionName) {
return this._actionsByName.get(actionName);
}
/**
* The program entry point will call this method to begin parsing command-line arguments
* and executing the corresponding action.
*
* @remarks
* The returned promise will never reject: If an error occurs, it will be printed
* to stderr, process.exitCode will be set to 1, and the promise will resolve to false.
* This simplifies the most common usage scenario where the program entry point doesn't
* want to be involved with the command-line logic, and will discard the promise without
* a then() or catch() block.
*
* If your caller wants to trap and handle errors, use {@link CommandLineParser.executeWithoutErrorHandlingAsync}
* instead.
*
* @param args - the command-line arguments to be parsed; if omitted, then
* the process.argv will be used
*/
async executeAsync(args) {
if (this._options.enableTabCompletionAction && !this._tabCompleteActionWasAdded) {
this.addAction(new TabCompletionAction_1.TabCompleteAction(this.actions, this.parameters));
this._tabCompleteActionWasAdded = true;
}
try {
await this.executeWithoutErrorHandlingAsync(args);
return true;
}
catch (err) {
if (err instanceof CommandLineParserExitError_1.CommandLineParserExitError) {
// executeWithoutErrorHandlingAsync() handles the successful cases,
// so here we can assume err has a nonzero exit code
if (err.message) {
// eslint-disable-next-line no-console
console.error(err.message);
}
if (!process.exitCode) {
process.exitCode = err.exitCode;
}
}
else if (TypeUuidLite_1.TypeUuid.isInstanceOf(err, TypeUuidLite_1.uuidAlreadyReportedError)) {
// AlreadyReportedError
if (!process.exitCode) {
process.exitCode = 1;
}
}
else {
let message = (err.message || 'An unknown error occurred').trim();
// If the message doesn't already start with "Error:" then add a prefix
if (!/^(error|internal error|warning)\b/i.test(message)) {
message = 'Error: ' + message;
}
// eslint-disable-next-line no-console
console.error();
// eslint-disable-next-line no-console
console.error(terminal_1.Colorize.red(message));
if (!process.exitCode) {
process.exitCode = 1;
}
}
return false;
}
}
/**
* @deprecated Use {@link CommandLineParser.executeAsync} instead.
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
async execute(args) {
return await this.executeAsync(args);
}
/**
* This is similar to {@link CommandLineParser.executeAsync}, except that execution errors
* simply cause the promise to reject. It is the caller's responsibility to trap
*/
async executeWithoutErrorHandlingAsync(args) {
var _a, _b;
try {
if (this._executed) {
// In the future we could allow the same parser to be invoked multiple times
// with different arguments. We'll do that work as soon as someone encounters
// a real world need for it.
throw new Error('executeAsync() was already called for this parser instance');
}
this._executed = true;
this._validateDefinitions();
// Register the parameters before we print help or parse the CLI
const initialState = {
parentParameterNames: new Set()
};
this._registerDefinedParameters(initialState);
if (!args) {
// 0=node.exe, 1=script name
args = process.argv.slice(2);
}
if (this.actions.length > 0) {
if (args.length === 0) {
// Parsers that use actions should print help when 0 args are provided. Allow
// actionless parsers to continue on zero args.
this._argumentParser.printHelp();
return;
}
// Alias actions may provide a list of default params to add after the action name.
// Since we don't know which params are required and which are optional, perform a
// manual search for the action name to obtain the default params and insert them if
// any are found. We will guess that the action name is the first arg that doesn't
// start with a hyphen.
const actionNameIndex = args.findIndex((x) => !x.startsWith('-'));
if (actionNameIndex !== undefined) {
const actionName = args[actionNameIndex];
const action = this.tryGetAction(actionName);
const aliasAction = action;
if ((_a = aliasAction === null || aliasAction === void 0 ? void 0 : aliasAction.defaultParameters) === null || _a === void 0 ? void 0 : _a.length) {
const insertIndex = actionNameIndex + 1;
args = args.slice(0, insertIndex).concat(aliasAction.defaultParameters, args.slice(insertIndex));
}
}
}
const postParse = () => {
this._postParse();
for (const action of this.actions) {
action._postParse();
}
};
function patchFormatUsageForArgumentParser(argumentParser) {
const originalFormatUsage = argumentParser.formatUsage.bind(argumentParser);
argumentParser.formatUsage = () => {
postParse();
return originalFormatUsage();
};
}
this._preParse();
patchFormatUsageForArgumentParser(this._argumentParser);
for (const action of this.actions) {
action._preParse();
patchFormatUsageForArgumentParser(action._getArgumentParser());
}
const data = this._argumentParser.parseArgs(args);
postParse();
this._processParsedData(this._options, data);
this.selectedAction = this.tryGetAction(data.action);
if (this.actions.length > 0 && !this.selectedAction) {
const actions = this.actions.map((x) => x.actionName);
throw new Error(`An action must be specified (${actions.join(', ')})`);
}
(_b = this.selectedAction) === null || _b === void 0 ? void 0 : _b._processParsedData(this._options, data);
await this.onExecute();
}
catch (err) {
if (err instanceof CommandLineParserExitError_1.CommandLineParserExitError) {
if (!err.exitCode) {
// non-error exit modeled using exception handling
if (err.message) {
// eslint-disable-next-line no-console
console.log(err.message);
}
return;
}
}
throw err;
}
}
/**
* @deprecated Use {@link CommandLineParser.executeWithoutErrorHandlingAsync} instead.
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
async executeWithoutErrorHandling(args) {
await this.executeWithoutErrorHandlingAsync(args);
}
/** @internal */
_registerDefinedParameters(state) {
super._registerDefinedParameters(state);
const { parentParameterNames } = state;
const updatedParentParameterNames = new Set([
...parentParameterNames,
...this._registeredParameterParserKeysByName.keys()
]);
const parentState = {
...state,
parentParameterNames: updatedParentParameterNames
};
for (const action of this._actions) {
action._registerDefinedParameters(parentState);
}
}
_validateDefinitions() {
if (this.remainder && this.actions.length > 0) {
// This is apparently not supported by argparse
throw new Error('defineCommandLineRemainder() cannot be called for a CommandLineParser with actions');
}
}
/**
* {@inheritDoc CommandLineParameterProvider._getArgumentParser}
* @internal
*/
_getArgumentParser() {
// override
return this._argumentParser;
}
/**
* This hook allows the subclass to perform additional operations before or after
* the chosen action is executed.
*/
async onExecute() {
if (this.selectedAction) {
await this.selectedAction._executeAsync();
}
}
}
exports.CommandLineParser = CommandLineParser;
//# sourceMappingURL=CommandLineParser.js.map
@@ -0,0 +1 @@
{"version":3,"file":"CommandLineParser.js","sourceRoot":"","sources":["../../src/providers/CommandLineParser.ts"],"names":[],"mappings":";AAAA,4FAA4F;AAC5F,2DAA2D;;;AAG3D,kDAA+C;AAI/C,iFAIwC;AACxC,6EAAgG;AAChG,+DAA0D;AAC1D,kDAAqE;AA6BrE;;;;;;;;;GASG;AACH,MAAsB,iBAAkB,SAAQ,2DAA4B;IAgB1E,YAAmB,OAAkC;;QACnD,KAAK,EAAE,CAAC;QAJF,cAAS,GAAY,KAAK,CAAC;QAC3B,+BAA0B,GAAY,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C,CAAC;YAEF,SAAS,iCAAiC,CAAC,cAAuC;gBAChF,MAAM,mBAAmB,GAAiB,cAAc,CAAC,WAAW,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;gBAC1F,cAAc,CAAC,WAAW,GAAG,GAAG,EAAE;oBAChC,SAAS,EAAE,CAAC;oBACZ,OAAO,mBAAmB,EAAE,CAAC;gBAC/B,CAAC,CAAC;YACJ,CAAC;YAED,IAAI,CAAC,SAAS,EAAE,CAAC;YACjB,iCAAiC,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;YACxD,KAAK,MAAM,MAAM,IAAI,IAAI,CAAC,OAAO,EAAE,CAAC;gBAClC,MAAM,CAAC,SAAS,EAAE,CAAC;gBACnB,iCAAiC,CAAC,MAAM,CAAC,kBAAkB,EAAE,CAAC,CAAC;YACjE,CAAC;YAED,MAAM,IAALine truncated
@@ -0,0 +1,10 @@
import * as argparse from 'argparse';
export declare class CommandLineParserExitError extends Error {
readonly exitCode: number;
constructor(exitCode: number, message: string);
}
export declare class CustomArgumentParser extends argparse.ArgumentParser {
exit(status: number, message: string): void;
error(err: Error | string): void;
}
//# sourceMappingURL=CommandLineParserExitError.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"CommandLineParserExitError.d.ts","sourceRoot":"","sources":["../../src/providers/CommandLineParserExitError.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,QAAQ,MAAM,UAAU,CAAC;AAErC,qBAAa,0BAA2B,SAAQ,KAAK;IACnD,SAAgB,QAAQ,EAAE,MAAM,CAAC;gBAEd,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM;CAWrD;AAED,qBAAa,oBAAqB,SAAQ,QAAQ,CAAC,cAAc;IACxD,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,IAAI;IAK3C,KAAK,CAAC,GAAG,EAAE,KAAK,GAAG,MAAM,GAAG,IAAI;CASxC"}
@@ -0,0 +1,67 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.CustomArgumentParser = exports.CommandLineParserExitError = void 0;
const argparse = __importStar(require("argparse"));
class CommandLineParserExitError extends Error {
constructor(exitCode, message) {
super(message);
// Manually set the prototype, as we can no longer extend built-in classes like Error, Array, Map, etc
// https://github.com/microsoft/TypeScript-wiki/blob/main/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
//
// Note: the prototype must also be set on any classes which extend this one
this.__proto__ = CommandLineParserExitError.prototype; // eslint-disable-line @typescript-eslint/no-explicit-any
this.exitCode = exitCode;
}
}
exports.CommandLineParserExitError = CommandLineParserExitError;
class CustomArgumentParser extends argparse.ArgumentParser {
exit(status, message) {
// override
throw new CommandLineParserExitError(status, message);
}
error(err) {
// override
// Ensure the ParserExitError bubbles up to the top without any special processing
if (err instanceof CommandLineParserExitError) {
throw err;
}
super.error(err);
}
}
exports.CustomArgumentParser = CustomArgumentParser;
//# sourceMappingURL=CommandLineParserExitError.js.map
@@ -0,0 +1 @@
{"version":3,"file":"CommandLineParserExitError.js","sourceRoot":"","sources":["../../src/providers/CommandLineParserExitError.ts"],"names":[],"mappings":";AAAA,4FAA4F;AAC5F,2DAA2D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAE3D,mDAAqC;AAErC,MAAa,0BAA2B,SAAQ,KAAK;IAGnD,YAAmB,QAAgB,EAAE,OAAe;QAClD,KAAK,CAAC,OAAO,CAAC,CAAC;QAEf,sGAAsG;QACtG,6IAA6I;QAC7I,EAAE;QACF,4EAA4E;QAC3E,IAAY,CAAC,SAAS,GAAG,0BAA0B,CAAC,SAAS,CAAC,CAAC,yDAAyD;QAEzH,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC3B,CAAC;CACF;AAdD,gEAcC;AAED,MAAa,oBAAqB,SAAQ,QAAQ,CAAC,cAAc;IACxD,IAAI,CAAC,MAAc,EAAE,OAAe;QACzC,WAAW;QACX,MAAM,IAAI,0BAA0B,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACxD,CAAC;IAEM,KAAK,CAAC,GAAmB;QAC9B,WAAW;QACX,kFAAkF;QAClF,IAAI,GAAG,YAAY,0BAA0B,EAAE,CAAC;YAC9C,MAAM,GAAG,CAAC;QACZ,CAAC;QAED,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACnB,CAAC;CACF;AAfD,oDAeC","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 * as argparse from 'argparse';\n\nexport class CommandLineParserExitError extends Error {\n public readonly exitCode: number;\n\n public constructor(exitCode: number, message: string) {\n super(message);\n\n // Manually set the prototype, as we can no longer extend built-in classes like Error, Array, Map, etc\n // https://github.com/microsoft/TypeScript-wiki/blob/main/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n //\n // Note: the prototype must also be set on any classes which extend this one\n (this as any).__proto__ = CommandLineParserExitError.prototype; // eslint-disable-line @typescript-eslint/no-explicit-any\n\n this.exitCode = exitCode;\n }\n}\n\nexport class CustomArgumentParser extends argparse.ArgumentParser {\n public exit(status: number, message: string): void {\n // override\n throw new CommandLineParserExitError(status, message);\n }\n\n public error(err: Error | string): void {\n // override\n // Ensure the ParserExitError bubbles up to the top without any special processing\n if (err instanceof CommandLineParserExitError) {\n throw err;\n }\n\n super.error(err);\n }\n}\n"]}
@@ -0,0 +1,8 @@
import { CommandLineAction } from './CommandLineAction';
/**
* @public
*/
export declare class DynamicCommandLineAction extends CommandLineAction {
protected onExecute(): Promise<void>;
}
//# sourceMappingURL=DynamicCommandLineAction.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"DynamicCommandLineAction.d.ts","sourceRoot":"","sources":["../../src/providers/DynamicCommandLineAction.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAExD;;GAEG;AACH,qBAAa,wBAAyB,SAAQ,iBAAiB;cAC7C,SAAS,IAAI,OAAO,CAAC,IAAI,CAAC;CAI3C"}
@@ -0,0 +1,17 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
Object.defineProperty(exports, "__esModule", { value: true });
exports.DynamicCommandLineAction = void 0;
const CommandLineAction_1 = require("./CommandLineAction");
/**
* @public
*/
class DynamicCommandLineAction extends CommandLineAction_1.CommandLineAction {
async onExecute() {
// abstract
// (handled by the external code)
}
}
exports.DynamicCommandLineAction = DynamicCommandLineAction;
//# sourceMappingURL=DynamicCommandLineAction.js.map
@@ -0,0 +1 @@
{"version":3,"file":"DynamicCommandLineAction.js","sourceRoot":"","sources":["../../src/providers/DynamicCommandLineAction.ts"],"names":[],"mappings":";AAAA,4FAA4F;AAC5F,2DAA2D;;;AAE3D,2DAAwD;AAExD;;GAEG;AACH,MAAa,wBAAyB,SAAQ,qCAAiB;IACnD,KAAK,CAAC,SAAS;QACvB,WAAW;QACX,iCAAiC;IACnC,CAAC;CACF;AALD,4DAKC","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 { CommandLineAction } from './CommandLineAction';\n\n/**\n * @public\n */\nexport class DynamicCommandLineAction extends CommandLineAction {\n protected async onExecute(): Promise<void> {\n // abstract\n // (handled by the external code)\n }\n}\n"]}
@@ -0,0 +1,7 @@
import { CommandLineParser } from './CommandLineParser';
/**
* @public
*/
export declare class DynamicCommandLineParser extends CommandLineParser {
}
//# sourceMappingURL=DynamicCommandLineParser.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"DynamicCommandLineParser.d.ts","sourceRoot":"","sources":["../../src/providers/DynamicCommandLineParser.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAExD;;GAEG;AACH,qBAAa,wBAAyB,SAAQ,iBAAiB;CAAG"}
@@ -0,0 +1,13 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
Object.defineProperty(exports, "__esModule", { value: true });
exports.DynamicCommandLineParser = void 0;
const CommandLineParser_1 = require("./CommandLineParser");
/**
* @public
*/
class DynamicCommandLineParser extends CommandLineParser_1.CommandLineParser {
}
exports.DynamicCommandLineParser = DynamicCommandLineParser;
//# sourceMappingURL=DynamicCommandLineParser.js.map
@@ -0,0 +1 @@
{"version":3,"file":"DynamicCommandLineParser.js","sourceRoot":"","sources":["../../src/providers/DynamicCommandLineParser.ts"],"names":[],"mappings":";AAAA,4FAA4F;AAC5F,2DAA2D;;;AAE3D,2DAAwD;AAExD;;GAEG;AACH,MAAa,wBAAyB,SAAQ,qCAAiB;CAAG;AAAlE,4DAAkE","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 { CommandLineParser } from './CommandLineParser';\n\n/**\n * @public\n */\nexport class DynamicCommandLineParser extends CommandLineParser {}\n"]}
@@ -0,0 +1,84 @@
import { SCOPING_PARAMETER_GROUP } from '../Constants';
import { CommandLineAction, type ICommandLineActionOptions } from './CommandLineAction';
import { CommandLineParser, type ICommandLineParserOptions } from './CommandLineParser';
import type { CommandLineParameter, CommandLineParameterBase } from '../parameters/BaseClasses';
import type { CommandLineParameterProvider, ICommandLineParserData, IRegisterDefinedParametersState } from './CommandLineParameterProvider';
/**
* Represents a sub-command that is part of the CommandLineParser command-line.
* Applications should create subclasses of ScopedCommandLineAction corresponding to
* each action that they want to expose.
*
* The action name should be comprised of lower case words separated by hyphens
* or colons. The name should include an English verb (e.g. "deploy"). Use a
* hyphen to separate words (e.g. "upload-docs"). A group of related commands
* can be prefixed with a colon (e.g. "docs:generate", "docs:deploy",
* "docs:serve", etc).
*
* Scoped commands allow for different parameters to be specified for different
* provided scoping values. For example, the "scoped-action --scope A" command
* may allow for different scoped arguments to be specified than the "scoped-action
* --scope B" command.
*
* Scoped arguments are specified after the "--" pseudo-argument. For example,
* "scoped-action --scope A -- --scopedFoo --scopedBar".
*
* @public
*/
export declare abstract class ScopedCommandLineAction extends CommandLineAction {
private _options;
private _scopingParameters;
private _unscopedParserOptions;
private _scopedCommandLineParser;
private _subparserState;
/**
* The required group name to apply to all scoping parameters. At least one parameter
* must be defined with this group name.
*/
static readonly ScopingParameterGroup: typeof SCOPING_PARAMETER_GROUP;
constructor(options: ICommandLineActionOptions);
/**
* {@inheritDoc CommandLineParameterProvider.parameters}
*
* @internalremarks
* TODO: Replace this type with `CommandLineParameter` in the next major bump.
*/
get parameters(): ReadonlyArray<CommandLineParameterBase>;
/**
* {@inheritdoc CommandLineParameterProvider._processParsedData}
* @internal
*/
_processParsedData(parserOptions: ICommandLineParserOptions, data: ICommandLineParserData): void;
/**
* {@inheritdoc CommandLineAction._executeAsync}
* @internal
*/
_executeAsync(): Promise<void>;
/** @internal */
_registerDefinedParameters(state: IRegisterDefinedParametersState): void;
/**
* Retrieves the scoped CommandLineParser, which is populated after the ScopedCommandLineAction is executed.
* @internal
*/
protected _getScopedCommandLineParser(): CommandLineParser;
/** @internal */
protected _defineParameter(parameter: CommandLineParameter): void;
/**
* @deprecated - Define parameters in the constructor
*/
protected onDefineUnscopedParameters?(): void;
/**
* The child class should implement this hook to define its scoped command-line
* parameters, e.g. by calling scopedParameterProvider.defineFlagParameter(). These
* parameters will only be available if the action is invoked with a scope.
*
* @remarks
* onDefineScopedParameters is called after the unscoped parameters have been parsed.
* The values they provide can be used to vary the defined scope parameters.
*/
protected abstract onDefineScopedParameters(scopedParameterProvider: CommandLineParameterProvider): void;
/**
* {@inheritDoc CommandLineAction.onExecute}
*/
protected abstract onExecute(): Promise<void>;
}
//# sourceMappingURL=ScopedCommandLineAction.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"ScopedCommandLineAction.d.ts","sourceRoot":"","sources":["../../src/providers/ScopedCommandLineAction.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,uBAAuB,EAAE,MAAM,cAAc,CAAC;AACvD,OAAO,EAAE,iBAAiB,EAAE,KAAK,yBAAyB,EAAE,MAAM,qBAAqB,CAAC;AACxF,OAAO,EAAE,iBAAiB,EAAE,KAAK,yBAAyB,EAAE,MAAM,qBAAqB,CAAC;AAExF,OAAO,KAAK,EAAE,oBAAoB,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AAChG,OAAO,KAAK,EACV,4BAA4B,EAC5B,sBAAsB,EACtB,+BAA+B,EAChC,MAAM,gCAAgC,CAAC;AAmExC;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,8BAAsB,uBAAwB,SAAQ,iBAAiB;IACrE,OAAO,CAAC,QAAQ,CAA4B;IAC5C,OAAO,CAAC,kBAAkB,CAAyB;IACnD,OAAO,CAAC,sBAAsB,CAAwC;IACtE,OAAO,CAAC,wBAAwB,CAA8C;IAC9E,OAAO,CAAC,eAAe,CAA8C;IAErE;;;OAGG;IACH,gBAAuB,qBAAqB,EAAE,OAAO,uBAAuB,CAA2B;gBAEpF,OAAO,EAAE,yBAAyB;IAkBrD;;;;;OAKG;IACH,IAAW,UAAU,IAAI,aAAa,CAAC,wBAAwB,CAAC,CAM/D;IAED;;;OAGG;IACI,kBAAkB,CAAC,aAAa,EAAE,yBAAyB,EAAE,IAAI,EAAE,sBAAsB,GAAG,IAAI;IAyBvG;;;OAGG;IACU,aAAa,IAAI,OAAO,CAAC,IAAI,CAAC;IAuC3C,gBAAgB;IACT,0BAA0B,CAAC,KAAK,EAAE,+BAA+B,GAAG,IAAI;IAuB/E;;;OAGG;IACH,SAAS,CAAC,2BAA2B,IAAI,iBAAiB;IAO1D,gBAAgB;IAChB,SAAS,CAAC,gBAAgB,CAAC,SAAS,EAAE,oBAAoB,GAAG,IAAI;IAOjE;;OAEG;IACH,SAAS,CAAC,0BAA0B,CAAC,IAAI,IAAI;IAE7C;;;;;;;;OAQG;IACH,SAAS,CAAC,QAAQ,CAAC,wBAAwB,CAAC,uBAAuB,EAAE,4BAA4B,GAAG,IAAI;IAExG;;OAEG;IACH,SAAS,CAAC,QAAQ,CAAC,SAAS,IAAI,OAAO,CAAC,IAAI,CAAC;CAC9C"}
@@ -0,0 +1,209 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
Object.defineProperty(exports, "__esModule", { value: true });
exports.ScopedCommandLineAction = void 0;
const Constants_1 = require("../Constants");
const CommandLineAction_1 = require("./CommandLineAction");
const CommandLineParser_1 = require("./CommandLineParser");
const CommandLineParserExitError_1 = require("./CommandLineParserExitError");
/**
* A CommandLineParser used exclusively to parse the scoped command-line parameters
* for a ScopedCommandLineAction.
*/
class InternalScopedCommandLineParser extends CommandLineParser_1.CommandLineParser {
get canExecute() {
return this._canExecute;
}
constructor(options) {
const { actionOptions, unscopedActionParameters, toolFilename, aliasAction, aliasDocumentation } = options;
const toolCommand = `${toolFilename} ${actionOptions.actionName}`;
// When coming from an alias command, we want to show the alias command name in the help text
const toolCommandForLogging = `${toolFilename} ${aliasAction !== null && aliasAction !== void 0 ? aliasAction : actionOptions.actionName}`;
const scopingArgs = [];
for (const parameter of unscopedActionParameters) {
parameter.appendToArgList(scopingArgs);
}
const scope = scopingArgs.join(' ');
// We can run the parser directly because we are not going to use it for any other actions,
// so construct a special options object to make the "--help" text more useful.
const scopedCommandLineParserOptions = {
// Strip the scoping args if coming from an alias command, since they are not applicable
// to the alias command itself
toolFilename: `${toolCommandForLogging}${scope && !aliasAction ? ` ${scope} --` : ''}`,
toolDescription: aliasDocumentation !== null && aliasDocumentation !== void 0 ? aliasDocumentation : actionOptions.documentation,
toolEpilog: `For more information on available unscoped parameters, use "${toolCommand} --help"`,
enableTabCompletionAction: false
};
super(scopedCommandLineParserOptions);
this._canExecute = false;
this._internalOptions = options;
this._internalOptions.onDefineScopedParameters(this);
}
_registerDefinedParameters(state) {
// Since we are in a separate parser, we need to register the parameters using the state
// from the parent parser.
super._registerDefinedParameters(this._internalOptions.registerDefinedParametersState);
}
async onExecute() {
// override
// Only set if we made it this far, which may not be the case if an error occurred or
// if '--help' was specified.
this._canExecute = true;
}
}
/**
* Represents a sub-command that is part of the CommandLineParser command-line.
* Applications should create subclasses of ScopedCommandLineAction corresponding to
* each action that they want to expose.
*
* The action name should be comprised of lower case words separated by hyphens
* or colons. The name should include an English verb (e.g. "deploy"). Use a
* hyphen to separate words (e.g. "upload-docs"). A group of related commands
* can be prefixed with a colon (e.g. "docs:generate", "docs:deploy",
* "docs:serve", etc).
*
* Scoped commands allow for different parameters to be specified for different
* provided scoping values. For example, the "scoped-action --scope A" command
* may allow for different scoped arguments to be specified than the "scoped-action
* --scope B" command.
*
* Scoped arguments are specified after the "--" pseudo-argument. For example,
* "scoped-action --scope A -- --scopedFoo --scopedBar".
*
* @public
*/
class ScopedCommandLineAction extends CommandLineAction_1.CommandLineAction {
constructor(options) {
var _a;
super(options);
this._options = options;
this._scopingParameters = [];
// Consume the remainder of the command-line, which will later be passed the scoped parser.
// This will also prevent developers from calling this.defineCommandLineRemainder(...) since
// we will have already defined it.
this.defineCommandLineRemainder({
description: 'Scoped parameters. Must be prefixed with "--", ex. "-- --scopedParameter ' +
'foo --scopedFlag". For more information on available scoped parameters, use "-- --help".'
});
(_a = this.onDefineUnscopedParameters) === null || _a === void 0 ? void 0 : _a.call(this);
}
/**
* {@inheritDoc CommandLineParameterProvider.parameters}
*
* @internalremarks
* TODO: Replace this type with `CommandLineParameter` in the next major bump.
*/
get parameters() {
if (this._scopedCommandLineParser) {
return [...super.parameters, ...this._scopedCommandLineParser.parameters];
}
else {
return super.parameters;
}
}
/**
* {@inheritdoc CommandLineParameterProvider._processParsedData}
* @internal
*/
_processParsedData(parserOptions, data) {
// override
super._processParsedData(parserOptions, data);
// This should never happen because the super method should throw if parameters haven't been registered,
// but guard against this just in-case.
if (this._subparserState === undefined) {
throw new Error('Parameters have not been registered');
}
this._unscopedParserOptions = parserOptions;
// Generate the scoped parser using the parent parser information. We can only create this after we
// have parsed the data, since the parameter values are used during construction.
this._scopedCommandLineParser = new InternalScopedCommandLineParser({
...parserOptions,
actionOptions: this._options,
aliasAction: data.aliasAction,
aliasDocumentation: data.aliasDocumentation,
unscopedActionParameters: this.parameters,
registerDefinedParametersState: this._subparserState,
onDefineScopedParameters: this.onDefineScopedParameters.bind(this)
});
}
/**
* {@inheritdoc CommandLineAction._executeAsync}
* @internal
*/
async _executeAsync() {
// override
if (!this._unscopedParserOptions || !this._scopedCommandLineParser) {
throw new Error('The CommandLineAction parameters must be processed before execution.');
}
if (!this.remainder) {
throw new Error('CommandLineAction.onDefineParameters must be called before execution.');
}
// The '--' argument is required to separate the action parameters from the scoped parameters,
// so it needs to be trimmed. If remainder values are provided but no '--' is found, then throw.
const scopedArgs = [];
if (this.remainder.values.length) {
if (this.remainder.values[0] !== '--') {
throw new CommandLineParserExitError_1.CommandLineParserExitError(
// argparse sets exit code 2 for invalid arguments
2,
// model the message off of the built-in "unrecognized arguments" message
`${this.renderUsageText()}\n${this._unscopedParserOptions.toolFilename} ${this.actionName}: ` +
`error: Unrecognized arguments: ${this.remainder.values[0]}.\n`);
}
for (const scopedArg of this.remainder.values.slice(1)) {
scopedArgs.push(scopedArg);
}
}
// Call the scoped parser using only the scoped args to handle parsing
await this._scopedCommandLineParser.executeWithoutErrorHandlingAsync(scopedArgs);
// Only call execute if the parser reached the execute stage. This may not be true if
// the parser exited early due to a specified '--help' parameter.
if (this._scopedCommandLineParser.canExecute) {
await super._executeAsync();
}
return;
}
/** @internal */
_registerDefinedParameters(state) {
if (!this._scopingParameters.length) {
throw new Error('No scoping parameters defined. At least one scoping parameter must be defined. ' +
'Scoping parameters are defined by setting the parameterGroupName to ' +
'ScopedCommandLineAction.ScopingParameterGroupName.');
}
super._registerDefinedParameters(state);
const { parentParameterNames } = state;
const updatedParentParameterNames = new Set([
...parentParameterNames,
...this._registeredParameterParserKeysByName.keys()
]);
this._subparserState = {
...state,
parentParameterNames: updatedParentParameterNames
};
}
/**
* Retrieves the scoped CommandLineParser, which is populated after the ScopedCommandLineAction is executed.
* @internal
*/
_getScopedCommandLineParser() {
if (!this._scopedCommandLineParser) {
throw new Error('The scoped CommandLineParser is only populated after the action is executed.');
}
return this._scopedCommandLineParser;
}
/** @internal */
_defineParameter(parameter) {
super._defineParameter(parameter);
if (parameter.parameterGroup === ScopedCommandLineAction.ScopingParameterGroup) {
this._scopingParameters.push(parameter);
}
}
}
exports.ScopedCommandLineAction = ScopedCommandLineAction;
/**
* The required group name to apply to all scoping parameters. At least one parameter
* must be defined with this group name.
*/
ScopedCommandLineAction.ScopingParameterGroup = Constants_1.SCOPING_PARAMETER_GROUP;
//# sourceMappingURL=ScopedCommandLineAction.js.map
@@ -0,0 +1 @@
{"version":3,"file":"ScopedCommandLineAction.js","sourceRoot":"","sources":["../../src/providers/Sc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BAAwB,CAAC;IACvC,CAAC;IAED,gBAAgB;IACN,gBAAgB,CAAC,SAA+B;QACxD,KAAK,CAAC,gBAAgB,CAAC,SAAS,CAAC,CAAC;QAClC,IAAI,SAAS,CAAC,cAAc,KAAK,uBAAuB,CAAC,qBAAqB,EAAE,CAAC;YAC/E,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QAC1C,CAAC;IACH,CAAC;;AA9JH,0DAoLC;AA7KC;;;GAGG;AACoB,6CAAqB,GAAmC,mCAAuB,CAAC","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 { SCOPING_PARAMETER_GROUP } from '../Constants';\nimport { CommandLineAction, type ICommandLineActionOptions } from './CommandLineAction';\nimport { CommandLineParser, type ICommandLineParserOptionsLine truncated
@@ -0,0 +1,17 @@
import { type CommandLineParameterBase } from '../parameters/BaseClasses';
import { CommandLineAction } from './CommandLineAction';
export declare class TabCompleteAction extends CommandLineAction {
private readonly _wordToCompleteParameter;
private readonly _positionParameter;
private readonly _actions;
private readonly _globalParameters;
constructor(actions: ReadonlyArray<CommandLineAction>, globalParameters: ReadonlyArray<CommandLineParameterBase>);
protected onExecute(): Promise<void>;
getCompletionsAsync(commandLine: string, caretPosition?: number): AsyncIterable<string>;
private _getAllActions;
tokenizeCommandLine(commandLine: string): string[];
private _getParameterValueCompletionsAsync;
private _getGlobalParameterOffset;
private _completeParameterValues;
}
//# sourceMappingURL=TabCompletionAction.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"TabCompletionAction.d.ts","sourceRoot":"","sources":["../../src/providers/TabCompletionAction.ts"],"names":[],"mappings":"AAOA,OAAO,EAEL,KAAK,wBAAwB,EAG9B,MAAM,2BAA2B,CAAC;AAEnC,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAMxD,qBAAa,iBAAkB,SAAQ,iBAAiB;IACtD,OAAO,CAAC,QAAQ,CAAC,wBAAwB,CAAsC;IAC/E,OAAO,CAAC,QAAQ,CAAC,kBAAkB,CAAuC;IAC1E,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAiD;IAC1E,OAAO,CAAC,QAAQ,CAAC,iBAAiB,CAAoC;gBAGpE,OAAO,EAAE,aAAa,CAAC,iBAAiB,CAAC,EACzC,gBAAgB,EAAE,aAAa,CAAC,wBAAwB,CAAC;cA2C3C,SAAS,IAAI,OAAO,CAAC,IAAI,CAAC;IAU5B,mBAAmB,CAC/B,WAAW,EAAE,MAAM,EACnB,aAAa,GAAE,MAA2B,GACzC,aAAa,CAAC,MAAM,CAAC;IAiFxB,OAAO,CAAE,cAAc;IAKhB,mBAAmB,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM,EAAE;YAI3C,kCAAkC;IA0BhD,OAAO,CAAC,yBAAyB;IAgBjC,OAAO,CAAE,wBAAwB;CAUlC"}
@@ -0,0 +1,173 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TabCompleteAction = void 0;
const string_argv_1 = __importDefault(require("string-argv"));
const BaseClasses_1 = require("../parameters/BaseClasses");
const CommandLineChoiceParameter_1 = require("../parameters/CommandLineChoiceParameter");
const CommandLineAction_1 = require("./CommandLineAction");
const Constants_1 = require("../Constants");
const DEFAULT_WORD_TO_AUTOCOMPLETE = '';
const DEFAULT_POSITION = 0;
class TabCompleteAction extends CommandLineAction_1.CommandLineAction {
constructor(actions, globalParameters) {
super({
actionName: Constants_1.CommandLineConstants.TabCompletionActionName,
summary: 'Provides tab completion.',
documentation: 'Provides tab completion.'
});
this._actions = new Map();
for (const action of actions) {
const parameterNameToParameterInfoMap = new Map();
for (const parameter of action.parameters) {
parameterNameToParameterInfoMap.set(parameter.longName, parameter);
if (parameter.shortName) {
parameterNameToParameterInfoMap.set(parameter.shortName, parameter);
}
}
this._actions.set(action.actionName, parameterNameToParameterInfoMap);
}
this._globalParameters = new Map();
for (const parameter of globalParameters) {
this._globalParameters.set(parameter.longName, parameter);
if (parameter.shortName) {
this._globalParameters.set(parameter.shortName, parameter);
}
}
this._wordToCompleteParameter = this.defineStringParameter({
parameterLongName: '--word',
argumentName: 'WORD',
description: `The word to complete.`,
defaultValue: DEFAULT_WORD_TO_AUTOCOMPLETE
});
this._positionParameter = this.defineIntegerParameter({
parameterLongName: '--position',
argumentName: 'INDEX',
description: `The position in the word to be completed.`,
defaultValue: DEFAULT_POSITION
});
}
async onExecute() {
const commandLine = this._wordToCompleteParameter.value;
const caretPosition = this._positionParameter.value || commandLine.length;
for await (const value of this.getCompletionsAsync(commandLine, caretPosition)) {
// eslint-disable-next-line no-console
console.log(value);
}
}
async *getCompletionsAsync(commandLine, caretPosition = commandLine.length) {
const actions = this._actions;
if (!commandLine || !caretPosition) {
yield* this._getAllActions();
return;
}
const tokens = Array.from(this.tokenizeCommandLine(commandLine));
// offset arguments by the number of global params in the input
const globalParameterOffset = this._getGlobalParameterOffset(tokens);
if (tokens.length < 2 + globalParameterOffset) {
yield* this._getAllActions();
return;
}
const lastToken = tokens[tokens.length - 1];
const secondLastToken = tokens[tokens.length - 2];
const lastCharacterIsWhitespace = !commandLine.slice(-1).trim();
const completePartialWord = caretPosition === commandLine.length && !lastCharacterIsWhitespace;
if (completePartialWord && tokens.length === 2 + globalParameterOffset) {
for (const actionName of actions.keys()) {
if (actionName.indexOf(tokens[1 + globalParameterOffset]) === 0) {
yield actionName;
}
}
}
else {
for (const actionName of actions.keys()) {
if (actionName === tokens[1 + globalParameterOffset]) {
const parameterNameMap = actions.get(actionName);
const parameterNames = Array.from(parameterNameMap.keys());
if (completePartialWord) {
for (const parameterName of parameterNames) {
if (parameterName === secondLastToken) {
const values = await this._getParameterValueCompletionsAsync(parameterNameMap.get(parameterName));
if (values.size > 0) {
yield* this._completeParameterValues(values, lastToken);
return;
}
}
}
yield* this._completeParameterValues(parameterNames, lastToken);
}
else {
for (const parameterName of parameterNames) {
if (parameterName === lastToken) {
const values = await this._getParameterValueCompletionsAsync(parameterNameMap.get(parameterName));
if (values.size > 0) {
yield* values;
return;
}
}
}
for (const parameterName of parameterNames) {
if (parameterName === lastToken &&
parameterNameMap.get(parameterName).kind !== BaseClasses_1.CommandLineParameterKind.Flag) {
// The parameter is expecting a value, so don't suggest parameter names again
return;
}
}
yield* parameterNames;
}
break;
}
}
}
}
*_getAllActions() {
yield* this._actions.keys();
yield* this._globalParameters.keys();
}
tokenizeCommandLine(commandLine) {
return (0, string_argv_1.default)(commandLine);
}
async _getParameterValueCompletionsAsync(parameter) {
var _a;
let choiceParameterValues;
if (parameter.kind === BaseClasses_1.CommandLineParameterKind.Choice) {
choiceParameterValues = parameter.alternatives;
}
else if (parameter.kind !== BaseClasses_1.CommandLineParameterKind.Flag) {
let parameterWithArgumentOrChoices = undefined;
if (parameter instanceof BaseClasses_1.CommandLineParameterWithArgument ||
parameter instanceof CommandLineChoiceParameter_1.CommandLineChoiceParameter) {
parameterWithArgumentOrChoices = parameter;
}
const completionValues = await ((_a = parameterWithArgumentOrChoices === null || parameterWithArgumentOrChoices === void 0 ? void 0 : parameterWithArgumentOrChoices.completions) === null || _a === void 0 ? void 0 : _a.call(parameterWithArgumentOrChoices));
choiceParameterValues = completionValues instanceof Set ? completionValues : new Set(completionValues);
}
return choiceParameterValues !== null && choiceParameterValues !== void 0 ? choiceParameterValues : new Set();
}
_getGlobalParameterOffset(tokens) {
const globalParameters = this._globalParameters;
let count = 0;
outer: for (let i = 1; i < tokens.length; i++) {
for (const globalParameter of globalParameters.values()) {
if (tokens[i] !== globalParameter.longName && tokens[i] !== globalParameter.shortName) {
break outer;
}
}
count++;
}
return count;
}
*_completeParameterValues(choiceParameterValues, lastToken) {
for (const choiceParameterValue of choiceParameterValues) {
if (choiceParameterValue.indexOf(lastToken) === 0) {
yield choiceParameterValue;
}
}
}
}
exports.TabCompleteAction = TabCompleteAction;
//# sourceMappingURL=TabCompletionAction.js.map
@@ -0,0 +1 @@
{"version":3,"file":"TabCompletionAction.js","sourceRoot":"","sources":["../../src/providers/TabCompletionAction.ts"],"names":[],"mappings":";AAAA,4FAA4F;AAC5F,2DAA2D;;;;;;AAE3D,8DAAqC;AAIrC,2DAKmC;AACnC,yFAAsF;AACtF,2DAAwD;AACxD,4CAAoD;AAEpD,MAAM,4BAA4B,GAAW,EAAE,CAAC;AAChD,MAAM,gBAAgB,GAAW,CAAC,CAAC;AAEnC,MAAa,iBAAkB,SAAQ,qCAAiB;IAMtD,YACE,OAAyC,EACzC,gBAAyD;QAEzD,KAAK,CAAC;YACJ,UAAU,EAAE,gCAAoB,CAAC,uBAAuB;YACxD,OAAO,EAAE,0BAA0B;YACnC,aAAa,EAAE,0BAA0B;SAC1C,CAAC,CAAC;QAEH,IAAI,CAAC,QAAQ,GAAG,IAAI,GAAG,EAAE,CAAC;QAC1B,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;YAC7B,MAAM,+BAA+B,GAAsC,IAAI,GAAG,EAAE,CAAC;YACrF,KAAK,MAAM,SAAS,IAAI,MAAM,CAAC,UAAU,EAAE,CAAC;gBAC1C,+BAA+B,CAAC,GAAG,CAAC,SAAS,CAAC,QAAQ,EAAE,SAAiC,CAAC,CAAC;gBAC3F,IAAI,SAAS,CAAC,SAAS,EAAE,CAAC;oBACxB,+BAA+B,CAAC,GAAG,CAAC,SAAS,CAAC,SAAS,EAAE,SAAiC,CAAC,CAAC;gBAC9F,CAAC;YACH,CAAC;YACD,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,UAAU,EAAE,+BAA+B,CAAC,CAAC;QACxE,CAAC;QAED,IAAI,CAAC,iBAAiB,GAAG,IAAI,GAAG,EAAgC,CAAC;QACjE,KAAK,MAAM,SAAS,IAAI,gBAAgB,EAAE,CAAC;YACzC,IAAI,CAAC,iBAAi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