node_modules ignore

This commit is contained in:
2025-05-08 23:43:47 +02:00
parent e19d52f172
commit 4574544c9f
65041 changed files with 10593536 additions and 0 deletions

View File

@@ -0,0 +1,14 @@
/**
* Helpers for working with the ts-command-line API.
*
* @public
*/
export declare class CommandLineHelper {
/**
* Returns true if the current command line action is tab-complete.
*
* @public
*/
static isTabCompletionActionRequest(argv: string[]): boolean;
}
//# sourceMappingURL=CommandLineHelper.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"CommandLineHelper.d.ts","sourceRoot":"","sources":["../src/CommandLineHelper.ts"],"names":[],"mappings":"AAKA;;;;GAIG;AACH,qBAAa,iBAAiB;IAC5B;;;;OAIG;WACW,4BAA4B,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,OAAO;CAGpE"}

View File

@@ -0,0 +1,23 @@
"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.CommandLineHelper = void 0;
const Constants_1 = require("./Constants");
/**
* Helpers for working with the ts-command-line API.
*
* @public
*/
class CommandLineHelper {
/**
* Returns true if the current command line action is tab-complete.
*
* @public
*/
static isTabCompletionActionRequest(argv) {
return argv && argv.length > 2 && argv[2] === Constants_1.CommandLineConstants.TabCompletionActionName;
}
}
exports.CommandLineHelper = CommandLineHelper;
//# sourceMappingURL=CommandLineHelper.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"CommandLineHelper.js","sourceRoot":"","sources":["../src/CommandLineHelper.ts"],"names":[],"mappings":";AAAA,4FAA4F;AAC5F,2DAA2D;;;AAE3D,2CAAmD;AAEnD;;;;GAIG;AACH,MAAa,iBAAiB;IAC5B;;;;OAIG;IACI,MAAM,CAAC,4BAA4B,CAAC,IAAc;QACvD,OAAO,IAAI,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,gCAAoB,CAAC,uBAAuB,CAAC;IAC7F,CAAC;CACF;AATD,8CASC","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 { CommandLineConstants } from './Constants';\n\n/**\n * Helpers for working with the ts-command-line API.\n *\n * @public\n */\nexport class CommandLineHelper {\n /**\n * Returns true if the current command line action is tab-complete.\n *\n * @public\n */\n public static isTabCompletionActionRequest(argv: string[]): boolean {\n return argv && argv.length > 2 && argv[2] === CommandLineConstants.TabCompletionActionName;\n }\n}\n"]}

View File

@@ -0,0 +1,13 @@
/**
* String constants for command line processing.
*
* @public
*/
export declare enum CommandLineConstants {
/**
* The name of the built-in action that serves suggestions for tab-completion
*/
TabCompletionActionName = "tab-complete"
}
export declare const SCOPING_PARAMETER_GROUP: unique symbol;
//# sourceMappingURL=Constants.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"Constants.d.ts","sourceRoot":"","sources":["../src/Constants.ts"],"names":[],"mappings":"AAGA;;;;GAIG;AACH,oBAAY,oBAAoB;IAC9B;;OAEG;IACH,uBAAuB,iBAAiB;CACzC;AAED,eAAO,MAAM,uBAAuB,EAAE,OAAO,MAA0B,CAAC"}

View File

@@ -0,0 +1,19 @@
"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.SCOPING_PARAMETER_GROUP = exports.CommandLineConstants = void 0;
/**
* String constants for command line processing.
*
* @public
*/
var CommandLineConstants;
(function (CommandLineConstants) {
/**
* The name of the built-in action that serves suggestions for tab-completion
*/
CommandLineConstants["TabCompletionActionName"] = "tab-complete";
})(CommandLineConstants || (exports.CommandLineConstants = CommandLineConstants = {}));
exports.SCOPING_PARAMETER_GROUP = Symbol('scoping');
//# sourceMappingURL=Constants.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"Constants.js","sourceRoot":"","sources":["../src/Constants.ts"],"names":[],"mappings":";AAAA,4FAA4F;AAC5F,2DAA2D;;;AAE3D;;;;GAIG;AACH,IAAY,oBAKX;AALD,WAAY,oBAAoB;IAC9B;;OAEG;IACH,gEAAwC,CAAA;AAC1C,CAAC,EALW,oBAAoB,oCAApB,oBAAoB,QAK/B;AAEY,QAAA,uBAAuB,GAAkB,MAAM,CAAC,SAAS,CAAC,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\n/**\n * String constants for command line processing.\n *\n * @public\n */\nexport enum CommandLineConstants {\n /**\n * The name of the built-in action that serves suggestions for tab-completion\n */\n TabCompletionActionName = 'tab-complete'\n}\n\nexport const SCOPING_PARAMETER_GROUP: unique symbol = Symbol('scoping');\n"]}

View File

@@ -0,0 +1,9 @@
export declare const uuidAlreadyReportedError: string;
export declare class TypeUuid {
/**
* Returns true if the `targetObject` is an instance of a JavaScript class that was previously
* registered using the specified `typeUuid`. Base classes are also considered.
*/
static isInstanceOf(targetObject: unknown, typeUuid: string): boolean;
}
//# sourceMappingURL=TypeUuidLite.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"TypeUuidLite.d.ts","sourceRoot":"","sources":["../src/TypeUuidLite.ts"],"names":[],"mappings":"AAKA,eAAO,MAAM,wBAAwB,EAAE,MAA+C,CAAC;AAGvF,qBAAa,QAAQ;IACnB;;;OAGG;WACW,YAAY,CAAC,YAAY,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO;CAkB7E"}

View File

@@ -0,0 +1,32 @@
"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.TypeUuid = exports.uuidAlreadyReportedError = void 0;
const classPrototypeUuidSymbol = Symbol.for('TypeUuid.classPrototypeUuid');
exports.uuidAlreadyReportedError = 'f26b0640-a49b-49d1-9ead-1a516d5920c7';
// Avoid a dependency on node-core-library to access just this one API:
class TypeUuid {
/**
* Returns true if the `targetObject` is an instance of a JavaScript class that was previously
* registered using the specified `typeUuid`. Base classes are also considered.
*/
static isInstanceOf(targetObject, typeUuid) {
if (targetObject === undefined || targetObject === null) {
return false;
}
let objectPrototype = Object.getPrototypeOf(targetObject);
while (objectPrototype !== undefined && objectPrototype !== null) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const registeredUuid = objectPrototype[classPrototypeUuidSymbol];
if (registeredUuid === typeUuid) {
return true;
}
// Walk upwards an examine base class prototypes
objectPrototype = Object.getPrototypeOf(objectPrototype);
}
return false;
}
}
exports.TypeUuid = TypeUuid;
//# sourceMappingURL=TypeUuidLite.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"TypeUuidLite.js","sourceRoot":"","sources":["../src/TypeUuidLite.ts"],"names":[],"mappings":";AAAA,4FAA4F;AAC5F,2DAA2D;;;AAE3D,MAAM,wBAAwB,GAAW,MAAM,CAAC,GAAG,CAAC,6BAA6B,CAAC,CAAC;AAEtE,QAAA,wBAAwB,GAAW,sCAAsC,CAAC;AAEvF,uEAAuE;AACvE,MAAa,QAAQ;IACnB;;;OAGG;IACI,MAAM,CAAC,YAAY,CAAC,YAAqB,EAAE,QAAgB;QAChE,IAAI,YAAY,KAAK,SAAS,IAAI,YAAY,KAAK,IAAI,EAAE,CAAC;YACxD,OAAO,KAAK,CAAC;QACf,CAAC;QAED,IAAI,eAAe,GAAO,MAAM,CAAC,cAAc,CAAC,YAAY,CAAC,CAAC;QAC9D,OAAO,eAAe,KAAK,SAAS,IAAI,eAAe,KAAK,IAAI,EAAE,CAAC;YACjE,8DAA8D;YAC9D,MAAM,cAAc,GAAY,eAAuB,CAAC,wBAAwB,CAAC,CAAC;YAClF,IAAI,cAAc,KAAK,QAAQ,EAAE,CAAC;gBAChC,OAAO,IAAI,CAAC;YACd,CAAC;YACD,gDAAgD;YAChD,eAAe,GAAG,MAAM,CAAC,cAAc,CAAC,eAAe,CAAC,CAAC;QAC3D,CAAC;QAED,OAAO,KAAK,CAAC;IACf,CAAC;CACF;AAvBD,4BAuBC","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.\n// See LICENSE in the project root for license information.\n\nconst classPrototypeUuidSymbol: symbol = Symbol.for('TypeUuid.classPrototypeUuid');\n\nexport const uuidAlreadyReportedError: string = 'f26b0640-a49b-49d1-9ead-1a516d5920c7';\n\n// Avoid a dependency on node-core-library to access just this one API:\nexport class TypeUuid {\n /**\n * Returns true if the `targetObject` is an instance of a JavaScript class that was previously\n * registered using the specified `typeUuid`. Base classes are also considered.\n */\n public static isInstanceOf(targetObject: unknown, typeUuid: string): boolean {\n if (targetObject === undefined || targetObject === null) {\n return false;\n }\n\n let objectPrototype: {} = Object.getPrototypeOf(targetObject);\n while (objectPrototype !== undefined && objectPrototype !== null) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const registeredUuid: string = (objectPrototype as any)[classPrototypeUuidSymbol];\n if (registeredUuid === typeUuid) {\n return true;\n }\n // Walk upwards an examine base class prototypes\n objectPrototype = Object.getPrototypeOf(objectPrototype);\n }\n\n return false;\n }\n}\n"]}

View File

@@ -0,0 +1,25 @@
/**
* An object-oriented command-line parser for TypeScript projects.
*
* @packageDocumentation
*/
export { CommandLineAction, type ICommandLineActionOptions } from './providers/CommandLineAction';
export { DynamicCommandLineAction } from './providers/DynamicCommandLineAction';
export { ScopedCommandLineAction } from './providers/ScopedCommandLineAction';
export { AliasCommandLineAction, type IAliasCommandLineActionOptions } from './providers/AliasCommandLineAction';
export type { IBaseCommandLineDefinition, IBaseCommandLineDefinitionWithArgument, ICommandLineFlagDefinition, ICommandLineStringDefinition, ICommandLineStringListDefinition, ICommandLineIntegerDefinition, ICommandLineIntegerListDefinition, ICommandLineChoiceDefinition, ICommandLineChoiceListDefinition, ICommandLineRemainderDefinition } from './parameters/CommandLineDefinition';
export { CommandLineParameterKind, CommandLineParameterBase as CommandLineParameter, CommandLineParameterWithArgument } from './parameters/BaseClasses';
export { CommandLineFlagParameter } from './parameters/CommandLineFlagParameter';
export { CommandLineStringParameter, type IRequiredCommandLineStringParameter } from './parameters/CommandLineStringParameter';
export { CommandLineStringListParameter } from './parameters/CommandLineStringListParameter';
export { CommandLineIntegerParameter, type IRequiredCommandLineIntegerParameter } from './parameters/CommandLineIntegerParameter';
export { CommandLineIntegerListParameter } from './parameters/CommandLineIntegerListParameter';
export { CommandLineChoiceParameter, type IRequiredCommandLineChoiceParameter } from './parameters/CommandLineChoiceParameter';
export { CommandLineChoiceListParameter } from './parameters/CommandLineChoiceListParameter';
export { CommandLineRemainder } from './parameters/CommandLineRemainder';
export { CommandLineParameterProvider, type IScopedLongNameParseResult, type ICommandLineParserData as _ICommandLineParserData, type IRegisterDefinedParametersState as _IRegisterDefinedParametersState } from './providers/CommandLineParameterProvider';
export { CommandLineParser, type ICommandLineParserOptions } from './providers/CommandLineParser';
export { DynamicCommandLineParser } from './providers/DynamicCommandLineParser';
export { CommandLineConstants } from './Constants';
export { CommandLineHelper } from './CommandLineHelper';
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA;;;;GAIG;AAEH,OAAO,EAAE,iBAAiB,EAAE,KAAK,yBAAyB,EAAE,MAAM,+BAA+B,CAAC;AAClG,OAAO,EAAE,wBAAwB,EAAE,MAAM,sCAAsC,CAAC;AAChF,OAAO,EAAE,uBAAuB,EAAE,MAAM,qCAAqC,CAAC;AAC9E,OAAO,EACL,sBAAsB,EACtB,KAAK,8BAA8B,EACpC,MAAM,oCAAoC,CAAC;AAE5C,YAAY,EACV,0BAA0B,EAC1B,sCAAsC,EACtC,0BAA0B,EAC1B,4BAA4B,EAC5B,gCAAgC,EAChC,6BAA6B,EAC7B,iCAAiC,EACjC,4BAA4B,EAC5B,gCAAgC,EAChC,+BAA+B,EAChC,MAAM,oCAAoC,CAAC;AAE5C,OAAO,EACL,wBAAwB,EAExB,wBAAwB,IAAI,oBAAoB,EAChD,gCAAgC,EACjC,MAAM,0BAA0B,CAAC;AAElC,OAAO,EAAE,wBAAwB,EAAE,MAAM,uCAAuC,CAAC;AACjF,OAAO,EACL,0BAA0B,EAC1B,KAAK,mCAAmC,EACzC,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAAE,8BAA8B,EAAE,MAAM,6CAA6C,CAAC;AAC7F,OAAO,EACL,2BAA2B,EAC3B,KAAK,oCAAoC,EAC1C,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAAE,+BAA+B,EAAE,MAAM,8CAA8C,CAAC;AAC/F,OAAO,EACL,0BAA0B,EAC1B,KAAK,mCAAmC,EACzC,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAAE,8BAA8B,EAAE,MAAM,6CAA6C,CAAC;AAC7F,OAAO,EAAE,oBAAoB,EAAE,MAAM,mCAAmC,CAAC;AAEzE,OAAO,EACL,4BAA4B,EAC5B,KAAK,0BAA0B,EAC/B,KAAK,sBAAsB,IAAI,uBAAuB,EACtD,KAAK,+BAA+B,IAAI,gCAAgC,EACzE,MAAM,0CAA0C,CAAC;AAElD,OAAO,EAAE,iBAAiB,EAAE,KAAK,yBAAyB,EAAE,MAAM,+BAA+B,CAAC;AAClG,OAAO,EAAE,wBAAwB,EAAE,MAAM,sCAAsC,CAAC;AAEhF,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAEnD,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC"}

View File

@@ -0,0 +1,50 @@
"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.CommandLineHelper = exports.CommandLineConstants = exports.DynamicCommandLineParser = exports.CommandLineParser = exports.CommandLineParameterProvider = exports.CommandLineRemainder = exports.CommandLineChoiceListParameter = exports.CommandLineChoiceParameter = exports.CommandLineIntegerListParameter = exports.CommandLineIntegerParameter = exports.CommandLineStringListParameter = exports.CommandLineStringParameter = exports.CommandLineFlagParameter = exports.CommandLineParameterWithArgument = exports.CommandLineParameter = exports.CommandLineParameterKind = exports.AliasCommandLineAction = exports.ScopedCommandLineAction = exports.DynamicCommandLineAction = exports.CommandLineAction = void 0;
/**
* An object-oriented command-line parser for TypeScript projects.
*
* @packageDocumentation
*/
var CommandLineAction_1 = require("./providers/CommandLineAction");
Object.defineProperty(exports, "CommandLineAction", { enumerable: true, get: function () { return CommandLineAction_1.CommandLineAction; } });
var DynamicCommandLineAction_1 = require("./providers/DynamicCommandLineAction");
Object.defineProperty(exports, "DynamicCommandLineAction", { enumerable: true, get: function () { return DynamicCommandLineAction_1.DynamicCommandLineAction; } });
var ScopedCommandLineAction_1 = require("./providers/ScopedCommandLineAction");
Object.defineProperty(exports, "ScopedCommandLineAction", { enumerable: true, get: function () { return ScopedCommandLineAction_1.ScopedCommandLineAction; } });
var AliasCommandLineAction_1 = require("./providers/AliasCommandLineAction");
Object.defineProperty(exports, "AliasCommandLineAction", { enumerable: true, get: function () { return AliasCommandLineAction_1.AliasCommandLineAction; } });
var BaseClasses_1 = require("./parameters/BaseClasses");
Object.defineProperty(exports, "CommandLineParameterKind", { enumerable: true, get: function () { return BaseClasses_1.CommandLineParameterKind; } });
// TODO: Export both `CommandLineParameter` and `CommandLineParameterBase` in the next major bump
Object.defineProperty(exports, "CommandLineParameter", { enumerable: true, get: function () { return BaseClasses_1.CommandLineParameterBase; } });
Object.defineProperty(exports, "CommandLineParameterWithArgument", { enumerable: true, get: function () { return BaseClasses_1.CommandLineParameterWithArgument; } });
var CommandLineFlagParameter_1 = require("./parameters/CommandLineFlagParameter");
Object.defineProperty(exports, "CommandLineFlagParameter", { enumerable: true, get: function () { return CommandLineFlagParameter_1.CommandLineFlagParameter; } });
var CommandLineStringParameter_1 = require("./parameters/CommandLineStringParameter");
Object.defineProperty(exports, "CommandLineStringParameter", { enumerable: true, get: function () { return CommandLineStringParameter_1.CommandLineStringParameter; } });
var CommandLineStringListParameter_1 = require("./parameters/CommandLineStringListParameter");
Object.defineProperty(exports, "CommandLineStringListParameter", { enumerable: true, get: function () { return CommandLineStringListParameter_1.CommandLineStringListParameter; } });
var CommandLineIntegerParameter_1 = require("./parameters/CommandLineIntegerParameter");
Object.defineProperty(exports, "CommandLineIntegerParameter", { enumerable: true, get: function () { return CommandLineIntegerParameter_1.CommandLineIntegerParameter; } });
var CommandLineIntegerListParameter_1 = require("./parameters/CommandLineIntegerListParameter");
Object.defineProperty(exports, "CommandLineIntegerListParameter", { enumerable: true, get: function () { return CommandLineIntegerListParameter_1.CommandLineIntegerListParameter; } });
var CommandLineChoiceParameter_1 = require("./parameters/CommandLineChoiceParameter");
Object.defineProperty(exports, "CommandLineChoiceParameter", { enumerable: true, get: function () { return CommandLineChoiceParameter_1.CommandLineChoiceParameter; } });
var CommandLineChoiceListParameter_1 = require("./parameters/CommandLineChoiceListParameter");
Object.defineProperty(exports, "CommandLineChoiceListParameter", { enumerable: true, get: function () { return CommandLineChoiceListParameter_1.CommandLineChoiceListParameter; } });
var CommandLineRemainder_1 = require("./parameters/CommandLineRemainder");
Object.defineProperty(exports, "CommandLineRemainder", { enumerable: true, get: function () { return CommandLineRemainder_1.CommandLineRemainder; } });
var CommandLineParameterProvider_1 = require("./providers/CommandLineParameterProvider");
Object.defineProperty(exports, "CommandLineParameterProvider", { enumerable: true, get: function () { return CommandLineParameterProvider_1.CommandLineParameterProvider; } });
var CommandLineParser_1 = require("./providers/CommandLineParser");
Object.defineProperty(exports, "CommandLineParser", { enumerable: true, get: function () { return CommandLineParser_1.CommandLineParser; } });
var DynamicCommandLineParser_1 = require("./providers/DynamicCommandLineParser");
Object.defineProperty(exports, "DynamicCommandLineParser", { enumerable: true, get: function () { return DynamicCommandLineParser_1.DynamicCommandLineParser; } });
var Constants_1 = require("./Constants");
Object.defineProperty(exports, "CommandLineConstants", { enumerable: true, get: function () { return Constants_1.CommandLineConstants; } });
var CommandLineHelper_1 = require("./CommandLineHelper");
Object.defineProperty(exports, "CommandLineHelper", { enumerable: true, get: function () { return CommandLineHelper_1.CommandLineHelper; } });
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA,4FAA4F;AAC5F,2DAA2D;;;AAE3D;;;;GAIG;AAEH,mEAAkG;AAAzF,sHAAA,iBAAiB,OAAA;AAC1B,iFAAgF;AAAvE,oIAAA,wBAAwB,OAAA;AACjC,+EAA8E;AAArE,kIAAA,uBAAuB,OAAA;AAChC,6EAG4C;AAF1C,gIAAA,sBAAsB,OAAA;AAiBxB,wDAKkC;AAJhC,uHAAA,wBAAwB,OAAA;AACxB,iGAAiG;AACjG,mHAAA,wBAAwB,OAAwB;AAChD,+HAAA,gCAAgC,OAAA;AAGlC,kFAAiF;AAAxE,oIAAA,wBAAwB,OAAA;AACjC,sFAGiD;AAF/C,wIAAA,0BAA0B,OAAA;AAG5B,8FAA6F;AAApF,gJAAA,8BAA8B,OAAA;AACvC,wFAGkD;AAFhD,0IAAA,2BAA2B,OAAA;AAG7B,gGAA+F;AAAtF,kJAAA,+BAA+B,OAAA;AACxC,sFAGiD;AAF/C,wIAAA,0BAA0B,OAAA;AAG5B,8FAA6F;AAApF,gJAAA,8BAA8B,OAAA;AACvC,0EAAyE;AAAhE,4HAAA,oBAAoB,OAAA;AAE7B,yFAKkD;AAJhD,4IAAA,4BAA4B,OAAA;AAM9B,mEAAkG;AAAzF,sHAAA,iBAAiB,OAAA;AAC1B,iFAAgF;AAAvE,oIAAA,wBAAwB,OAAA;AAEjC,yCAAmD;AAA1C,iHAAA,oBAAoB,OAAA;AAE7B,yDAAwD;AAA/C,sHAAA,iBAAiB,OAAA","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.\n// See LICENSE in the project root for license information.\n\n/**\n * An object-oriented command-line parser for TypeScript projects.\n *\n * @packageDocumentation\n */\n\nexport { CommandLineAction, type ICommandLineActionOptions } from './providers/CommandLineAction';\nexport { DynamicCommandLineAction } from './providers/DynamicCommandLineAction';\nexport { ScopedCommandLineAction } from './providers/ScopedCommandLineAction';\nexport {\n AliasCommandLineAction,\n type IAliasCommandLineActionOptions\n} from './providers/AliasCommandLineAction';\n\nexport type {\n IBaseCommandLineDefinition,\n IBaseCommandLineDefinitionWithArgument,\n ICommandLineFlagDefinition,\n ICommandLineStringDefinition,\n ICommandLineStringListDefinition,\n ICommandLineIntegerDefinition,\n ICommandLineIntegerListDefinition,\n ICommandLineChoiceDefinition,\n ICommandLineChoiceListDefinition,\n ICommandLineRemainderDefinition\n} from './parameters/CommandLineDefinition';\n\nexport {\n CommandLineParameterKind,\n // TODO: Export both `CommandLineParameter` and `CommandLineParameterBase` in the next major bump\n CommandLineParameterBase as CommandLineParameter,\n CommandLineParameterWithArgument\n} from './parameters/BaseClasses';\n\nexport { CommandLineFlagParameter } from './parameters/CommandLineFlagParameter';\nexport {\n CommandLineStringParameter,\n type IRequiredCommandLineStringParameter\n} from './parameters/CommandLineStringParameter';\nexport { CommandLineStringListParameter } from './parameters/CommandLineStringListParameter';\nexport {\n CommandLineIntegerParameter,\n type IRequiredCommandLineIntegerParameter\n} from './parameters/CommandLineIntegerParameter';\nexport { CommandLineIntegerListParameter } from './parameters/CommandLineIntegerListParameter';\nexport {\n CommandLineChoiceParameter,\n type IRequiredCommandLineChoiceParameter\n} from './parameters/CommandLineChoiceParameter';\nexport { CommandLineChoiceListParameter } from './parameters/CommandLineChoiceListParameter';\nexport { CommandLineRemainder } from './parameters/CommandLineRemainder';\n\nexport {\n CommandLineParameterProvider,\n type IScopedLongNameParseResult,\n type ICommandLineParserData as _ICommandLineParserData,\n type IRegisterDefinedParametersState as _IRegisterDefinedParametersState\n} from './providers/CommandLineParameterProvider';\n\nexport { CommandLineParser, type ICommandLineParserOptions } from './providers/CommandLineParser';\nexport { DynamicCommandLineParser } from './providers/DynamicCommandLineParser';\n\nexport { CommandLineConstants } from './Constants';\n\nexport { CommandLineHelper } from './CommandLineHelper';\n"]}

View File

@@ -0,0 +1,130 @@
import type { SCOPING_PARAMETER_GROUP } from '../Constants';
import type { IBaseCommandLineDefinition, IBaseCommandLineDefinitionWithArgument } from './CommandLineDefinition';
import type { CommandLineChoiceListParameter } from './CommandLineChoiceListParameter';
import type { CommandLineChoiceParameter } from './CommandLineChoiceParameter';
import type { CommandLineFlagParameter } from './CommandLineFlagParameter';
import type { CommandLineIntegerListParameter } from './CommandLineIntegerListParameter';
import type { CommandLineIntegerParameter } from './CommandLineIntegerParameter';
import type { CommandLineStringListParameter } from './CommandLineStringListParameter';
import type { CommandLineStringParameter } from './CommandLineStringParameter';
/**
* Identifies the kind of a CommandLineParameter.
* @public
*/
export declare enum CommandLineParameterKind {
/** Indicates a CommandLineChoiceParameter */
Choice = 0,
/** Indicates a CommandLineFlagParameter */
Flag = 1,
/** Indicates a CommandLineIntegerParameter */
Integer = 2,
/** Indicates a CommandLineStringParameter */
String = 3,
/** Indicates a CommandLineStringListParameter */
StringList = 4,
/** Indicates a CommandLineChoiceListParameter */
ChoiceList = 5,
/** Indicates a CommandLineIntegerListParameter */
IntegerList = 6
}
export type CommandLineParameter = CommandLineChoiceListParameter | CommandLineChoiceParameter | CommandLineFlagParameter | CommandLineIntegerListParameter | CommandLineIntegerParameter | CommandLineStringListParameter | CommandLineStringParameter;
/**
* The base class for the various command-line parameter types.
* @public
*/
export declare abstract class CommandLineParameterBase {
private _shortNameValue;
/**
* A unique internal key used to retrieve the value from the parser's dictionary.
* @internal
*/
_parserKey: string | undefined;
/**
* @internal
*/
_preParse?: () => void;
/**
* @internal
*/
_postParse?: () => void;
/**
* @internal
*/
_validateValue?: () => void;
/** {@inheritDoc IBaseCommandLineDefinition.parameterLongName} */
readonly longName: string;
/**
* If a parameterScope is provided, returns the scope-prefixed long name of the flag,
* including double dashes, eg. "--scope:do-something". Otherwise undefined.
*/
readonly scopedLongName: string | undefined;
/** {@inheritDoc IBaseCommandLineDefinition.parameterGroup} */
readonly parameterGroup: string | typeof SCOPING_PARAMETER_GROUP | undefined;
/** {@inheritDoc IBaseCommandLineDefinition.parameterScope} */
readonly parameterScope: string | undefined;
/** {@inheritDoc IBaseCommandLineDefinition.description} */
readonly description: string;
/** {@inheritDoc IBaseCommandLineDefinition.required} */
readonly required: boolean;
/** {@inheritDoc IBaseCommandLineDefinition.environmentVariable} */
readonly environmentVariable: string | undefined;
/** {@inheritDoc IBaseCommandLineDefinition.allowNonStandardEnvironmentVariableNames} */
readonly allowNonStandardEnvironmentVariableNames: boolean | undefined;
/** {@inheritDoc IBaseCommandLineDefinition.undocumentedSynonyms } */
readonly undocumentedSynonyms: string[] | undefined;
/** @internal */
constructor(definition: IBaseCommandLineDefinition);
/** {@inheritDoc IBaseCommandLineDefinition.parameterShortName} */
get shortName(): string | undefined;
/**
* Called internally by CommandLineParameterProvider._processParsedData()
* @internal
*/
abstract _setValue(data: unknown): void;
/**
* Returns additional text used by the help formatter.
* @internal
*/
_getSupplementaryNotes(supplementaryNotes: string[]): void;
/**
* Indicates the type of parameter.
*/
abstract get kind(): CommandLineParameterKind;
/**
* Append the parsed values to the provided string array.
* @remarks
* Sometimes a command line parameter is not used directly, but instead gets passed through to another
* tool that will use it. For example if our parameter comes in as "--max-count 3", then we might want to
* call `child_process.spawn()` and append ["--max-count", "3"] to the args array for that tool.
* appendToArgList() appends zero or more strings to the provided array, based on the input command-line
* that we parsed.
*
* If the parameter was omitted from our command-line and has no default value, then
* nothing will be appended. If the short name was used, the long name will be appended instead.
* @param argList - the parsed strings will be appended to this string array
*/
abstract appendToArgList(argList: string[]): void;
/**
* Internal usage only. Used to report unexpected output from the argparse library.
*/
protected reportInvalidData(data: unknown): never;
protected validateDefaultValue(hasDefaultValue: boolean): void;
}
/**
* The common base class for parameters types that receive an argument.
*
* @remarks
* An argument is an accompanying command-line token, such as "123" in the
* example "--max-count 123".
* @public
*/
export declare abstract class CommandLineParameterWithArgument extends CommandLineParameterBase {
private static _invalidArgumentNameRegExp;
/** {@inheritDoc IBaseCommandLineDefinitionWithArgument.argumentName} */
readonly argumentName: string;
/** {@inheritDoc IBaseCommandLineDefinitionWithArgument.completions} */
readonly completions: (() => Promise<ReadonlyArray<string> | ReadonlySet<string>>) | undefined;
/** @internal */
constructor(definition: IBaseCommandLineDefinitionWithArgument);
}
//# sourceMappingURL=BaseClasses.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"BaseClasses.d.ts","sourceRoot":"","sources":["../../src/parameters/BaseClasses.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,cAAc,CAAC;AAC5D,OAAO,KAAK,EACV,0BAA0B,EAC1B,sCAAsC,EACvC,MAAM,yBAAyB,CAAC;AACjC,OAAO,KAAK,EAAE,8BAA8B,EAAE,MAAM,kCAAkC,CAAC;AACvF,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,8BAA8B,CAAC;AAC/E,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,4BAA4B,CAAC;AAC3E,OAAO,KAAK,EAAE,+BAA+B,EAAE,MAAM,mCAAmC,CAAC;AACzF,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,+BAA+B,CAAC;AACjF,OAAO,KAAK,EAAE,8BAA8B,EAAE,MAAM,kCAAkC,CAAC;AACvF,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,8BAA8B,CAAC;AAE/E;;;GAGG;AACH,oBAAY,wBAAwB;IAClC,6CAA6C;IAC7C,MAAM,IAAA;IACN,2CAA2C;IAC3C,IAAI,IAAA;IACJ,8CAA8C;IAC9C,OAAO,IAAA;IACP,6CAA6C;IAC7C,MAAM,IAAA;IACN,iDAAiD;IACjD,UAAU,IAAA;IACV,iDAAiD;IACjD,UAAU,IAAA;IACV,kDAAkD;IAClD,WAAW,IAAA;CACZ;AA4BD,MAAM,MAAM,oBAAoB,GAC5B,8BAA8B,GAC9B,0BAA0B,GAC1B,wBAAwB,GACxB,+BAA+B,GAC/B,2BAA2B,GAC3B,8BAA8B,GAC9B,0BAA0B,CAAC;AAE/B;;;GAGG;AACH,8BAAsB,wBAAwB;IAC5C,OAAO,CAAC,eAAe,CAAqB;IAE5C;;;OAGG;IACI,UAAU,EAAE,MAAM,GAAG,SAAS,CAAC;IAEtC;;OAEG;IACI,SAAS,CAAC,EAAE,MAAM,IAAI,CAAC;IAE9B;;OAEG;IACI,UAAU,CAAC,EAAE,MAAM,IAAI,CAAC;IAE/B;;OAEG;IACI,cAAc,CAAC,EAAE,MAAM,IAAI,CAAC;IAEnC,iEAAiE;IACjE,SAAgB,QAAQ,EAAE,MAAM,CAAC;IAEjC;;;OAGG;IACH,SAAgB,cAAc,EAAE,MAAM,GAAG,SAAS,CAAC;IAEnD,8DAA8D;IAC9D,SAAgB,cAAc,EAAE,MAAM,GAAG,OAAO,uBAAuB,GAAG,SAAS,CAAC;IAEpF,8DAA8D;IAC9D,SAAgB,cAAc,EAAE,MAAM,GAAG,SAAS,CAAC;IAEnD,2DAA2D;IAC3D,SAAgB,WAAW,EAAE,MAAM,CAAC;IAEpC,wDAAwD;IACxD,SAAgB,QAAQ,EAAE,OAAO,CAAC;IAElC,mEAAmE;IACnE,SAAgB,mBAAmB,EAAE,MAAM,GAAG,SAAS,CAAC;IAExD,wFAAwF;IACxF,SAAgB,wCAAwC,EAAE,OAAO,GAAG,SAAS,CAAC;IAE9E,qEAAqE;IACrE,SAAgB,oBAAoB,EAAE,MAAM,EAAE,GAAG,SAAS,CAAC;IAE3D,gBAAgB;gBACG,UAAU,EAAE,0BAA0B;IAoEzD,kEAAkE;IAClE,IAAW,SAAS,IAAI,MAAM,GAAG,SAAS,CAEzC;IAED;;;OAGG;aACa,SAAS,CAAC,IAAI,EAAE,OAAO,GAAG,IAAI;IAE9C;;;OAGG;IACI,sBAAsB,CAAC,kBAAkB,EAAE,MAAM,EAAE,GAAG,IAAI;IAWjE;;OAEG;IACH,aAAoB,IAAI,IAAI,wBAAwB,CAAC;IAErD;;;;;;;;;;;;OAYG;aACa,eAAe,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI;IAExD;;OAEG;IACH,SAAS,CAAC,iBAAiB,CAAC,IAAI,EAAE,OAAO,GAAG,KAAK;IAIjD,SAAS,CAAC,oBAAoB,CAAC,eAAe,EAAE,OAAO,GAAG,IAAI;CAY/D;AAED;;;;;;;GAOG;AACH,8BAAsB,gCAAiC,SAAQ,wBAAwB;IAErF,OAAO,CAAC,MAAM,CAAC,0BAA0B,CAAwB;IAEjE,wEAAwE;IACxE,SAAgB,YAAY,EAAE,MAAM,CAAC;IAErC,uEAAuE;IACvE,SAAgB,WAAW,EAAE,CAAC,MAAM,OAAO,CAAC,aAAa,CAAC,MAAM,CAAC,GAAG,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,SAAS,CAAC;IAEtG,gBAAgB;gBACG,UAAU,EAAE,sCAAsC;CAyBtE"}

View File

@@ -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.
Object.defineProperty(exports, "__esModule", { value: true });
exports.CommandLineParameterWithArgument = exports.CommandLineParameterBase = exports.CommandLineParameterKind = void 0;
/**
* Identifies the kind of a CommandLineParameter.
* @public
*/
var CommandLineParameterKind;
(function (CommandLineParameterKind) {
/** Indicates a CommandLineChoiceParameter */
CommandLineParameterKind[CommandLineParameterKind["Choice"] = 0] = "Choice";
/** Indicates a CommandLineFlagParameter */
CommandLineParameterKind[CommandLineParameterKind["Flag"] = 1] = "Flag";
/** Indicates a CommandLineIntegerParameter */
CommandLineParameterKind[CommandLineParameterKind["Integer"] = 2] = "Integer";
/** Indicates a CommandLineStringParameter */
CommandLineParameterKind[CommandLineParameterKind["String"] = 3] = "String";
/** Indicates a CommandLineStringListParameter */
CommandLineParameterKind[CommandLineParameterKind["StringList"] = 4] = "StringList";
/** Indicates a CommandLineChoiceListParameter */
CommandLineParameterKind[CommandLineParameterKind["ChoiceList"] = 5] = "ChoiceList";
/** Indicates a CommandLineIntegerListParameter */
CommandLineParameterKind[CommandLineParameterKind["IntegerList"] = 6] = "IntegerList";
})(CommandLineParameterKind || (exports.CommandLineParameterKind = CommandLineParameterKind = {}));
/**
* Matches kebab-case formatted strings prefixed with double dashes.
* Example: "--do-something"
*/
const LONG_NAME_REGEXP = /^-(-[a-z0-9]+)+$/;
/**
* Matches a single upper-case or lower-case letter prefixed with a dash.
* Example: "-d"
*/
const SHORT_NAME_REGEXP = /^-[a-zA-Z]$/;
/**
* Matches kebab-case formatted strings
* Example: "my-scope"
*/
const SCOPE_REGEXP = /^[a-z0-9]+(-[a-z0-9]+)*$/;
/**
* "Environment variable names used by the utilities in the Shell and Utilities volume of
* IEEE Std 1003.1-2001 consist solely of uppercase letters, digits, and the '_' (underscore)
* from the characters defined in Portable Character Set and do not begin with a digit."
* Example: "THE_SETTING"
*/
const ENVIRONMENT_VARIABLE_NAME_REGEXP = /^[A-Z_][A-Z0-9_]*$/;
/**
* The base class for the various command-line parameter types.
* @public
*/
class CommandLineParameterBase {
/** @internal */
constructor(definition) {
this.longName = definition.parameterLongName;
this._shortNameValue = definition.parameterShortName;
this.parameterGroup = definition.parameterGroup;
this.parameterScope = definition.parameterScope;
this.description = definition.description;
this.required = !!definition.required;
this.environmentVariable = definition.environmentVariable;
this.undocumentedSynonyms = definition.undocumentedSynonyms;
this.allowNonStandardEnvironmentVariableNames = definition.allowNonStandardEnvironmentVariableNames;
if (!LONG_NAME_REGEXP.test(this.longName)) {
throw new Error(`Invalid name: "${this.longName}". The parameter long name must be` +
` lower-case and use dash delimiters (e.g. "--do-a-thing")`);
}
if (this.shortName) {
if (!SHORT_NAME_REGEXP.test(this.shortName)) {
throw new Error(`Invalid name: "${this.shortName}". The parameter short name must be` +
` a dash followed by a single upper-case or lower-case letter (e.g. "-a")`);
}
}
if (this.parameterScope) {
if (!SCOPE_REGEXP.test(this.parameterScope)) {
throw new Error(`Invalid scope: "${this.parameterScope}". The parameter scope name must be` +
` lower-case and use dash delimiters (e.g. "my-scope")`);
}
// Parameter long name is guaranteed to start with '--' since this is validated above
const unprefixedLongName = this.longName.slice(2);
this.scopedLongName = `--${this.parameterScope}:${unprefixedLongName}`;
}
if (this.environmentVariable) {
if (!this.allowNonStandardEnvironmentVariableNames &&
!ENVIRONMENT_VARIABLE_NAME_REGEXP.test(this.environmentVariable)) {
throw new Error(`Invalid environment variable name: "${this.environmentVariable}". The name must` +
` consist only of upper-case letters, numbers, and underscores. It may not start with a number.`);
}
}
if (this.undocumentedSynonyms && this.undocumentedSynonyms.length > 0) {
for (const undocumentedSynonym of this.undocumentedSynonyms) {
if (this.longName === undocumentedSynonym) {
throw new Error(`Invalid name: "${undocumentedSynonym}". Undocumented synonyms must not be the same` +
` as the the long name.`);
}
else if (!LONG_NAME_REGEXP.test(undocumentedSynonym)) {
throw new Error(`Invalid name: "${undocumentedSynonym}". All undocumented synonyms name must be lower-case and ` +
'use dash delimiters (e.g. "--do-a-thing")');
}
}
}
}
/** {@inheritDoc IBaseCommandLineDefinition.parameterShortName} */
get shortName() {
return this._shortNameValue;
}
/**
* Returns additional text used by the help formatter.
* @internal
*/
_getSupplementaryNotes(supplementaryNotes) {
// virtual
if (this.environmentVariable !== undefined) {
supplementaryNotes.push('This parameter may alternatively be specified via the ' +
this.environmentVariable +
' environment variable.');
}
}
/**
* Internal usage only. Used to report unexpected output from the argparse library.
*/
reportInvalidData(data) {
throw new Error(`Unexpected data object for parameter "${this.longName}": ` + JSON.stringify(data));
}
validateDefaultValue(hasDefaultValue) {
if (this.required && hasDefaultValue) {
// If a parameter is "required", then the user understands that they always need to
// specify a value for this parameter (either via the command line or via an environment variable).
// It would be confusing to allow a default value that sometimes allows the "required" parameter
// to be omitted. If you sometimes don't have a suitable default value, then the better approach
// is to throw a custom error explaining why the parameter is required in that case.
throw new Error(`A default value cannot be specified for "${this.longName}" because it is a "required" parameter`);
}
}
}
exports.CommandLineParameterBase = CommandLineParameterBase;
/**
* The common base class for parameters types that receive an argument.
*
* @remarks
* An argument is an accompanying command-line token, such as "123" in the
* example "--max-count 123".
* @public
*/
class CommandLineParameterWithArgument extends CommandLineParameterBase {
/** @internal */
constructor(definition) {
super(definition);
if (definition.argumentName === '') {
throw new Error('The argument name cannot be an empty string. (For the default name, specify undefined.)');
}
if (definition.argumentName.toUpperCase() !== definition.argumentName) {
throw new Error(`Invalid name: "${definition.argumentName}". The argument name must be all upper case.`);
}
const match = definition.argumentName.match(CommandLineParameterWithArgument._invalidArgumentNameRegExp);
if (match) {
throw new Error(`The argument name "${definition.argumentName}" contains an invalid character "${match[0]}".` +
` Only upper-case letters, numbers, and underscores are allowed.`);
}
this.argumentName = definition.argumentName;
this.completions = definition.completions;
}
}
exports.CommandLineParameterWithArgument = CommandLineParameterWithArgument;
// Matches the first character that *isn't* part of a valid upper-case argument name such as "URL_2"
CommandLineParameterWithArgument._invalidArgumentNameRegExp = /[^A-Z_0-9]/;
//# sourceMappingURL=BaseClasses.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,33 @@
import type { ICommandLineChoiceListDefinition } from './CommandLineDefinition';
import { CommandLineParameterBase, CommandLineParameterKind } from './BaseClasses';
/**
* The data type returned by {@link CommandLineParameterProvider.defineChoiceListParameter}.
* @public
*/
export declare class CommandLineChoiceListParameter<TChoice extends string = string> extends CommandLineParameterBase {
/** {@inheritDoc ICommandLineChoiceListDefinition.alternatives} */
readonly alternatives: ReadonlySet<TChoice>;
private _values;
/** {@inheritDoc ICommandLineChoiceListDefinition.completions} */
readonly completions: (() => Promise<ReadonlyArray<TChoice> | ReadonlySet<TChoice>>) | undefined;
/** {@inheritDoc CommandLineParameter.kind} */
readonly kind: CommandLineParameterKind.ChoiceList;
/** @internal */
constructor(definition: ICommandLineChoiceListDefinition<TChoice>);
/**
* {@inheritDoc CommandLineParameter._setValue}
* @internal
*/
_setValue(data: unknown): void;
/**
* Returns the string arguments for a choice list parameter that was parsed from the command line.
*
* @remarks
* The array will be empty if the command-line has not been parsed yet,
* or if the parameter was omitted and has no default value.
*/
get values(): ReadonlyArray<TChoice>;
/** {@inheritDoc CommandLineParameter.appendToArgList} @override */
appendToArgList(argList: string[]): void;
}
//# sourceMappingURL=CommandLineChoiceListParameter.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"CommandLineChoiceListParameter.d.ts","sourceRoot":"","sources":["../../src/parameters/CommandLineChoiceListParameter.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,gCAAgC,EAAE,MAAM,yBAAyB,CAAC;AAChF,OAAO,EAAE,wBAAwB,EAAE,wBAAwB,EAAE,MAAM,eAAe,CAAC;AAGnF;;;GAGG;AACH,qBAAa,8BAA8B,CACzC,OAAO,SAAS,MAAM,GAAG,MAAM,CAC/B,SAAQ,wBAAwB;IAChC,kEAAkE;IAClE,SAAgB,YAAY,EAAE,WAAW,CAAC,OAAO,CAAC,CAAC;IAEnD,OAAO,CAAC,OAAO,CAAiB;IAEhC,iEAAiE;IACjE,SAAgB,WAAW,EAAE,CAAC,MAAM,OAAO,CAAC,aAAa,CAAC,OAAO,CAAC,GAAG,WAAW,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,SAAS,CAAC;IAExG,8CAA8C;IAC9C,SAAgB,IAAI,EAAE,wBAAwB,CAAC,UAAU,CAAuC;IAEhG,gBAAgB;gBACG,UAAU,EAAE,gCAAgC,CAAC,OAAO,CAAC;IAexE;;;OAGG;IACI,SAAS,CAAC,IAAI,EAAE,OAAO,GAAG,IAAI;IAsCrC;;;;;;OAMG;IACH,IAAW,MAAM,IAAI,aAAa,CAAC,OAAO,CAAC,CAE1C;IAED,mEAAmE;IAC5D,eAAe,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI;CAQhD"}

View File

@@ -0,0 +1,83 @@
"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.CommandLineChoiceListParameter = void 0;
const BaseClasses_1 = require("./BaseClasses");
const EnvironmentVariableParser_1 = require("./EnvironmentVariableParser");
/**
* The data type returned by {@link CommandLineParameterProvider.defineChoiceListParameter}.
* @public
*/
class CommandLineChoiceListParameter extends BaseClasses_1.CommandLineParameterBase {
/** @internal */
constructor(definition) {
super(definition);
this._values = [];
/** {@inheritDoc CommandLineParameter.kind} */
this.kind = BaseClasses_1.CommandLineParameterKind.ChoiceList;
const { alternatives, completions } = definition;
const alternativesSet = alternatives instanceof Set ? alternatives : new Set(alternatives);
if (alternativesSet.size < 1) {
throw new Error(`When defining a choice list parameter, the alternatives list must contain at least one value.`);
}
this.alternatives = alternativesSet;
this.completions = completions;
}
/**
* {@inheritDoc CommandLineParameter._setValue}
* @internal
*/
_setValue(data) {
// If argparse passed us a value, confirm it is valid
if (data !== null && data !== undefined) {
if (!Array.isArray(data)) {
this.reportInvalidData(data);
}
for (const arrayItem of data) {
if (typeof arrayItem !== 'string') {
this.reportInvalidData(data);
}
}
this._values = data;
return;
}
if (this.environmentVariable !== undefined) {
const values = EnvironmentVariableParser_1.EnvironmentVariableParser.parseAsList(this.environmentVariable);
if (values) {
for (const value of values) {
if (!this.alternatives.has(value)) {
const choices = '"' + Array.from(this.alternatives).join('", "') + '"';
throw new Error(`Invalid value "${value}" for the environment variable` +
` ${this.environmentVariable}. Valid choices are: ${choices}`);
}
}
this._values = values;
return;
}
}
// (No default value for choice lists)
this._values = [];
}
/**
* Returns the string arguments for a choice list parameter that was parsed from the command line.
*
* @remarks
* The array will be empty if the command-line has not been parsed yet,
* or if the parameter was omitted and has no default value.
*/
get values() {
return this._values;
}
/** {@inheritDoc CommandLineParameter.appendToArgList} @override */
appendToArgList(argList) {
if (this.values.length > 0) {
for (const value of this.values) {
argList.push(this.longName);
argList.push(value);
}
}
}
}
exports.CommandLineChoiceListParameter = CommandLineChoiceListParameter;
//# sourceMappingURL=CommandLineChoiceListParameter.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,47 @@
import type { ICommandLineChoiceDefinition } from './CommandLineDefinition';
import { CommandLineParameterBase, CommandLineParameterKind } from './BaseClasses';
/**
* The data type returned by {@link CommandLineParameterProvider.(defineChoiceParameter:2)}.
* @public
*/
export interface IRequiredCommandLineChoiceParameter<TChoice extends string = string> extends CommandLineChoiceParameter<TChoice> {
readonly value: TChoice;
}
/**
* The data type returned by {@link CommandLineParameterProvider.(defineChoiceParameter:1)}.
* @public
*/
export declare class CommandLineChoiceParameter<TChoice extends string = string> extends CommandLineParameterBase {
/** {@inheritDoc ICommandLineChoiceDefinition.alternatives} */
readonly alternatives: ReadonlySet<TChoice>;
/** {@inheritDoc ICommandLineStringDefinition.defaultValue} */
readonly defaultValue: TChoice | undefined;
private _value;
/** {@inheritDoc ICommandLineChoiceDefinition.completions} */
readonly completions: (() => Promise<ReadonlyArray<TChoice> | ReadonlySet<TChoice>>) | undefined;
/** {@inheritDoc CommandLineParameter.kind} */
readonly kind: CommandLineParameterKind.Choice;
/** @internal */
constructor(definition: ICommandLineChoiceDefinition<TChoice>);
/**
* {@inheritDoc CommandLineParameter._setValue}
* @internal
*/
_setValue(data: unknown): void;
/**
* {@inheritDoc CommandLineParameter._getSupplementaryNotes}
* @internal
*/
_getSupplementaryNotes(supplementaryNotes: string[]): void;
/**
* Returns the argument value for a choice parameter that was parsed from the command line.
*
* @remarks
* The return value will be `undefined` if the command-line has not been parsed yet,
* or if the parameter was omitted and has no default value.
*/
get value(): TChoice | undefined;
/** {@inheritDoc CommandLineParameter.appendToArgList} @override */
appendToArgList(argList: string[]): void;
}
//# sourceMappingURL=CommandLineChoiceParameter.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"CommandLineChoiceParameter.d.ts","sourceRoot":"","sources":["../../src/parameters/CommandLineChoiceParameter.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,4BAA4B,EAAE,MAAM,yBAAyB,CAAC;AAC5E,OAAO,EAAE,wBAAwB,EAAE,wBAAwB,EAAE,MAAM,eAAe,CAAC;AAEnF;;;GAGG;AACH,MAAM,WAAW,mCAAmC,CAAC,OAAO,SAAS,MAAM,GAAG,MAAM,CAClF,SAAQ,0BAA0B,CAAC,OAAO,CAAC;IAC3C,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAC;CACzB;AAED;;;GAGG;AACH,qBAAa,0BAA0B,CAAC,OAAO,SAAS,MAAM,GAAG,MAAM,CAAE,SAAQ,wBAAwB;IACvG,8DAA8D;IAC9D,SAAgB,YAAY,EAAE,WAAW,CAAC,OAAO,CAAC,CAAC;IAEnD,8DAA8D;IAC9D,SAAgB,YAAY,EAAE,OAAO,GAAG,SAAS,CAAC;IAElD,OAAO,CAAC,MAAM,CAAkC;IAEhD,6DAA6D;IAC7D,SAAgB,WAAW,EAAE,CAAC,MAAM,OAAO,CAAC,aAAa,CAAC,OAAO,CAAC,GAAG,WAAW,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,SAAS,CAAC;IAExG,8CAA8C;IAC9C,SAAgB,IAAI,EAAE,wBAAwB,CAAC,MAAM,CAAoC;IAEzF,gBAAgB;gBACG,UAAU,EAAE,4BAA4B,CAAC,OAAO,CAAC;IAuBpE;;;OAGG;IACI,SAAS,CAAC,IAAI,EAAE,OAAO,GAAG,IAAI;IAmCrC;;;OAGG;IACI,sBAAsB,CAAC,kBAAkB,EAAE,MAAM,EAAE,GAAG,IAAI;IAQjE;;;;;;OAMG;IACH,IAAW,KAAK,IAAI,OAAO,GAAG,SAAS,CAEtC;IAED,mEAAmE;IAC5D,eAAe,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI;CAMhD"}

View File

@@ -0,0 +1,94 @@
"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.CommandLineChoiceParameter = void 0;
const BaseClasses_1 = require("./BaseClasses");
/**
* The data type returned by {@link CommandLineParameterProvider.(defineChoiceParameter:1)}.
* @public
*/
class CommandLineChoiceParameter extends BaseClasses_1.CommandLineParameterBase {
/** @internal */
constructor(definition) {
super(definition);
this._value = undefined;
/** {@inheritDoc CommandLineParameter.kind} */
this.kind = -BaseClasses_1.CommandLineParameterKind.Choice;
const { alternatives, defaultValue, completions } = definition;
const alternativesSet = alternatives instanceof Set ? alternatives : new Set(alternatives);
if (alternativesSet.size < 1) {
throw new Error(`When defining a choice parameter, the alternatives list must contain at least one value.`);
}
if (defaultValue && !alternativesSet.has(defaultValue)) {
throw new Error(`The specified default value "${defaultValue}"` +
` is not one of the available options: ${alternatives.toString()}`);
}
this.alternatives = alternativesSet;
this.defaultValue = defaultValue;
this.validateDefaultValue(!!this.defaultValue);
this.completions = completions;
}
/**
* {@inheritDoc CommandLineParameter._setValue}
* @internal
*/
_setValue(data) {
// abstract
if (data !== null && data !== undefined) {
if (typeof data !== 'string') {
this.reportInvalidData(data);
}
this._value = data;
return;
}
if (this.environmentVariable !== undefined) {
// Try reading the environment variable
const environmentValue = process.env[this.environmentVariable];
if (environmentValue !== undefined && environmentValue !== '') {
if (!this.alternatives.has(environmentValue)) {
const choices = '"' + Array.from(this.alternatives).join('", "') + '"';
throw new Error(`Invalid value "${environmentValue}" for the environment variable` +
` ${this.environmentVariable}. Valid choices are: ${choices}`);
}
this._value = environmentValue;
return;
}
}
if (this.defaultValue !== undefined) {
this._value = this.defaultValue;
return;
}
this._value = undefined;
}
/**
* {@inheritDoc CommandLineParameter._getSupplementaryNotes}
* @internal
*/
_getSupplementaryNotes(supplementaryNotes) {
// virtual
super._getSupplementaryNotes(supplementaryNotes);
if (this.defaultValue !== undefined) {
supplementaryNotes.push(`The default value is "${this.defaultValue}".`);
}
}
/**
* Returns the argument value for a choice parameter that was parsed from the command line.
*
* @remarks
* The return value will be `undefined` if the command-line has not been parsed yet,
* or if the parameter was omitted and has no default value.
*/
get value() {
return this._value;
}
/** {@inheritDoc CommandLineParameter.appendToArgList} @override */
appendToArgList(argList) {
if (this.value !== undefined) {
argList.push(this.longName);
argList.push(this.value);
}
}
}
exports.CommandLineChoiceParameter = CommandLineChoiceParameter;
//# sourceMappingURL=CommandLineChoiceParameter.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,236 @@
import type { SCOPING_PARAMETER_GROUP } from '../Constants';
/**
* For use with CommandLineParser, this interface represents a generic command-line parameter
*
* @public
*/
export interface IBaseCommandLineDefinition {
/**
* The long name of the flag including double dashes, e.g. "--do-something"
*/
parameterLongName: string;
/**
* An optional short name for the flag including the dash, e.g. "-d"
*/
parameterShortName?: string;
/**
* An optional parameter group name, shown when invoking the tool with "--help"
*/
parameterGroup?: string | typeof SCOPING_PARAMETER_GROUP;
/**
* An optional parameter scope name, used to add a scope-prefixed parameter synonym,
* e.g. "--scope:do-something". Scopes provide additional flexibility for parameters
* in conflict resolution since when a scope is specified, parameters that have
* conflicting long names will be defined using only the scope-prefixed name.
*/
parameterScope?: string;
/**
* Documentation for the parameter that will be shown when invoking the tool with "--help"
*/
description: string;
/**
* If true, then an error occurs if the parameter was not included on the command-line.
*/
required?: boolean;
/**
* The name of an environment variable that the parameter value will be read from,
* if it was omitted from the command-line. An error will be reported if the
* environment value cannot be parsed.
*
* @remarks
* The environment variable name must consist only of upper-case letters, numbers,
* and underscores. It may not start with a number. To disable this validation, set
* `{@link IBaseCommandLineDefinition.allowNonStandardEnvironmentVariableNames}`
* to `true`.
*
* Syntax notes for environment variable values:
*
* - Choice Parameter: The value must match one of the defined choices,
* otherwise a validation error is reported.
* An empty string causes the environment variable to be ignored.
*
* - Flag Parameter: The value must be `1` for true, or `0` for false,
* otherwise a validation error is reported.
* An empty string causes the environment variable to be ignored.
*
* - Integer Parameter: The value must be an integer number,
* otherwise a validation error is reported.
* An empty string causes the environment variable to be ignored.
*
* - String Parameter: Any value is accepted, including an empty string.
*
* - String List Parameter: If the string starts with `[` (ignoring whitespace)
* then it will be parsed as a JSON array, whose elements must be strings,
* numbers, or boolean values.
* If the string does not start with `[`, then it behaves like an
* ordinary String Parameter: Any value is accepted, including an empty string.
*/
environmentVariable?: string;
/**
* Allows for the use of environment variable names that do not conform to the standard
* described by the Shell and Utilities volume of IEEE Std 1003.1-2001. This disables
* the validation that is performed on the provided
* {@link IBaseCommandLineDefinition.environmentVariable} value by default.
*
* @remarks
* if this is set to `true`, environment variable discovery will vary based on the
* platform in use. For example, Windows environment variable names are case-insensitive,
* while on Linux, environment variable names are case-sensitive. It is recommended that
* this option be used only when necessary based on environmental constraints.
*/
allowNonStandardEnvironmentVariableNames?: boolean;
/**
* Specifies additional names for this parameter that are accepted but not displayed
* in the command line help.
*
* @remarks
* This option can be used in cases where a command-line parameter may have been renamed,
* but the developer doesn't want to break backwards compatibility with systems that may
* still be using the old name. Only the `parameterLongName` syntax is currently allowed.
*/
undocumentedSynonyms?: string[];
}
/**
* The common base interface for parameter types that accept an argument.
*
* @remarks
* An argument is an accompanying command-line token, such as "123" in the
* example "--max-count 123".
* @public
*/
export interface IBaseCommandLineDefinitionWithArgument extends IBaseCommandLineDefinition {
/**
* The name of the argument, which will be shown in the command-line help.
*
* @remarks
* For example, if the parameter name is '--count" and the argument name is "NUMBER",
* then the command-line help would display "--count NUMBER". The argument name must
* be comprised of upper-case letters, numbers, and underscores. It should be kept short.
*/
argumentName: string;
/**
* An optional callback that provides a list of custom choices for tab completion.
* @remarks
* This option is only used when `ICommandLineParserOptions.enableTabCompletionAction`
* is enabled.
*
* In a future release, this will be renamed to `getCompletionsAsync`
*/
completions?: () => Promise<ReadonlyArray<string> | ReadonlySet<string>>;
}
/**
* For use with {@link CommandLineParameterProvider.(defineChoiceParameter:1)} and
* {@link CommandLineParameterProvider.(defineChoiceParameter:2)}, this interface
* defines a command line parameter which is constrained to a list of possible
* options.
*
* @public
*/
export interface ICommandLineChoiceDefinition<TChoice extends string = string> extends IBaseCommandLineDefinition {
/**
* A list of strings (which contain no spaces), of possible options which can be selected
*/
alternatives: ReadonlyArray<TChoice> | ReadonlySet<TChoice>;
/**
* {@inheritDoc ICommandLineStringDefinition.defaultValue}
*/
defaultValue?: TChoice;
/**
* An optional callback that provides a list of custom choices for tab completion.
* @remarks
* This option is only used when `ICommandLineParserOptions.enableTabCompletionAction`
* is enabled.
*/
completions?: () => Promise<ReadonlyArray<TChoice> | ReadonlySet<TChoice>>;
}
/**
* For use with {@link CommandLineParameterProvider.defineChoiceListParameter},
* this interface defines a command line parameter which is constrained to a list of possible
* options. The parameter can be specified multiple times to build a list.
*
* @public
*/
export interface ICommandLineChoiceListDefinition<TChoice extends string = string> extends IBaseCommandLineDefinition {
/**
* A list of strings (which contain no spaces), of possible options which can be selected
*/
alternatives: ReadonlyArray<TChoice> | ReadonlySet<TChoice>;
/**
* An optional callback that provides a list of custom choices for tab completion.
* @remarks
* This option is only used when `ICommandLineParserOptions.enableTabCompletionAction`
* is enabled.
*/
completions?: () => Promise<ReadonlyArray<TChoice> | ReadonlySet<TChoice>>;
}
/**
* For use with {@link CommandLineParameterProvider.defineFlagParameter},
* this interface defines a command line parameter that is a boolean flag.
*
* @public
*/
export interface ICommandLineFlagDefinition extends IBaseCommandLineDefinition {
}
/**
* For use with {@link CommandLineParameterProvider.(defineIntegerParameter:1)},
* {@link CommandLineParameterProvider.(defineIntegerParameter:2)}, this interface
* defines a command line parameter whose argument is an integer value.
*
* @public
*/
export interface ICommandLineIntegerDefinition extends IBaseCommandLineDefinitionWithArgument {
/**
* {@inheritDoc ICommandLineStringDefinition.defaultValue}
*/
defaultValue?: number;
}
/**
* For use with {@link CommandLineParameterProvider.defineIntegerListParameter},
* this interface defines a command line parameter whose argument is an integer value. The
* parameter can be specified multiple times to build a list.
*
* @public
*/
export interface ICommandLineIntegerListDefinition extends IBaseCommandLineDefinitionWithArgument {
}
/**
* For use with {@link CommandLineParameterProvider.(defineStringParameter:1)} and
* {@link CommandLineParameterProvider.(defineStringParameter:2)}, this interface
* defines a command line parameter whose argument is a string value.
*
* @public
*/
export interface ICommandLineStringDefinition extends IBaseCommandLineDefinitionWithArgument {
/**
* The default value which will be used if the parameter is omitted from the command line.
*
* @remarks
* If a default value is specified, then {@link IBaseCommandLineDefinition.required}
* must not be true. Instead, a custom error message should be used to report cases
* where a default value was not available.
*/
defaultValue?: string;
}
/**
* For use with {@link CommandLineParameterProvider.defineStringListParameter},
* this interface defines a command line parameter whose argument is a single text string.
* The parameter can be specified multiple times to build a list.
*
* @public
*/
export interface ICommandLineStringListDefinition extends IBaseCommandLineDefinitionWithArgument {
}
/**
* For use with {@link CommandLineParameterProvider.defineCommandLineRemainder},
* this interface defines a rule that captures any remaining command line arguments after the recognized portion.
*
* @public
*/
export interface ICommandLineRemainderDefinition {
/**
* Documentation for how the remaining arguments will be used. This will be shown when invoking
* the tool with "--help".
*/
description: string;
}
//# sourceMappingURL=CommandLineDefinition.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"CommandLineDefinition.d.ts","sourceRoot":"","sources":["../../src/parameters/CommandLineDefinition.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,cAAc,CAAC;AAE5D;;;;GAIG;AACH,MAAM,WAAW,0BAA0B;IACzC;;OAEG;IACH,iBAAiB,EAAE,MAAM,CAAC;IAE1B;;OAEG;IACH,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAE5B;;OAEG;IACH,cAAc,CAAC,EAAE,MAAM,GAAG,OAAO,uBAAuB,CAAC;IAEzD;;;;;OAKG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;IAExB;;OAEG;IACH,WAAW,EAAE,MAAM,CAAC;IAEpB;;OAEG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAC;IAEnB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAgCG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAE7B;;;;;;;;;;;OAWG;IACH,wCAAwC,CAAC,EAAE,OAAO,CAAC;IAEnD;;;;;;;;OAQG;IACH,oBAAoB,CAAC,EAAE,MAAM,EAAE,CAAC;CACjC;AAED;;;;;;;GAOG;AACH,MAAM,WAAW,sCAAuC,SAAQ,0BAA0B;IACxF;;;;;;;OAOG;IACH,YAAY,EAAE,MAAM,CAAC;IAErB;;;;;;;OAOG;IACH,WAAW,CAAC,EAAE,MAAM,OAAO,CAAC,aAAa,CAAC,MAAM,CAAC,GAAG,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC;CAC1E;AAED;;;;;;;GAOG;AACH,MAAM,WAAW,4BAA4B,CAAC,OAAO,SAAS,MAAM,GAAG,MAAM,CAC3E,SAAQ,0BAA0B;IAClC;;OAEG;IACH,YAAY,EAAE,aAAa,CAAC,OAAO,CAAC,GAAG,WAAW,CAAC,OAAO,CAAC,CAAC;IAE5D;;OAEG;IACH,YAAY,CAAC,EAAE,OAAO,CAAC;IAEvB;;;;;OAKG;IACH,WAAW,CAAC,EAAE,MAAM,OAAO,CAAC,aAAa,CAAC,OAAO,CAAC,GAAG,WAAW,CAAC,OAAO,CAAC,CAAC,CAAC;CAC5E;AAED;;;;;;GAMG;AACH,MAAM,WAAW,gCAAgC,CAAC,OAAO,SAAS,MAAM,GAAG,MAAM,CAC/E,SAAQ,0BAA0B;IAClC;;OAEG;IACH,YAAY,EAAE,aAAa,CAAC,OAAO,CAAC,GAAG,WAAW,CAAC,OAAO,CAAC,CAAC;IAE5D;;;;;OAKG;IACH,WAAW,CAAC,EAAE,MAAM,OAAO,CAAC,aAAa,CAAC,OAAO,CAAC,GAAG,WAAW,CAAC,OAAO,CAAC,CAAC,CAAC;CAC5E;AAED;;;;;GAKG;AACH,MAAM,WAAW,0BAA2B,SAAQ,0BAA0B;CAAG;AAEjF;;;;;;GAMG;AACH,MAAM,WAAW,6BAA8B,SAAQ,sCAAsC;IAC3F;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AAED;;;;;;GAMG;AACH,MAAM,WAAW,iCAAkC,SAAQ,sCAAsC;CAAG;AAEpG;;;;;;GAMG;AACH,MAAM,WAAW,4BAA6B,SAAQ,sCAAsC;IAC1F;;;;;;;OAOG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AAED;;;;;;GAMG;AACH,MAAM,WAAW,gCAAiC,SAAQ,sCAAsC;CAAG;AAEnG;;;;;GAKG;AACH,MAAM,WAAW,+BAA+B;IAC9C;;;OAGG;IACH,WAAW,EAAE,MAAM,CAAC;CACrB"}

View File

@@ -0,0 +1,5 @@
"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 });
//# sourceMappingURL=CommandLineDefinition.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,29 @@
import type { ICommandLineFlagDefinition } from './CommandLineDefinition';
import { CommandLineParameterBase, CommandLineParameterKind } from './BaseClasses';
/**
* The data type returned by {@link CommandLineParameterProvider.defineFlagParameter}.
* @public
*/
export declare class CommandLineFlagParameter extends CommandLineParameterBase {
private _value;
/** {@inheritDoc CommandLineParameter.kind} */
readonly kind: CommandLineParameterKind.Flag;
/** @internal */
constructor(definition: ICommandLineFlagDefinition);
/**
* {@inheritDoc CommandLineParameter._setValue}
* @internal
*/
_setValue(data: unknown): void;
/**
* Returns a boolean indicating whether the parameter was included in the command line.
*
* @remarks
* The return value will be false if the command-line has not been parsed yet,
* or if the flag was not used.
*/
get value(): boolean;
/** {@inheritDoc CommandLineParameter.appendToArgList} @override */
appendToArgList(argList: string[]): void;
}
//# sourceMappingURL=CommandLineFlagParameter.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"CommandLineFlagParameter.d.ts","sourceRoot":"","sources":["../../src/parameters/CommandLineFlagParameter.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,yBAAyB,CAAC;AAC1E,OAAO,EAAE,wBAAwB,EAAE,wBAAwB,EAAE,MAAM,eAAe,CAAC;AAEnF;;;GAGG;AACH,qBAAa,wBAAyB,SAAQ,wBAAwB;IACpE,OAAO,CAAC,MAAM,CAAkB;IAEhC,8CAA8C;IAC9C,SAAgB,IAAI,EAAE,wBAAwB,CAAC,IAAI,CAAiC;IAEpF,gBAAgB;gBACG,UAAU,EAAE,0BAA0B;IAIzD;;;OAGG;IACI,SAAS,CAAC,IAAI,EAAE,OAAO,GAAG,IAAI;IAkCrC;;;;;;OAMG;IACH,IAAW,KAAK,IAAI,OAAO,CAE1B;IAED,mEAAmE;IAC5D,eAAe,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI;CAKhD"}

View File

@@ -0,0 +1,69 @@
"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.CommandLineFlagParameter = void 0;
const BaseClasses_1 = require("./BaseClasses");
/**
* The data type returned by {@link CommandLineParameterProvider.defineFlagParameter}.
* @public
*/
class CommandLineFlagParameter extends BaseClasses_1.CommandLineParameterBase {
/** @internal */
constructor(definition) {
super(definition);
this._value = false;
/** {@inheritDoc CommandLineParameter.kind} */
this.kind = BaseClasses_1.CommandLineParameterKind.Flag;
}
/**
* {@inheritDoc CommandLineParameter._setValue}
* @internal
*/
_setValue(data) {
// abstract
if (data !== null && data !== undefined) {
if (typeof data !== 'boolean') {
this.reportInvalidData(data);
}
// If the flag is omitted, then argparse sets the data to "false" instead of "undefined".
// This design prevents a syntax such as "--flag=false", probably because argparse prefers "--no-flag".
// If we switch to a new CLI parser, we should try to add support for "--flag=false".
if (data) {
this._value = data;
return;
}
}
if (this.environmentVariable !== undefined) {
// Try reading the environment variable
const environmentValue = process.env[this.environmentVariable];
if (environmentValue !== undefined && environmentValue !== '') {
if (environmentValue !== '0' && environmentValue !== '1') {
throw new Error(`Invalid value "${environmentValue}" for the environment variable` +
` ${this.environmentVariable}. Valid choices are 0 or 1.`);
}
this._value = environmentValue === '1';
return;
}
}
this._value = false;
}
/**
* Returns a boolean indicating whether the parameter was included in the command line.
*
* @remarks
* The return value will be false if the command-line has not been parsed yet,
* or if the flag was not used.
*/
get value() {
return this._value;
}
/** {@inheritDoc CommandLineParameter.appendToArgList} @override */
appendToArgList(argList) {
if (this.value) {
argList.push(this.longName);
}
}
}
exports.CommandLineFlagParameter = CommandLineFlagParameter;
//# sourceMappingURL=CommandLineFlagParameter.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"CommandLineFlagParameter.js","sourceRoot":"","sources":["../../src/parameters/CommandLineFlagParameter.ts"],"names":[],"mappings":";AAAA,4FAA4F;AAC5F,2DAA2D;;;AAG3D,+CAAmF;AAEnF;;;GAGG;AACH,MAAa,wBAAyB,SAAQ,sCAAwB;IAMpE,gBAAgB;IAChB,YAAmB,UAAsC;QACvD,KAAK,CAAC,UAAU,CAAC,CAAC;QAPZ,WAAM,GAAY,KAAK,CAAC;QAEhC,8CAA8C;QAC9B,SAAI,GAAkC,sCAAwB,CAAC,IAAI,CAAC;IAKpF,CAAC;IAED;;;OAGG;IACI,SAAS,CAAC,IAAa;QAC5B,WAAW;QACX,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;YACxC,IAAI,OAAO,IAAI,KAAK,SAAS,EAAE,CAAC;gBAC9B,IAAI,CAAC,iBAAiB,CAAC,IAAI,CAAC,CAAC;YAC/B,CAAC;YAED,yFAAyF;YACzF,uGAAuG;YACvG,qFAAqF;YACrF,IAAI,IAAI,EAAE,CAAC;gBACT,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC;gBACnB,OAAO;YACT,CAAC;QACH,CAAC;QAED,IAAI,IAAI,CAAC,mBAAmB,KAAK,SAAS,EAAE,CAAC;YAC3C,uCAAuC;YACvC,MAAM,gBAAgB,GAAuB,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAAC;YACnF,IAAI,gBAAgB,KAAK,SAAS,IAAI,gBAAgB,KAAK,EAAE,EAAE,CAAC;gBAC9D,IAAI,gBAAgB,KAAK,GAAG,IAAI,gBAAgB,KAAK,GAAG,EAAE,CAAC;oBACzD,MAAM,IAAI,KAAK,CACb,kBAAkB,gBAAgB,gCAAgC;wBAChE,IAAI,IAAI,CAAC,mBAAmB,8BAA8B,CAC7D,CAAC;gBACJ,CAAC;gBACD,IAAI,CAAC,MAAM,GAAG,gBAAgB,KAAK,GAAG,CAAC;gBACvC,OAAO;YACT,CAAC;QACH,CAAC;QAED,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC;IACtB,CAAC;IAED;;;;;;OAMG;IACH,IAAW,KAAK;QACd,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;IAED,mEAAmE;IAC5D,eAAe,CAAC,OAAiB;QACtC,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QAC9B,CAAC;IACH,CAAC;CACF;AAlED,4DAkEC","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 { ICommandLineFlagDefinition } from './CommandLineDefinition';\nimport { CommandLineParameterBase, CommandLineParameterKind } from './BaseClasses';\n\n/**\n * The data type returned by {@link CommandLineParameterProvider.defineFlagParameter}.\n * @public\n */\nexport class CommandLineFlagParameter extends CommandLineParameterBase {\n private _value: boolean = false;\n\n /** {@inheritDoc CommandLineParameter.kind} */\n public readonly kind: CommandLineParameterKind.Flag = CommandLineParameterKind.Flag;\n\n /** @internal */\n public constructor(definition: ICommandLineFlagDefinition) {\n super(definition);\n }\n\n /**\n * {@inheritDoc CommandLineParameter._setValue}\n * @internal\n */\n public _setValue(data: unknown): void {\n // abstract\n if (data !== null && data !== undefined) {\n if (typeof data !== 'boolean') {\n this.reportInvalidData(data);\n }\n\n // If the flag is omitted, then argparse sets the data to \"false\" instead of \"undefined\".\n // This design prevents a syntax such as \"--flag=false\", probably because argparse prefers \"--no-flag\".\n // If we switch to a new CLI parser, we should try to add support for \"--flag=false\".\n if (data) {\n this._value = data;\n return;\n }\n }\n\n if (this.environmentVariable !== undefined) {\n // Try reading the environment variable\n const environmentValue: string | undefined = process.env[this.environmentVariable];\n if (environmentValue !== undefined && environmentValue !== '') {\n if (environmentValue !== '0' && environmentValue !== '1') {\n throw new Error(\n `Invalid value \"${environmentValue}\" for the environment variable` +\n ` ${this.environmentVariable}. Valid choices are 0 or 1.`\n );\n }\n this._value = environmentValue === '1';\n return;\n }\n }\n\n this._value = false;\n }\n\n /**\n * Returns a boolean indicating whether the parameter was included in the command line.\n *\n * @remarks\n * The return value will be false if the command-line has not been parsed yet,\n * or if the flag was not used.\n */\n public get value(): boolean {\n return this._value;\n }\n\n /** {@inheritDoc CommandLineParameter.appendToArgList} @override */\n public appendToArgList(argList: string[]): void {\n if (this.value) {\n argList.push(this.longName);\n }\n }\n}\n"]}

View File

@@ -0,0 +1,29 @@
import type { ICommandLineIntegerListDefinition } from './CommandLineDefinition';
import { CommandLineParameterWithArgument, CommandLineParameterKind } from './BaseClasses';
/**
* The data type returned by {@link CommandLineParameterProvider.defineIntegerListParameter}.
* @public
*/
export declare class CommandLineIntegerListParameter extends CommandLineParameterWithArgument {
private _values;
/** {@inheritDoc CommandLineParameter.kind} */
readonly kind: CommandLineParameterKind.IntegerList;
/** @internal */
constructor(definition: ICommandLineIntegerListDefinition);
/**
* {@inheritDoc CommandLineParameter._setValue}
* @internal
*/
_setValue(data: unknown): void;
/**
* Returns the integer arguments for an integer list parameter that was parsed from the command line.
*
* @remarks
* The array will be empty if the command-line has not been parsed yet,
* or if the parameter was omitted and has no default value.
*/
get values(): ReadonlyArray<number>;
/** {@inheritDoc CommandLineParameter.appendToArgList} @override */
appendToArgList(argList: string[]): void;
}
//# sourceMappingURL=CommandLineIntegerListParameter.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"CommandLineIntegerListParameter.d.ts","sourceRoot":"","sources":["../../src/parameters/CommandLineIntegerListParameter.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,iCAAiC,EAAE,MAAM,yBAAyB,CAAC;AACjF,OAAO,EAAE,gCAAgC,EAAE,wBAAwB,EAAE,MAAM,eAAe,CAAC;AAG3F;;;GAGG;AACH,qBAAa,+BAAgC,SAAQ,gCAAgC;IACnF,OAAO,CAAC,OAAO,CAAgB;IAE/B,8CAA8C;IAC9C,SAAgB,IAAI,EAAE,wBAAwB,CAAC,WAAW,CAAwC;IAElG,gBAAgB;gBACG,UAAU,EAAE,iCAAiC;IAIhE;;;OAGG;IACI,SAAS,CAAC,IAAI,EAAE,OAAO,GAAG,IAAI;IAwCrC;;;;;;OAMG;IACH,IAAW,MAAM,IAAI,aAAa,CAAC,MAAM,CAAC,CAEzC;IAED,mEAAmE;IAC5D,eAAe,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI;CAQhD"}

View File

@@ -0,0 +1,79 @@
"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.CommandLineIntegerListParameter = void 0;
const BaseClasses_1 = require("./BaseClasses");
const EnvironmentVariableParser_1 = require("./EnvironmentVariableParser");
/**
* The data type returned by {@link CommandLineParameterProvider.defineIntegerListParameter}.
* @public
*/
class CommandLineIntegerListParameter extends BaseClasses_1.CommandLineParameterWithArgument {
/** @internal */
constructor(definition) {
super(definition);
this._values = [];
/** {@inheritDoc CommandLineParameter.kind} */
this.kind = BaseClasses_1.CommandLineParameterKind.IntegerList;
}
/**
* {@inheritDoc CommandLineParameter._setValue}
* @internal
*/
_setValue(data) {
// If argparse passed us a value, confirm it is valid
if (data !== null && data !== undefined) {
if (!Array.isArray(data)) {
this.reportInvalidData(data);
}
for (const arrayItem of data) {
if (typeof arrayItem !== 'number') {
this.reportInvalidData(data);
}
}
this._values = data;
return;
}
// If an environment variable exists, attempt to parse it as a list
if (this.environmentVariable !== undefined) {
const values = EnvironmentVariableParser_1.EnvironmentVariableParser.parseAsList(this.environmentVariable);
if (values) {
const parsedValues = [];
for (const value of values) {
const parsed = parseInt(value, 10);
if (isNaN(parsed) || value.indexOf('.') >= 0) {
throw new Error(`Invalid value "${value}" for the environment variable` +
` ${this.environmentVariable}. It must be an integer value.`);
}
parsedValues.push(parsed);
}
this._values = parsedValues;
return;
}
}
// (No default value for integer lists)
this._values = [];
}
/**
* Returns the integer arguments for an integer list parameter that was parsed from the command line.
*
* @remarks
* The array will be empty if the command-line has not been parsed yet,
* or if the parameter was omitted and has no default value.
*/
get values() {
return this._values;
}
/** {@inheritDoc CommandLineParameter.appendToArgList} @override */
appendToArgList(argList) {
if (this.values.length > 0) {
for (const value of this.values) {
argList.push(this.longName);
argList.push(value.toString());
}
}
}
}
exports.CommandLineIntegerListParameter = CommandLineIntegerListParameter;
//# sourceMappingURL=CommandLineIntegerListParameter.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"CommandLineIntegerListParameter.js","sourceRoot":"","sources":["../../src/parameters/CommandLineIntegerListParameter.ts"],"names":[],"mappings":";AAAA,4FAA4F;AAC5F,2DAA2D;;;AAG3D,+CAA2F;AAC3F,2EAAwE;AAExE;;;GAGG;AACH,MAAa,+BAAgC,SAAQ,8CAAgC;IAMnF,gBAAgB;IAChB,YAAmB,UAA6C;QAC9D,KAAK,CAAC,UAAU,CAAC,CAAC;QAPZ,YAAO,GAAa,EAAE,CAAC;QAE/B,8CAA8C;QAC9B,SAAI,GAAyC,sCAAwB,CAAC,WAAW,CAAC;IAKlG,CAAC;IAED;;;OAGG;IACI,SAAS,CAAC,IAAa;QAC5B,qDAAqD;QACrD,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;YACxC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC;gBACzB,IAAI,CAAC,iBAAiB,CAAC,IAAI,CAAC,CAAC;YAC/B,CAAC;YACD,KAAK,MAAM,SAAS,IAAI,IAAI,EAAE,CAAC;gBAC7B,IAAI,OAAO,SAAS,KAAK,QAAQ,EAAE,CAAC;oBAClC,IAAI,CAAC,iBAAiB,CAAC,IAAI,CAAC,CAAC;gBAC/B,CAAC;YACH,CAAC;YACD,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;YACpB,OAAO;QACT,CAAC;QAED,mEAAmE;QACnE,IAAI,IAAI,CAAC,mBAAmB,KAAK,SAAS,EAAE,CAAC;YAC3C,MAAM,MAAM,GAAyB,qDAAyB,CAAC,WAAW,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAAC;YACrG,IAAI,MAAM,EAAE,CAAC;gBACX,MAAM,YAAY,GAAa,EAAE,CAAC;gBAClC,KAAK,MAAM,KAAK,IAAI,MAAM,EAAE,CAAC;oBAC3B,MAAM,MAAM,GAAW,QAAQ,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;oBAC3C,IAAI,KAAK,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC;wBAC7C,MAAM,IAAI,KAAK,CACb,kBAAkB,KAAK,gCAAgC;4BACrD,IAAI,IAAI,CAAC,mBAAmB,iCAAiC,CAChE,CAAC;oBACJ,CAAC;oBACD,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;gBAC5B,CAAC;gBACD,IAAI,CAAC,OAAO,GAAG,YAAY,CAAC;gBAC5B,OAAO;YACT,CAAC;QACH,CAAC;QAED,uCAAuC;QAEvC,IAAI,CAAC,OAAO,GAAG,EAAE,CAAC;IACpB,CAAC;IAED;;;;;;OAMG;IACH,IAAW,MAAM;QACf,OAAO,IAAI,CAAC,OAAO,CAAC;IACtB,CAAC;IAED,mEAAmE;IAC5D,eAAe,CAAC,OAAiB;QACtC,IAAI,IAAI,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YAC3B,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;gBAChC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;gBAC5B,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,CAAC,CAAC;YACjC,CAAC;QACH,CAAC;IACH,CAAC;CACF;AA3ED,0EA2EC","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 { ICommandLineIntegerListDefinition } from './CommandLineDefinition';\nimport { CommandLineParameterWithArgument, CommandLineParameterKind } from './BaseClasses';\nimport { EnvironmentVariableParser } from './EnvironmentVariableParser';\n\n/**\n * The data type returned by {@link CommandLineParameterProvider.defineIntegerListParameter}.\n * @public\n */\nexport class CommandLineIntegerListParameter extends CommandLineParameterWithArgument {\n private _values: number[] = [];\n\n /** {@inheritDoc CommandLineParameter.kind} */\n public readonly kind: CommandLineParameterKind.IntegerList = CommandLineParameterKind.IntegerList;\n\n /** @internal */\n public constructor(definition: ICommandLineIntegerListDefinition) {\n super(definition);\n }\n\n /**\n * {@inheritDoc CommandLineParameter._setValue}\n * @internal\n */\n public _setValue(data: unknown): void {\n // If argparse passed us a value, confirm it is valid\n if (data !== null && data !== undefined) {\n if (!Array.isArray(data)) {\n this.reportInvalidData(data);\n }\n for (const arrayItem of data) {\n if (typeof arrayItem !== 'number') {\n this.reportInvalidData(data);\n }\n }\n this._values = data;\n return;\n }\n\n // If an environment variable exists, attempt to parse it as a list\n if (this.environmentVariable !== undefined) {\n const values: string[] | undefined = EnvironmentVariableParser.parseAsList(this.environmentVariable);\n if (values) {\n const parsedValues: number[] = [];\n for (const value of values) {\n const parsed: number = parseInt(value, 10);\n if (isNaN(parsed) || value.indexOf('.') >= 0) {\n throw new Error(\n `Invalid value \"${value}\" for the environment variable` +\n ` ${this.environmentVariable}. It must be an integer value.`\n );\n }\n parsedValues.push(parsed);\n }\n this._values = parsedValues;\n return;\n }\n }\n\n // (No default value for integer lists)\n\n this._values = [];\n }\n\n /**\n * Returns the integer arguments for an integer list parameter that was parsed from the command line.\n *\n * @remarks\n * The array will be empty if the command-line has not been parsed yet,\n * or if the parameter was omitted and has no default value.\n */\n public get values(): ReadonlyArray<number> {\n return this._values;\n }\n\n /** {@inheritDoc CommandLineParameter.appendToArgList} @override */\n public appendToArgList(argList: string[]): void {\n if (this.values.length > 0) {\n for (const value of this.values) {\n argList.push(this.longName);\n argList.push(value.toString());\n }\n }\n }\n}\n"]}

View File

@@ -0,0 +1,43 @@
import type { ICommandLineIntegerDefinition } from './CommandLineDefinition';
import { CommandLineParameterWithArgument, CommandLineParameterKind } from './BaseClasses';
/**
* The data type returned by {@link CommandLineParameterProvider.(defineIntegerParameter:2)}.
* @public
*/
export interface IRequiredCommandLineIntegerParameter extends CommandLineIntegerParameter {
readonly value: number;
}
/**
* The data type returned by {@link CommandLineParameterProvider.(defineIntegerParameter:1)}.
* @public
*/
export declare class CommandLineIntegerParameter extends CommandLineParameterWithArgument {
/** {@inheritDoc ICommandLineStringDefinition.defaultValue} */
readonly defaultValue: number | undefined;
private _value;
/** {@inheritDoc CommandLineParameter.kind} */
readonly kind: CommandLineParameterKind.Integer;
/** @internal */
constructor(definition: ICommandLineIntegerDefinition);
/**
* {@inheritDoc CommandLineParameter._setValue}
* @internal
*/
_setValue(data: unknown): void;
/**
* {@inheritDoc CommandLineParameter._getSupplementaryNotes}
* @internal
*/
_getSupplementaryNotes(supplementaryNotes: string[]): void;
/**
* Returns the argument value for an integer parameter that was parsed from the command line.
*
* @remarks
* The return value will be undefined if the command-line has not been parsed yet,
* or if the parameter was omitted and has no default value.
*/
get value(): number | undefined;
/** {@inheritDoc CommandLineParameter.appendToArgList} @override */
appendToArgList(argList: string[]): void;
}
//# sourceMappingURL=CommandLineIntegerParameter.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"CommandLineIntegerParameter.d.ts","sourceRoot":"","sources":["../../src/parameters/CommandLineIntegerParameter.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,6BAA6B,EAAE,MAAM,yBAAyB,CAAC;AAC7E,OAAO,EAAE,gCAAgC,EAAE,wBAAwB,EAAE,MAAM,eAAe,CAAC;AAE3F;;;GAGG;AACH,MAAM,WAAW,oCAAqC,SAAQ,2BAA2B;IACvF,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;CACxB;AAED;;;GAGG;AACH,qBAAa,2BAA4B,SAAQ,gCAAgC;IAC/E,8DAA8D;IAC9D,SAAgB,YAAY,EAAE,MAAM,GAAG,SAAS,CAAC;IAEjD,OAAO,CAAC,MAAM,CAAiC;IAE/C,8CAA8C;IAC9C,SAAgB,IAAI,EAAE,wBAAwB,CAAC,OAAO,CAAoC;IAE1F,gBAAgB;gBACG,UAAU,EAAE,6BAA6B;IAM5D;;;OAGG;IACI,SAAS,CAAC,IAAI,EAAE,OAAO,GAAG,IAAI;IAkCrC;;;OAGG;IACI,sBAAsB,CAAC,kBAAkB,EAAE,MAAM,EAAE,GAAG,IAAI;IAQjE;;;;;;OAMG;IACH,IAAW,KAAK,IAAI,MAAM,GAAG,SAAS,CAErC;IAED,mEAAmE;IAC5D,eAAe,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI;CAMhD"}

View File

@@ -0,0 +1,83 @@
"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.CommandLineIntegerParameter = void 0;
const BaseClasses_1 = require("./BaseClasses");
/**
* The data type returned by {@link CommandLineParameterProvider.(defineIntegerParameter:1)}.
* @public
*/
class CommandLineIntegerParameter extends BaseClasses_1.CommandLineParameterWithArgument {
/** @internal */
constructor(definition) {
super(definition);
this._value = undefined;
/** {@inheritDoc CommandLineParameter.kind} */
this.kind = BaseClasses_1.CommandLineParameterKind.Integer;
this.defaultValue = definition.defaultValue;
this.validateDefaultValue(!!this.defaultValue);
}
/**
* {@inheritDoc CommandLineParameter._setValue}
* @internal
*/
_setValue(data) {
// abstract
if (data !== null && data !== undefined) {
if (typeof data !== 'number') {
this.reportInvalidData(data);
}
this._value = data;
return;
}
if (this.environmentVariable !== undefined) {
// Try reading the environment variable
const environmentValue = process.env[this.environmentVariable];
if (environmentValue !== undefined && environmentValue !== '') {
const parsed = parseInt(environmentValue, 10);
if (isNaN(parsed) || environmentValue.indexOf('.') >= 0) {
throw new Error(`Invalid value "${environmentValue}" for the environment variable` +
` ${this.environmentVariable}. It must be an integer value.`);
}
this._value = parsed;
return;
}
}
if (this.defaultValue !== undefined) {
this._value = this.defaultValue;
return;
}
this._value = undefined;
}
/**
* {@inheritDoc CommandLineParameter._getSupplementaryNotes}
* @internal
*/
_getSupplementaryNotes(supplementaryNotes) {
// virtual
super._getSupplementaryNotes(supplementaryNotes);
if (this.defaultValue !== undefined) {
supplementaryNotes.push(`The default value is ${this.defaultValue}.`);
}
}
/**
* Returns the argument value for an integer parameter that was parsed from the command line.
*
* @remarks
* The return value will be undefined if the command-line has not been parsed yet,
* or if the parameter was omitted and has no default value.
*/
get value() {
return this._value;
}
/** {@inheritDoc CommandLineParameter.appendToArgList} @override */
appendToArgList(argList) {
if (this.value !== undefined) {
argList.push(this.longName);
argList.push(this.value.toString());
}
}
}
exports.CommandLineIntegerParameter = CommandLineIntegerParameter;
//# sourceMappingURL=CommandLineIntegerParameter.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,28 @@
import type { ICommandLineRemainderDefinition } from './CommandLineDefinition';
/**
* The data type returned by {@link CommandLineParameterProvider.defineCommandLineRemainder}.
* @public
*/
export declare class CommandLineRemainder {
private _values;
/** {@inheritDoc IBaseCommandLineDefinition.description} */
readonly description: string;
/** @internal */
constructor(definition: ICommandLineRemainderDefinition);
/**
* Returns any remaining command line arguments after the recognized portion
* that was parsed from the command line.
*
* @remarks
* The array will be empty if the command-line has not been parsed yet.
*/
get values(): ReadonlyArray<string>;
/**
* {@inheritDoc CommandLineParameter._setValue}
* @internal
*/
_setValue(data: unknown): void;
/** {@inheritDoc CommandLineParameter.appendToArgList} @override */
appendToArgList(argList: string[]): void;
}
//# sourceMappingURL=CommandLineRemainder.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"CommandLineRemainder.d.ts","sourceRoot":"","sources":["../../src/parameters/CommandLineRemainder.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,+BAA+B,EAAE,MAAM,yBAAyB,CAAC;AAE/E;;;GAGG;AACH,qBAAa,oBAAoB;IAC/B,OAAO,CAAC,OAAO,CAAgB;IAE/B,2DAA2D;IAC3D,SAAgB,WAAW,EAAE,MAAM,CAAC;IAEpC,gBAAgB;gBACG,UAAU,EAAE,+BAA+B;IAI9D;;;;;;OAMG;IACH,IAAW,MAAM,IAAI,aAAa,CAAC,MAAM,CAAC,CAEzC;IAED;;;OAGG;IACI,SAAS,CAAC,IAAI,EAAE,OAAO,GAAG,IAAI;IASrC,mEAAmE;IAC5D,eAAe,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI;CAOhD"}

View File

@@ -0,0 +1,47 @@
"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.CommandLineRemainder = void 0;
/**
* The data type returned by {@link CommandLineParameterProvider.defineCommandLineRemainder}.
* @public
*/
class CommandLineRemainder {
/** @internal */
constructor(definition) {
this._values = [];
this.description = definition.description;
}
/**
* Returns any remaining command line arguments after the recognized portion
* that was parsed from the command line.
*
* @remarks
* The array will be empty if the command-line has not been parsed yet.
*/
get values() {
return this._values;
}
/**
* {@inheritDoc CommandLineParameter._setValue}
* @internal
*/
_setValue(data) {
// abstract
if (!Array.isArray(data) || !data.every((x) => typeof x === 'string')) {
throw new Error(`Unexpected data object for remainder: ` + JSON.stringify(data));
}
this._values.push(...data);
}
/** {@inheritDoc CommandLineParameter.appendToArgList} @override */
appendToArgList(argList) {
if (this.values.length > 0) {
for (const value of this.values) {
argList.push(value);
}
}
}
}
exports.CommandLineRemainder = CommandLineRemainder;
//# sourceMappingURL=CommandLineRemainder.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"CommandLineRemainder.js","sourceRoot":"","sources":["../../src/parameters/CommandLineRemainder.ts"],"names":[],"mappings":";AAAA,4FAA4F;AAC5F,2DAA2D;;;AAI3D;;;GAGG;AACH,MAAa,oBAAoB;IAM/B,gBAAgB;IAChB,YAAmB,UAA2C;QANtD,YAAO,GAAa,EAAE,CAAC;QAO7B,IAAI,CAAC,WAAW,GAAG,UAAU,CAAC,WAAW,CAAC;IAC5C,CAAC;IAED;;;;;;OAMG;IACH,IAAW,MAAM;QACf,OAAO,IAAI,CAAC,OAAO,CAAC;IACtB,CAAC;IAED;;;OAGG;IACI,SAAS,CAAC,IAAa;QAC5B,WAAW;QACX,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,OAAO,CAAC,KAAK,QAAQ,CAAC,EAAE,CAAC;YACtE,MAAM,IAAI,KAAK,CAAC,wCAAwC,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC;QACnF,CAAC;QAED,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC;IAC7B,CAAC;IAED,mEAAmE;IAC5D,eAAe,CAAC,OAAiB;QACtC,IAAI,IAAI,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YAC3B,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;gBAChC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;YACtB,CAAC;QACH,CAAC;IACH,CAAC;CACF;AA3CD,oDA2CC","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 { ICommandLineRemainderDefinition } from './CommandLineDefinition';\n\n/**\n * The data type returned by {@link CommandLineParameterProvider.defineCommandLineRemainder}.\n * @public\n */\nexport class CommandLineRemainder {\n private _values: string[] = [];\n\n /** {@inheritDoc IBaseCommandLineDefinition.description} */\n public readonly description: string;\n\n /** @internal */\n public constructor(definition: ICommandLineRemainderDefinition) {\n this.description = definition.description;\n }\n\n /**\n * Returns any remaining command line arguments after the recognized portion\n * that was parsed from the command line.\n *\n * @remarks\n * The array will be empty if the command-line has not been parsed yet.\n */\n public get values(): ReadonlyArray<string> {\n return this._values;\n }\n\n /**\n * {@inheritDoc CommandLineParameter._setValue}\n * @internal\n */\n public _setValue(data: unknown): void {\n // abstract\n if (!Array.isArray(data) || !data.every((x) => typeof x === 'string')) {\n throw new Error(`Unexpected data object for remainder: ` + JSON.stringify(data));\n }\n\n this._values.push(...data);\n }\n\n /** {@inheritDoc CommandLineParameter.appendToArgList} @override */\n public appendToArgList(argList: string[]): void {\n if (this.values.length > 0) {\n for (const value of this.values) {\n argList.push(value);\n }\n }\n }\n}\n"]}

View File

@@ -0,0 +1,29 @@
import type { ICommandLineStringListDefinition } from './CommandLineDefinition';
import { CommandLineParameterWithArgument, CommandLineParameterKind } from './BaseClasses';
/**
* The data type returned by {@link CommandLineParameterProvider.defineStringListParameter}.
* @public
*/
export declare class CommandLineStringListParameter extends CommandLineParameterWithArgument {
private _values;
/** {@inheritDoc CommandLineParameter.kind} */
readonly kind: CommandLineParameterKind.StringList;
/** @internal */
constructor(definition: ICommandLineStringListDefinition);
/**
* {@inheritDoc CommandLineParameter._setValue}
* @internal
*/
_setValue(data: unknown): void;
/**
* Returns the string arguments for a string list parameter that was parsed from the command line.
*
* @remarks
* The array will be empty if the command-line has not been parsed yet,
* or if the parameter was omitted and has no default value.
*/
get values(): ReadonlyArray<string>;
/** {@inheritDoc CommandLineParameter.appendToArgList} @override */
appendToArgList(argList: string[]): void;
}
//# sourceMappingURL=CommandLineStringListParameter.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"CommandLineStringListParameter.d.ts","sourceRoot":"","sources":["../../src/parameters/CommandLineStringListParameter.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,gCAAgC,EAAE,MAAM,yBAAyB,CAAC;AAChF,OAAO,EAAE,gCAAgC,EAAE,wBAAwB,EAAE,MAAM,eAAe,CAAC;AAG3F;;;GAGG;AACH,qBAAa,8BAA+B,SAAQ,gCAAgC;IAClF,OAAO,CAAC,OAAO,CAAgB;IAE/B,8CAA8C;IAC9C,SAAgB,IAAI,EAAE,wBAAwB,CAAC,UAAU,CAAuC;IAEhG,gBAAgB;gBACG,UAAU,EAAE,gCAAgC;IAI/D;;;OAGG;IACI,SAAS,CAAC,IAAI,EAAE,OAAO,GAAG,IAAI;IA6BrC;;;;;;OAMG;IACH,IAAW,MAAM,IAAI,aAAa,CAAC,MAAM,CAAC,CAEzC;IAED,mEAAmE;IAC5D,eAAe,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI;CAQhD"}

View File

@@ -0,0 +1,70 @@
"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.CommandLineStringListParameter = void 0;
const BaseClasses_1 = require("./BaseClasses");
const EnvironmentVariableParser_1 = require("./EnvironmentVariableParser");
/**
* The data type returned by {@link CommandLineParameterProvider.defineStringListParameter}.
* @public
*/
class CommandLineStringListParameter extends BaseClasses_1.CommandLineParameterWithArgument {
/** @internal */
constructor(definition) {
super(definition);
this._values = [];
/** {@inheritDoc CommandLineParameter.kind} */
this.kind = BaseClasses_1.CommandLineParameterKind.StringList;
}
/**
* {@inheritDoc CommandLineParameter._setValue}
* @internal
*/
_setValue(data) {
// If argparse passed us a value, confirm it is valid
if (data !== null && data !== undefined) {
if (!Array.isArray(data)) {
this.reportInvalidData(data);
}
for (const arrayItem of data) {
if (typeof arrayItem !== 'string') {
this.reportInvalidData(data);
}
}
this._values = data;
return;
}
// If an environment variable exists, attempt to parse it as a list
if (this.environmentVariable !== undefined) {
const values = EnvironmentVariableParser_1.EnvironmentVariableParser.parseAsList(this.environmentVariable);
if (values) {
this._values = values;
return;
}
}
// (No default value for string lists)
this._values = [];
}
/**
* Returns the string arguments for a string list parameter that was parsed from the command line.
*
* @remarks
* The array will be empty if the command-line has not been parsed yet,
* or if the parameter was omitted and has no default value.
*/
get values() {
return this._values;
}
/** {@inheritDoc CommandLineParameter.appendToArgList} @override */
appendToArgList(argList) {
if (this.values.length > 0) {
for (const value of this.values) {
argList.push(this.longName);
argList.push(value);
}
}
}
}
exports.CommandLineStringListParameter = CommandLineStringListParameter;
//# sourceMappingURL=CommandLineStringListParameter.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"CommandLineStringListParameter.js","sourceRoot":"","sources":["../../src/parameters/CommandLineStringListParameter.ts"],"names":[],"mappings":";AAAA,4FAA4F;AAC5F,2DAA2D;;;AAG3D,+CAA2F;AAC3F,2EAAwE;AAExE;;;GAGG;AACH,MAAa,8BAA+B,SAAQ,8CAAgC;IAMlF,gBAAgB;IAChB,YAAmB,UAA4C;QAC7D,KAAK,CAAC,UAAU,CAAC,CAAC;QAPZ,YAAO,GAAa,EAAE,CAAC;QAE/B,8CAA8C;QAC9B,SAAI,GAAwC,sCAAwB,CAAC,UAAU,CAAC;IAKhG,CAAC;IAED;;;OAGG;IACI,SAAS,CAAC,IAAa;QAC5B,qDAAqD;QACrD,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;YACxC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC;gBACzB,IAAI,CAAC,iBAAiB,CAAC,IAAI,CAAC,CAAC;YAC/B,CAAC;YACD,KAAK,MAAM,SAAS,IAAI,IAAI,EAAE,CAAC;gBAC7B,IAAI,OAAO,SAAS,KAAK,QAAQ,EAAE,CAAC;oBAClC,IAAI,CAAC,iBAAiB,CAAC,IAAI,CAAC,CAAC;gBAC/B,CAAC;YACH,CAAC;YACD,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;YACpB,OAAO;QACT,CAAC;QAED,mEAAmE;QACnE,IAAI,IAAI,CAAC,mBAAmB,KAAK,SAAS,EAAE,CAAC;YAC3C,MAAM,MAAM,GAAyB,qDAAyB,CAAC,WAAW,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAAC;YACrG,IAAI,MAAM,EAAE,CAAC;gBACX,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;gBACtB,OAAO;YACT,CAAC;QACH,CAAC;QAED,sCAAsC;QAEtC,IAAI,CAAC,OAAO,GAAG,EAAE,CAAC;IACpB,CAAC;IAED;;;;;;OAMG;IACH,IAAW,MAAM;QACf,OAAO,IAAI,CAAC,OAAO,CAAC;IACtB,CAAC;IAED,mEAAmE;IAC5D,eAAe,CAAC,OAAiB;QACtC,IAAI,IAAI,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YAC3B,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;gBAChC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;gBAC5B,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;YACtB,CAAC;QACH,CAAC;IACH,CAAC;CACF;AAhED,wEAgEC","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 { ICommandLineStringListDefinition } from './CommandLineDefinition';\nimport { CommandLineParameterWithArgument, CommandLineParameterKind } from './BaseClasses';\nimport { EnvironmentVariableParser } from './EnvironmentVariableParser';\n\n/**\n * The data type returned by {@link CommandLineParameterProvider.defineStringListParameter}.\n * @public\n */\nexport class CommandLineStringListParameter extends CommandLineParameterWithArgument {\n private _values: string[] = [];\n\n /** {@inheritDoc CommandLineParameter.kind} */\n public readonly kind: CommandLineParameterKind.StringList = CommandLineParameterKind.StringList;\n\n /** @internal */\n public constructor(definition: ICommandLineStringListDefinition) {\n super(definition);\n }\n\n /**\n * {@inheritDoc CommandLineParameter._setValue}\n * @internal\n */\n public _setValue(data: unknown): void {\n // If argparse passed us a value, confirm it is valid\n if (data !== null && data !== undefined) {\n if (!Array.isArray(data)) {\n this.reportInvalidData(data);\n }\n for (const arrayItem of data) {\n if (typeof arrayItem !== 'string') {\n this.reportInvalidData(data);\n }\n }\n this._values = data;\n return;\n }\n\n // If an environment variable exists, attempt to parse it as a list\n if (this.environmentVariable !== undefined) {\n const values: string[] | undefined = EnvironmentVariableParser.parseAsList(this.environmentVariable);\n if (values) {\n this._values = values;\n return;\n }\n }\n\n // (No default value for string lists)\n\n this._values = [];\n }\n\n /**\n * Returns the string arguments for a string list parameter that was parsed from the command line.\n *\n * @remarks\n * The array will be empty if the command-line has not been parsed yet,\n * or if the parameter was omitted and has no default value.\n */\n public get values(): ReadonlyArray<string> {\n return this._values;\n }\n\n /** {@inheritDoc CommandLineParameter.appendToArgList} @override */\n public appendToArgList(argList: string[]): void {\n if (this.values.length > 0) {\n for (const value of this.values) {\n argList.push(this.longName);\n argList.push(value);\n }\n }\n }\n}\n"]}

View File

@@ -0,0 +1,43 @@
import type { ICommandLineStringDefinition } from './CommandLineDefinition';
import { CommandLineParameterWithArgument, CommandLineParameterKind } from './BaseClasses';
/**
* The data type returned by {@link CommandLineParameterProvider.(defineStringParameter:2)}.
* @public
*/
export interface IRequiredCommandLineStringParameter extends CommandLineStringParameter {
readonly value: string;
}
/**
* The data type returned by {@link CommandLineParameterProvider.(defineStringParameter:1)}.
* @public
*/
export declare class CommandLineStringParameter extends CommandLineParameterWithArgument {
/** {@inheritDoc ICommandLineStringDefinition.defaultValue} */
readonly defaultValue: string | undefined;
private _value;
/** {@inheritDoc CommandLineParameter.kind} */
readonly kind: CommandLineParameterKind.String;
/** @internal */
constructor(definition: ICommandLineStringDefinition);
/**
* {@inheritDoc CommandLineParameter._setValue}
* @internal
*/
_setValue(data: unknown): void;
/**
* {@inheritDoc CommandLineParameter._getSupplementaryNotes}
* @internal
*/
_getSupplementaryNotes(supplementaryNotes: string[]): void;
/**
* Returns the argument value for a string parameter that was parsed from the command line.
*
* @remarks
* The return value will be undefined if the command-line has not been parsed yet,
* or if the parameter was omitted and has no default value.
*/
get value(): string | undefined;
/** {@inheritDoc CommandLineParameter.appendToArgList} @override */
appendToArgList(argList: string[]): void;
}
//# sourceMappingURL=CommandLineStringParameter.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"CommandLineStringParameter.d.ts","sourceRoot":"","sources":["../../src/parameters/CommandLineStringParameter.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,4BAA4B,EAAE,MAAM,yBAAyB,CAAC;AAC5E,OAAO,EAAE,gCAAgC,EAAE,wBAAwB,EAAE,MAAM,eAAe,CAAC;AAE3F;;;GAGG;AACH,MAAM,WAAW,mCAAoC,SAAQ,0BAA0B;IACrF,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;CACxB;AAED;;;GAGG;AACH,qBAAa,0BAA2B,SAAQ,gCAAgC;IAC9E,8DAA8D;IAC9D,SAAgB,YAAY,EAAE,MAAM,GAAG,SAAS,CAAC;IAEjD,OAAO,CAAC,MAAM,CAAiC;IAE/C,8CAA8C;IAC9C,SAAgB,IAAI,EAAE,wBAAwB,CAAC,MAAM,CAAmC;IAExF,gBAAgB;gBACG,UAAU,EAAE,4BAA4B;IAO3D;;;OAGG;IACI,SAAS,CAAC,IAAI,EAAE,OAAO,GAAG,IAAI;IA6BrC;;;OAGG;IACI,sBAAsB,CAAC,kBAAkB,EAAE,MAAM,EAAE,GAAG,IAAI;IAUjE;;;;;;OAMG;IACH,IAAW,KAAK,IAAI,MAAM,GAAG,SAAS,CAErC;IAED,mEAAmE;IAC5D,eAAe,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI;CAMhD"}

View File

@@ -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.CommandLineStringParameter = void 0;
const BaseClasses_1 = require("./BaseClasses");
/**
* The data type returned by {@link CommandLineParameterProvider.(defineStringParameter:1)}.
* @public
*/
class CommandLineStringParameter extends BaseClasses_1.CommandLineParameterWithArgument {
/** @internal */
constructor(definition) {
super(definition);
this._value = undefined;
/** {@inheritDoc CommandLineParameter.kind} */
this.kind = BaseClasses_1.CommandLineParameterKind.String;
this.defaultValue = definition.defaultValue;
this.validateDefaultValue(!!this.defaultValue);
}
/**
* {@inheritDoc CommandLineParameter._setValue}
* @internal
*/
_setValue(data) {
// abstract
if (data !== null && data !== undefined) {
if (typeof data !== 'string') {
this.reportInvalidData(data);
}
this._value = data;
return;
}
if (this.environmentVariable !== undefined) {
// Try reading the environment variable
const environmentValue = process.env[this.environmentVariable];
if (environmentValue !== undefined) {
// NOTE: If the environment variable is defined as an empty string,
// here we will accept the empty string as our value. (For number/flag we don't do that.)
this._value = environmentValue;
return;
}
}
if (this.defaultValue !== undefined) {
this._value = this.defaultValue;
return;
}
this._value = undefined;
}
/**
* {@inheritDoc CommandLineParameter._getSupplementaryNotes}
* @internal
*/
_getSupplementaryNotes(supplementaryNotes) {
// virtual
super._getSupplementaryNotes(supplementaryNotes);
if (this.defaultValue !== undefined) {
if (this.defaultValue.length < 160) {
supplementaryNotes.push(`The default value is ${JSON.stringify(this.defaultValue)}.`);
}
}
}
/**
* Returns the argument value for a string parameter that was parsed from the command line.
*
* @remarks
* The return value will be undefined if the command-line has not been parsed yet,
* or if the parameter was omitted and has no default value.
*/
get value() {
return this._value;
}
/** {@inheritDoc CommandLineParameter.appendToArgList} @override */
appendToArgList(argList) {
if (this.value !== undefined) {
argList.push(this.longName);
argList.push(this.value);
}
}
}
exports.CommandLineStringParameter = CommandLineStringParameter;
//# sourceMappingURL=CommandLineStringParameter.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,10 @@
/**
* Some parameter types can receive their values from an environment variable instead of
* a command line argument. This class provides some utility methods for parsing environment
* variable values.
* @internal
*/
export declare class EnvironmentVariableParser {
static parseAsList(envVarName: string): string[] | undefined;
}
//# sourceMappingURL=EnvironmentVariableParser.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"EnvironmentVariableParser.d.ts","sourceRoot":"","sources":["../../src/parameters/EnvironmentVariableParser.ts"],"names":[],"mappings":"AAGA;;;;;GAKG;AACH,qBAAa,yBAAyB;WACtB,WAAW,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS;CA2CpE"}

View File

@@ -0,0 +1,51 @@
"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.EnvironmentVariableParser = void 0;
/**
* Some parameter types can receive their values from an environment variable instead of
* a command line argument. This class provides some utility methods for parsing environment
* variable values.
* @internal
*/
class EnvironmentVariableParser {
static parseAsList(envVarName) {
const environmentValue = process.env[envVarName];
if (environmentValue !== undefined) {
// NOTE: If the environment variable is defined as an empty string,
// here we will accept the empty string as our value. (For number/flag we don't do that.)
if (environmentValue.trimLeft()[0] === '[') {
// Specifying multiple items in an environment variable is a somewhat rare case. But environment
// variables are actually a pretty reliable way for a tool to avoid shell escaping problems
// when spawning another tool. For this case, we need a reliable way to pass an array of strings
// that could contain any character. For example, if we simply used ";" as the list delimiter,
// then what to do if a string contains that character? We'd need to design an escaping mechanism.
// Since JSON is simple and standard and can escape every possible string, it's a better option
// than a custom delimiter.
try {
const parsedJson = JSON.parse(environmentValue);
if (!Array.isArray(parsedJson) ||
!parsedJson.every((x) => typeof x === 'string' || typeof x === 'boolean' || typeof x === 'number')) {
throw new Error(`The ${environmentValue} environment variable value must be a JSON ` +
` array containing only strings, numbers, and booleans.`);
}
return parsedJson.map((x) => x.toString());
}
catch (ex) {
throw new Error(`The ${environmentValue} environment variable value looks like a JSON array` +
` but failed to parse: ` +
ex.message);
}
}
else {
// As a shorthand, a single value may be specified without JSON encoding, as long as it does not
// start with the "[" character.
return [environmentValue];
}
}
return undefined;
}
}
exports.EnvironmentVariableParser = EnvironmentVariableParser;
//# sourceMappingURL=EnvironmentVariableParser.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"EnvironmentVariableParser.js","sourceRoot":"","sources":["../../src/parameters/EnvironmentVariableParser.ts"],"names":[],"mappings":";AAAA,4FAA4F;AAC5F,2DAA2D;;;AAE3D;;;;;GAKG;AACH,MAAa,yBAAyB;IAC7B,MAAM,CAAC,WAAW,CAAC,UAAkB;QAC1C,MAAM,gBAAgB,GAAuB,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;QAErE,IAAI,gBAAgB,KAAK,SAAS,EAAE,CAAC;YACnC,mEAAmE;YACnE,0FAA0F;YAE1F,IAAI,gBAAgB,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE,CAAC;gBAC3C,iGAAiG;gBACjG,2FAA2F;gBAC3F,iGAAiG;gBACjG,+FAA+F;gBAC/F,mGAAmG;gBACnG,+FAA+F;gBAC/F,2BAA2B;gBAC3B,IAAI,CAAC;oBACH,MAAM,UAAU,GAAY,IAAI,CAAC,KAAK,CAAC,gBAAgB,CAAC,CAAC;oBACzD,IACE,CAAC,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC;wBAC1B,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,OAAO,CAAC,KAAK,QAAQ,IAAI,OAAO,CAAC,KAAK,SAAS,IAAI,OAAO,CAAC,KAAK,QAAQ,CAAC,EAClG,CAAC;wBACD,MAAM,IAAI,KAAK,CACb,OAAO,gBAAgB,6CAA6C;4BAClE,wDAAwD,CAC3D,CAAC;oBACJ,CAAC;oBACD,OAAO,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAC;gBAC7C,CAAC;gBAAC,OAAO,EAAE,EAAE,CAAC;oBACZ,MAAM,IAAI,KAAK,CACb,OAAO,gBAAgB,qDAAqD;wBAC1E,wBAAwB;wBACvB,EAAY,CAAC,OAAO,CACxB,CAAC;gBACJ,CAAC;YACH,CAAC;iBAAM,CAAC;gBACN,gGAAgG;gBAChG,gCAAgC;gBAChC,OAAO,CAAC,gBAAgB,CAAC,CAAC;YAC5B,CAAC;QACH,CAAC;QAED,OAAO,SAAS,CAAC;IACnB,CAAC;CACF;AA5CD,8DA4CC","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.\n// See LICENSE in the project root for license information.\n\n/**\n * Some parameter types can receive their values from an environment variable instead of\n * a command line argument. This class provides some utility methods for parsing environment\n * variable values.\n * @internal\n */\nexport class EnvironmentVariableParser {\n public static parseAsList(envVarName: string): string[] | undefined {\n const environmentValue: string | undefined = process.env[envVarName];\n\n if (environmentValue !== undefined) {\n // NOTE: If the environment variable is defined as an empty string,\n // here we will accept the empty string as our value. (For number/flag we don't do that.)\n\n if (environmentValue.trimLeft()[0] === '[') {\n // Specifying multiple items in an environment variable is a somewhat rare case. But environment\n // variables are actually a pretty reliable way for a tool to avoid shell escaping problems\n // when spawning another tool. For this case, we need a reliable way to pass an array of strings\n // that could contain any character. For example, if we simply used \";\" as the list delimiter,\n // then what to do if a string contains that character? We'd need to design an escaping mechanism.\n // Since JSON is simple and standard and can escape every possible string, it's a better option\n // than a custom delimiter.\n try {\n const parsedJson: unknown = JSON.parse(environmentValue);\n if (\n !Array.isArray(parsedJson) ||\n !parsedJson.every((x) => typeof x === 'string' || typeof x === 'boolean' || typeof x === 'number')\n ) {\n throw new Error(\n `The ${environmentValue} environment variable value must be a JSON ` +\n ` array containing only strings, numbers, and booleans.`\n );\n }\n return parsedJson.map((x) => x.toString());\n } catch (ex) {\n throw new Error(\n `The ${environmentValue} environment variable value looks like a JSON array` +\n ` but failed to parse: ` +\n (ex as Error).message\n );\n }\n } else {\n // As a shorthand, a single value may be specified without JSON encoding, as long as it does not\n // start with the \"[\" character.\n return [environmentValue];\n }\n }\n\n return undefined;\n }\n}\n"]}

View File

@@ -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

View File

@@ -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"}

View File

@@ -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

File diff suppressed because one or more lines are too long

View File

@@ -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

View File

@@ -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"}

View File

@@ -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

File diff suppressed because one or more lines are too long

View File

@@ -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

File diff suppressed because one or more lines are too long

View File

@@ -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

File diff suppressed because one or more lines are too long

View File

@@ -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

View File

@@ -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,iBAAiB,GAAG,SAAS,CAAC;IAErD,OAAO,CAAC,QAAQ,CAAC,eAAe,CAA0B;IAC1D,OAAO,CAAC,iBAAiB,CAAiC;IAC1D,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAA4B;IACrD,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAsB;IAC/C,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAiC;IAChE,OAAO,CAAC,SAAS,CAAkB;IACnC,OAAO,CAAC,0BAA0B,CAAkB;gBAEjC,OAAO,EAAE,yBAAyB;IAoBrD;;OAEG;IACH,IAAW,OAAO,IAAI,aAAa,CAAC,iBAAiB,CAAC,CAErD;IAED;;OAEG;IACI,SAAS,CAAC,MAAM,EAAE,iBAAiB,GAAG,IAAI;IAajD;;;OAGG;IACI,SAAS,CAAC,UAAU,EAAE,MAAM,GAAG,iBAAiB;IAQvD;;;OAGG;IACI,YAAY,CAAC,UAAU,EAAE,MAAM,GAAG,iBAAiB,GAAG,SAAS;IAItE;;;;;;;;;;;;;;;;OAgBG;IACU,YAAY,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,OAAO,CAAC;IA+C5D;;OAEG;IAEU,OAAO,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,OAAO,CAAC;IAIvD;;;OAGG;IACU,gCAAgC,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAkG7E;;OAEG;IAEU,2BAA2B,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAIxE,gBAAgB;IACT,0BAA0B,CAAC,KAAK,EAAE,+BAA+B,GAAG,IAAI;IAkB/E,OAAO,CAAC,oBAAoB;IAO5B;;;OAGG;IACH,SAAS,CAAC,kBAAkB,IAAI,QAAQ,CAAC,cAAc;IAKvD;;;OAGG;cACa,SAAS,IAAI,OAAO,CAAC,IAAI,CAAC;CAK3C"}

View File

@@ -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

File diff suppressed because one or more lines are too long

View File

@@ -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

View File

@@ -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"}

View File

@@ -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

View File

@@ -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"]}

View File

@@ -0,0 +1,8 @@
import { CommandLineAction } from './CommandLineAction';
/**
* @public
*/
export declare class DynamicCommandLineAction extends CommandLineAction {
protected onExecute(): Promise<void>;
}
//# sourceMappingURL=DynamicCommandLineAction.d.ts.map

View File

@@ -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"}

View File

@@ -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

View File

@@ -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"]}

View File

@@ -0,0 +1,7 @@
import { CommandLineParser } from './CommandLineParser';
/**
* @public
*/
export declare class DynamicCommandLineParser extends CommandLineParser {
}
//# sourceMappingURL=DynamicCommandLineParser.d.ts.map

View File

@@ -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"}

View File

@@ -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

View File

@@ -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"]}

View File

@@ -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

View File

@@ -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"}

View File

@@ -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

File diff suppressed because one or more lines are too long

View File

@@ -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

View File

@@ -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"}

View File

@@ -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

File diff suppressed because one or more lines are too long