@rushstack/ts-command-line 5.1.7 → 5.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (156) hide show
  1. package/CHANGELOG.json +32 -0
  2. package/CHANGELOG.md +15 -1
  3. package/dist/ts-command-line.d.ts +2 -3
  4. package/{lib → lib-commonjs}/providers/CommandLineParser.js +3 -5
  5. package/lib-commonjs/providers/CommandLineParser.js.map +1 -0
  6. package/{lib → lib-dts}/providers/CommandLineParser.d.ts +2 -3
  7. package/lib-dts/providers/CommandLineParser.d.ts.map +1 -0
  8. package/lib-esm/CommandLineHelper.js +19 -0
  9. package/lib-esm/CommandLineHelper.js.map +1 -0
  10. package/lib-esm/Constants.js +16 -0
  11. package/lib-esm/Constants.js.map +1 -0
  12. package/lib-esm/TypeUuidLite.js +28 -0
  13. package/lib-esm/TypeUuidLite.js.map +1 -0
  14. package/lib-esm/escapeSprintf.js +9 -0
  15. package/lib-esm/escapeSprintf.js.map +1 -0
  16. package/lib-esm/index.js +26 -0
  17. package/lib-esm/index.js.map +1 -0
  18. package/lib-esm/parameters/BaseClasses.js +163 -0
  19. package/lib-esm/parameters/BaseClasses.js.map +1 -0
  20. package/lib-esm/parameters/CommandLineChoiceListParameter.js +79 -0
  21. package/lib-esm/parameters/CommandLineChoiceListParameter.js.map +1 -0
  22. package/lib-esm/parameters/CommandLineChoiceParameter.js +90 -0
  23. package/lib-esm/parameters/CommandLineChoiceParameter.js.map +1 -0
  24. package/lib-esm/parameters/CommandLineDefinition.js +4 -0
  25. package/lib-esm/parameters/CommandLineDefinition.js.map +1 -0
  26. package/lib-esm/parameters/CommandLineFlagParameter.js +65 -0
  27. package/lib-esm/parameters/CommandLineFlagParameter.js.map +1 -0
  28. package/lib-esm/parameters/CommandLineIntegerListParameter.js +75 -0
  29. package/lib-esm/parameters/CommandLineIntegerListParameter.js.map +1 -0
  30. package/lib-esm/parameters/CommandLineIntegerParameter.js +79 -0
  31. package/lib-esm/parameters/CommandLineIntegerParameter.js.map +1 -0
  32. package/lib-esm/parameters/CommandLineRemainder.js +43 -0
  33. package/lib-esm/parameters/CommandLineRemainder.js.map +1 -0
  34. package/lib-esm/parameters/CommandLineStringListParameter.js +66 -0
  35. package/lib-esm/parameters/CommandLineStringListParameter.js.map +1 -0
  36. package/lib-esm/parameters/CommandLineStringParameter.js +78 -0
  37. package/lib-esm/parameters/CommandLineStringParameter.js.map +1 -0
  38. package/lib-esm/parameters/EnvironmentVariableParser.js +47 -0
  39. package/lib-esm/parameters/EnvironmentVariableParser.js.map +1 -0
  40. package/lib-esm/providers/AliasCommandLineAction.js +131 -0
  41. package/lib-esm/providers/AliasCommandLineAction.js.map +1 -0
  42. package/lib-esm/providers/CommandLineAction.js +76 -0
  43. package/lib-esm/providers/CommandLineAction.js.map +1 -0
  44. package/lib-esm/providers/CommandLineParameterProvider.js +671 -0
  45. package/lib-esm/providers/CommandLineParameterProvider.js.map +1 -0
  46. package/lib-esm/providers/CommandLineParser.js +262 -0
  47. package/lib-esm/providers/CommandLineParser.js.map +1 -0
  48. package/lib-esm/providers/CommandLineParserExitError.js +27 -0
  49. package/lib-esm/providers/CommandLineParserExitError.js.map +1 -0
  50. package/lib-esm/providers/DynamicCommandLineAction.js +13 -0
  51. package/lib-esm/providers/DynamicCommandLineAction.js.map +1 -0
  52. package/lib-esm/providers/DynamicCommandLineParser.js +9 -0
  53. package/lib-esm/providers/DynamicCommandLineParser.js.map +1 -0
  54. package/lib-esm/providers/ScopedCommandLineAction.js +197 -0
  55. package/lib-esm/providers/ScopedCommandLineAction.js.map +1 -0
  56. package/lib-esm/providers/TabCompletionAction.js +166 -0
  57. package/lib-esm/providers/TabCompletionAction.js.map +1 -0
  58. package/package.json +28 -6
  59. package/lib/providers/CommandLineParser.d.ts.map +0 -1
  60. package/lib/providers/CommandLineParser.js.map +0 -1
  61. /package/{lib → lib-commonjs}/CommandLineHelper.js +0 -0
  62. /package/{lib → lib-commonjs}/CommandLineHelper.js.map +0 -0
  63. /package/{lib → lib-commonjs}/Constants.js +0 -0
  64. /package/{lib → lib-commonjs}/Constants.js.map +0 -0
  65. /package/{lib → lib-commonjs}/TypeUuidLite.js +0 -0
  66. /package/{lib → lib-commonjs}/TypeUuidLite.js.map +0 -0
  67. /package/{lib → lib-commonjs}/escapeSprintf.js +0 -0
  68. /package/{lib → lib-commonjs}/escapeSprintf.js.map +0 -0
  69. /package/{lib → lib-commonjs}/index.js +0 -0
  70. /package/{lib → lib-commonjs}/index.js.map +0 -0
  71. /package/{lib → lib-commonjs}/parameters/BaseClasses.js +0 -0
  72. /package/{lib → lib-commonjs}/parameters/BaseClasses.js.map +0 -0
  73. /package/{lib → lib-commonjs}/parameters/CommandLineChoiceListParameter.js +0 -0
  74. /package/{lib → lib-commonjs}/parameters/CommandLineChoiceListParameter.js.map +0 -0
  75. /package/{lib → lib-commonjs}/parameters/CommandLineChoiceParameter.js +0 -0
  76. /package/{lib → lib-commonjs}/parameters/CommandLineChoiceParameter.js.map +0 -0
  77. /package/{lib → lib-commonjs}/parameters/CommandLineDefinition.js +0 -0
  78. /package/{lib → lib-commonjs}/parameters/CommandLineDefinition.js.map +0 -0
  79. /package/{lib → lib-commonjs}/parameters/CommandLineFlagParameter.js +0 -0
  80. /package/{lib → lib-commonjs}/parameters/CommandLineFlagParameter.js.map +0 -0
  81. /package/{lib → lib-commonjs}/parameters/CommandLineIntegerListParameter.js +0 -0
  82. /package/{lib → lib-commonjs}/parameters/CommandLineIntegerListParameter.js.map +0 -0
  83. /package/{lib → lib-commonjs}/parameters/CommandLineIntegerParameter.js +0 -0
  84. /package/{lib → lib-commonjs}/parameters/CommandLineIntegerParameter.js.map +0 -0
  85. /package/{lib → lib-commonjs}/parameters/CommandLineRemainder.js +0 -0
  86. /package/{lib → lib-commonjs}/parameters/CommandLineRemainder.js.map +0 -0
  87. /package/{lib → lib-commonjs}/parameters/CommandLineStringListParameter.js +0 -0
  88. /package/{lib → lib-commonjs}/parameters/CommandLineStringListParameter.js.map +0 -0
  89. /package/{lib → lib-commonjs}/parameters/CommandLineStringParameter.js +0 -0
  90. /package/{lib → lib-commonjs}/parameters/CommandLineStringParameter.js.map +0 -0
  91. /package/{lib → lib-commonjs}/parameters/EnvironmentVariableParser.js +0 -0
  92. /package/{lib → lib-commonjs}/parameters/EnvironmentVariableParser.js.map +0 -0
  93. /package/{lib → lib-commonjs}/providers/AliasCommandLineAction.js +0 -0
  94. /package/{lib → lib-commonjs}/providers/AliasCommandLineAction.js.map +0 -0
  95. /package/{lib → lib-commonjs}/providers/CommandLineAction.js +0 -0
  96. /package/{lib → lib-commonjs}/providers/CommandLineAction.js.map +0 -0
  97. /package/{lib → lib-commonjs}/providers/CommandLineParameterProvider.js +0 -0
  98. /package/{lib → lib-commonjs}/providers/CommandLineParameterProvider.js.map +0 -0
  99. /package/{lib → lib-commonjs}/providers/CommandLineParserExitError.js +0 -0
  100. /package/{lib → lib-commonjs}/providers/CommandLineParserExitError.js.map +0 -0
  101. /package/{lib → lib-commonjs}/providers/DynamicCommandLineAction.js +0 -0
  102. /package/{lib → lib-commonjs}/providers/DynamicCommandLineAction.js.map +0 -0
  103. /package/{lib → lib-commonjs}/providers/DynamicCommandLineParser.js +0 -0
  104. /package/{lib → lib-commonjs}/providers/DynamicCommandLineParser.js.map +0 -0
  105. /package/{lib → lib-commonjs}/providers/ScopedCommandLineAction.js +0 -0
  106. /package/{lib → lib-commonjs}/providers/ScopedCommandLineAction.js.map +0 -0
  107. /package/{lib → lib-commonjs}/providers/TabCompletionAction.js +0 -0
  108. /package/{lib → lib-commonjs}/providers/TabCompletionAction.js.map +0 -0
  109. /package/{lib → lib-dts}/CommandLineHelper.d.ts +0 -0
  110. /package/{lib → lib-dts}/CommandLineHelper.d.ts.map +0 -0
  111. /package/{lib → lib-dts}/Constants.d.ts +0 -0
  112. /package/{lib → lib-dts}/Constants.d.ts.map +0 -0
  113. /package/{lib → lib-dts}/TypeUuidLite.d.ts +0 -0
  114. /package/{lib → lib-dts}/TypeUuidLite.d.ts.map +0 -0
  115. /package/{lib → lib-dts}/escapeSprintf.d.ts +0 -0
  116. /package/{lib → lib-dts}/escapeSprintf.d.ts.map +0 -0
  117. /package/{lib → lib-dts}/index.d.ts +0 -0
  118. /package/{lib → lib-dts}/index.d.ts.map +0 -0
  119. /package/{lib → lib-dts}/parameters/BaseClasses.d.ts +0 -0
  120. /package/{lib → lib-dts}/parameters/BaseClasses.d.ts.map +0 -0
  121. /package/{lib → lib-dts}/parameters/CommandLineChoiceListParameter.d.ts +0 -0
  122. /package/{lib → lib-dts}/parameters/CommandLineChoiceListParameter.d.ts.map +0 -0
  123. /package/{lib → lib-dts}/parameters/CommandLineChoiceParameter.d.ts +0 -0
  124. /package/{lib → lib-dts}/parameters/CommandLineChoiceParameter.d.ts.map +0 -0
  125. /package/{lib → lib-dts}/parameters/CommandLineDefinition.d.ts +0 -0
  126. /package/{lib → lib-dts}/parameters/CommandLineDefinition.d.ts.map +0 -0
  127. /package/{lib → lib-dts}/parameters/CommandLineFlagParameter.d.ts +0 -0
  128. /package/{lib → lib-dts}/parameters/CommandLineFlagParameter.d.ts.map +0 -0
  129. /package/{lib → lib-dts}/parameters/CommandLineIntegerListParameter.d.ts +0 -0
  130. /package/{lib → lib-dts}/parameters/CommandLineIntegerListParameter.d.ts.map +0 -0
  131. /package/{lib → lib-dts}/parameters/CommandLineIntegerParameter.d.ts +0 -0
  132. /package/{lib → lib-dts}/parameters/CommandLineIntegerParameter.d.ts.map +0 -0
  133. /package/{lib → lib-dts}/parameters/CommandLineRemainder.d.ts +0 -0
  134. /package/{lib → lib-dts}/parameters/CommandLineRemainder.d.ts.map +0 -0
  135. /package/{lib → lib-dts}/parameters/CommandLineStringListParameter.d.ts +0 -0
  136. /package/{lib → lib-dts}/parameters/CommandLineStringListParameter.d.ts.map +0 -0
  137. /package/{lib → lib-dts}/parameters/CommandLineStringParameter.d.ts +0 -0
  138. /package/{lib → lib-dts}/parameters/CommandLineStringParameter.d.ts.map +0 -0
  139. /package/{lib → lib-dts}/parameters/EnvironmentVariableParser.d.ts +0 -0
  140. /package/{lib → lib-dts}/parameters/EnvironmentVariableParser.d.ts.map +0 -0
  141. /package/{lib → lib-dts}/providers/AliasCommandLineAction.d.ts +0 -0
  142. /package/{lib → lib-dts}/providers/AliasCommandLineAction.d.ts.map +0 -0
  143. /package/{lib → lib-dts}/providers/CommandLineAction.d.ts +0 -0
  144. /package/{lib → lib-dts}/providers/CommandLineAction.d.ts.map +0 -0
  145. /package/{lib → lib-dts}/providers/CommandLineParameterProvider.d.ts +0 -0
  146. /package/{lib → lib-dts}/providers/CommandLineParameterProvider.d.ts.map +0 -0
  147. /package/{lib → lib-dts}/providers/CommandLineParserExitError.d.ts +0 -0
  148. /package/{lib → lib-dts}/providers/CommandLineParserExitError.d.ts.map +0 -0
  149. /package/{lib → lib-dts}/providers/DynamicCommandLineAction.d.ts +0 -0
  150. /package/{lib → lib-dts}/providers/DynamicCommandLineAction.d.ts.map +0 -0
  151. /package/{lib → lib-dts}/providers/DynamicCommandLineParser.d.ts +0 -0
  152. /package/{lib → lib-dts}/providers/DynamicCommandLineParser.d.ts.map +0 -0
  153. /package/{lib → lib-dts}/providers/ScopedCommandLineAction.d.ts +0 -0
  154. /package/{lib → lib-dts}/providers/ScopedCommandLineAction.d.ts.map +0 -0
  155. /package/{lib → lib-dts}/providers/TabCompletionAction.d.ts +0 -0
  156. /package/{lib → lib-dts}/providers/TabCompletionAction.d.ts.map +0 -0
@@ -0,0 +1,197 @@
1
+ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
2
+ // See LICENSE in the project root for license information.
3
+ import { SCOPING_PARAMETER_GROUP } from '../Constants';
4
+ import { CommandLineAction } from './CommandLineAction';
5
+ import { CommandLineParser } from './CommandLineParser';
6
+ import { CommandLineParserExitError } from './CommandLineParserExitError';
7
+ /**
8
+ * A CommandLineParser used exclusively to parse the scoped command-line parameters
9
+ * for a ScopedCommandLineAction.
10
+ */
11
+ class InternalScopedCommandLineParser extends CommandLineParser {
12
+ get canExecute() {
13
+ return this._canExecute;
14
+ }
15
+ constructor(options) {
16
+ const { actionOptions, unscopedActionParameters, toolFilename, aliasAction, aliasDocumentation } = options;
17
+ const toolCommand = `${toolFilename} ${actionOptions.actionName}`;
18
+ // When coming from an alias command, we want to show the alias command name in the help text
19
+ const toolCommandForLogging = `${toolFilename} ${aliasAction !== null && aliasAction !== void 0 ? aliasAction : actionOptions.actionName}`;
20
+ const scopingArgs = [];
21
+ for (const parameter of unscopedActionParameters) {
22
+ parameter.appendToArgList(scopingArgs);
23
+ }
24
+ const scope = scopingArgs.join(' ');
25
+ // We can run the parser directly because we are not going to use it for any other actions,
26
+ // so construct a special options object to make the "--help" text more useful.
27
+ const scopedCommandLineParserOptions = {
28
+ // Strip the scoping args if coming from an alias command, since they are not applicable
29
+ // to the alias command itself
30
+ toolFilename: `${toolCommandForLogging}${scope && !aliasAction ? ` ${scope} --` : ''}`,
31
+ toolDescription: aliasDocumentation !== null && aliasDocumentation !== void 0 ? aliasDocumentation : actionOptions.documentation,
32
+ toolEpilog: `For more information on available unscoped parameters, use "${toolCommand} --help"`,
33
+ enableTabCompletionAction: false
34
+ };
35
+ super(scopedCommandLineParserOptions);
36
+ this._canExecute = false;
37
+ this._internalOptions = options;
38
+ this._internalOptions.onDefineScopedParameters(this);
39
+ }
40
+ _registerDefinedParameters(state) {
41
+ // Since we are in a separate parser, we need to register the parameters using the state
42
+ // from the parent parser.
43
+ super._registerDefinedParameters(this._internalOptions.registerDefinedParametersState);
44
+ }
45
+ async onExecuteAsync() {
46
+ // Only set if we made it this far, which may not be the case if an error occurred or
47
+ // if '--help' was specified.
48
+ this._canExecute = true;
49
+ }
50
+ }
51
+ /**
52
+ * Represents a sub-command that is part of the CommandLineParser command-line.
53
+ * Applications should create subclasses of ScopedCommandLineAction corresponding to
54
+ * each action that they want to expose.
55
+ *
56
+ * The action name should be comprised of lower case words separated by hyphens
57
+ * or colons. The name should include an English verb (e.g. "deploy"). Use a
58
+ * hyphen to separate words (e.g. "upload-docs"). A group of related commands
59
+ * can be prefixed with a colon (e.g. "docs:generate", "docs:deploy",
60
+ * "docs:serve", etc).
61
+ *
62
+ * Scoped commands allow for different parameters to be specified for different
63
+ * provided scoping values. For example, the "scoped-action --scope A" command
64
+ * may allow for different scoped arguments to be specified than the "scoped-action
65
+ * --scope B" command.
66
+ *
67
+ * Scoped arguments are specified after the "--" pseudo-argument. For example,
68
+ * "scoped-action --scope A -- --scopedFoo --scopedBar".
69
+ *
70
+ * @public
71
+ */
72
+ export class ScopedCommandLineAction extends CommandLineAction {
73
+ constructor(options) {
74
+ super(options);
75
+ this._options = options;
76
+ this._scopingParameters = [];
77
+ // Consume the remainder of the command-line, which will later be passed the scoped parser.
78
+ // This will also prevent developers from calling this.defineCommandLineRemainder(...) since
79
+ // we will have already defined it.
80
+ this.defineCommandLineRemainder({
81
+ description: 'Scoped parameters. Must be prefixed with "--", ex. "-- --scopedParameter ' +
82
+ 'foo --scopedFlag". For more information on available scoped parameters, use "-- --help".'
83
+ });
84
+ }
85
+ /**
86
+ * {@inheritDoc CommandLineParameterProvider.parameters}
87
+ */
88
+ get parameters() {
89
+ if (this._scopedCommandLineParser) {
90
+ return [...super.parameters, ...this._scopedCommandLineParser.parameters];
91
+ }
92
+ else {
93
+ return super.parameters;
94
+ }
95
+ }
96
+ /**
97
+ * {@inheritdoc CommandLineParameterProvider._processParsedData}
98
+ * @internal
99
+ */
100
+ _processParsedData(parserOptions, data) {
101
+ super._processParsedData(parserOptions, data);
102
+ // This should never happen because the super method should throw if parameters haven't been registered,
103
+ // but guard against this just in-case.
104
+ if (this._subparserState === undefined) {
105
+ throw new Error('Parameters have not been registered');
106
+ }
107
+ this._unscopedParserOptions = parserOptions;
108
+ // Generate the scoped parser using the parent parser information. We can only create this after we
109
+ // have parsed the data, since the parameter values are used during construction.
110
+ this._scopedCommandLineParser = new InternalScopedCommandLineParser({
111
+ ...parserOptions,
112
+ actionOptions: this._options,
113
+ aliasAction: data.aliasAction,
114
+ aliasDocumentation: data.aliasDocumentation,
115
+ unscopedActionParameters: this.parameters,
116
+ registerDefinedParametersState: this._subparserState,
117
+ onDefineScopedParameters: this.onDefineScopedParameters.bind(this)
118
+ });
119
+ }
120
+ /**
121
+ * {@inheritdoc CommandLineAction._executeAsync}
122
+ * @internal
123
+ */
124
+ async _executeAsync() {
125
+ if (!this._unscopedParserOptions || !this._scopedCommandLineParser) {
126
+ throw new Error('The CommandLineAction parameters must be processed before execution.');
127
+ }
128
+ if (!this.remainder) {
129
+ throw new Error('Parameters must be defined before execution.');
130
+ }
131
+ // The '--' argument is required to separate the action parameters from the scoped parameters,
132
+ // so it needs to be trimmed. If remainder values are provided but no '--' is found, then throw.
133
+ const scopedArgs = [];
134
+ if (this.remainder.values.length) {
135
+ if (this.remainder.values[0] !== '--') {
136
+ throw new CommandLineParserExitError(
137
+ // argparse sets exit code 2 for invalid arguments
138
+ 2,
139
+ // model the message off of the built-in "unrecognized arguments" message
140
+ `${this.renderUsageText()}\n${this._unscopedParserOptions.toolFilename} ${this.actionName}: ` +
141
+ `error: Unrecognized arguments: ${this.remainder.values[0]}.\n`);
142
+ }
143
+ for (const scopedArg of this.remainder.values.slice(1)) {
144
+ scopedArgs.push(scopedArg);
145
+ }
146
+ }
147
+ // Call the scoped parser using only the scoped args to handle parsing
148
+ await this._scopedCommandLineParser.executeWithoutErrorHandlingAsync(scopedArgs);
149
+ // Only call execute if the parser reached the execute stage. This may not be true if
150
+ // the parser exited early due to a specified '--help' parameter.
151
+ if (this._scopedCommandLineParser.canExecute) {
152
+ await super._executeAsync();
153
+ }
154
+ return;
155
+ }
156
+ /** @internal */
157
+ _registerDefinedParameters(state) {
158
+ if (!this._scopingParameters.length) {
159
+ throw new Error('No scoping parameters defined. At least one scoping parameter must be defined. ' +
160
+ 'Scoping parameters are defined by setting the parameterGroupName to ' +
161
+ 'ScopedCommandLineAction.ScopingParameterGroupName.');
162
+ }
163
+ super._registerDefinedParameters(state);
164
+ const { parentParameterNames } = state;
165
+ const updatedParentParameterNames = new Set([
166
+ ...parentParameterNames,
167
+ ...this._registeredParameterParserKeysByName.keys()
168
+ ]);
169
+ this._subparserState = {
170
+ ...state,
171
+ parentParameterNames: updatedParentParameterNames
172
+ };
173
+ }
174
+ /**
175
+ * Retrieves the scoped CommandLineParser, which is populated after the ScopedCommandLineAction is executed.
176
+ * @internal
177
+ */
178
+ _getScopedCommandLineParser() {
179
+ if (!this._scopedCommandLineParser) {
180
+ throw new Error('The scoped CommandLineParser is only populated after the action is executed.');
181
+ }
182
+ return this._scopedCommandLineParser;
183
+ }
184
+ /** @internal */
185
+ _defineParameter(parameter) {
186
+ super._defineParameter(parameter);
187
+ if (parameter.parameterGroup === ScopedCommandLineAction.ScopingParameterGroup) {
188
+ this._scopingParameters.push(parameter);
189
+ }
190
+ }
191
+ }
192
+ /**
193
+ * The required group name to apply to all scoping parameters. At least one parameter
194
+ * must be defined with this group name.
195
+ */
196
+ ScopedCommandLineAction.ScopingParameterGroup = SCOPING_PARAMETER_GROUP;
197
+ //# sourceMappingURL=ScopedCommandLineAction.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ScopedCommandLineAction.js","sourceRoot":"","sources":["../../src/providers/ScopedCommandLineAction.ts"],"names":[],"mappings":"AAAA,4FAA4F;AAC5F,2DAA2D;AAE3D,OAAO,EAAE,uBAAuB,EAAE,MAAM,cAAc,CAAC;AACvD,OAAO,EAAE,iBAAiB,EAAkC,MAAM,qBAAqB,CAAC;AACxF,OAAO,EAAE,iBAAiB,EAAkC,MAAM,qBAAqB,CAAC;AACxF,OAAO,EAAE,0BAA0B,EAAE,MAAM,8BAA8B,CAAC;AAiB1E;;;GAGG;AACH,MAAM,+BAAgC,SAAQ,iBAAiB;IAI7D,IAAW,UAAU;QACnB,OAAO,IAAI,CAAC,WAAW,CAAC;IAC1B,CAAC;IAED,YAAmB,OAAgD;QACjE,MAAM,EAAE,aAAa,EAAE,wBAAw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MIT license.\n// See LICENSE in the project root for license information.\n\nimport { SCOPING_PARAMETER_GROUP } from '../Constants';\nimport { CommandLineAction, type ICommandLineActionOptions } from './CommandLineAction';\nimport { CommandLineParser, type ICommandLineParserOptions } from './CommandLineParser';\nimport { CommandLineParserExitError } from './CommandLineParserExitError';\nimport type { CommandLineParameter } from '../parameters/BaseClasses';\nimport type {\n CommandLineParameterProvider,\n ICommandLineParserData,\n IRegisterDefinedParametersState\n} from './CommandLineParameterProvider';\n\ninterface IInternalScopedCommandLineParserOptions extends ICommandLineParserOptions {\n readonly actionOptions: ICommandLineActionOptions;\n readonly unscopedActionParameters: ReadonlyArray<CommandLineParameter>;\n readonly onDefineScopedParameters: (commandLineParameterProvider: CommandLineParameterProvider) => void;\n readonly aliasAction?: string;\n readonly aliasDocumentation?: string;\n readonly registerDefinedParametersState: IRegisterDefinedParametersState;\n}\n\n/**\n * A CommandLineParser used exclusively to parse the scoped command-line parameters\n * for a ScopedCommandLineAction.\n */\nclass InternalScopedCommandLineParser extends CommandLineParser {\n private _canExecute: boolean;\n private readonly _internalOptions: IInternalScopedCommandLineParserOptions;\n\n public get canExecute(): boolean {\n return this._canExecute;\n }\n\n public constructor(options: IInternalScopedCommandLineParserOptions) {\n const { actionOptions, unscopedActionParameters, toolFilename, aliasAction, aliasDocumentation } =\n options;\n\n const toolCommand: string = `${toolFilename} ${actionOptions.actionName}`;\n // When coming from an alias command, we want to show the alias command name in the help text\n const toolCommandForLogging: string = `${toolFilename} ${aliasAction ?? actionOptions.actionName}`;\n const scopingArgs: string[] = [];\n for (const parameter of unscopedActionParameters) {\n parameter.appendToArgList(scopingArgs);\n }\n const scope: string = scopingArgs.join(' ');\n\n // We can run the parser directly because we are not going to use it for any other actions,\n // so construct a special options object to make the \"--help\" text more useful.\n const scopedCommandLineParserOptions: ICommandLineParserOptions = {\n // Strip the scoping args if coming from an alias command, since they are not applicable\n // to the alias command itself\n toolFilename: `${toolCommandForLogging}${scope && !aliasAction ? ` ${scope} --` : ''}`,\n toolDescription: aliasDocumentation ?? actionOptions.documentation,\n toolEpilog: `For more information on available unscoped parameters, use \"${toolCommand} --help\"`,\n enableTabCompletionAction: false\n };\n\n super(scopedCommandLineParserOptions);\n this._canExecute = false;\n this._internalOptions = options;\n this._internalOptions.onDefineScopedParameters(this);\n }\n\n public _registerDefinedParameters(state: IRegisterDefinedParametersState): void {\n // Since we are in a separate parser, we need to register the parameters using the state\n // from the parent parser.\n super._registerDefinedParameters(this._internalOptions.registerDefinedParametersState);\n }\n\n protected override async onExecuteAsync(): Promise<void> {\n // Only set if we made it this far, which may not be the case if an error occurred or\n // if '--help' was specified.\n this._canExecute = true;\n }\n}\n\n/**\n * Represents a sub-command that is part of the CommandLineParser command-line.\n * Applications should create subclasses of ScopedCommandLineAction corresponding to\n * each action that they want to expose.\n *\n * The action name should be comprised of lower case words separated by hyphens\n * or colons. The name should include an English verb (e.g. \"deploy\"). Use a\n * hyphen to separate words (e.g. \"upload-docs\"). A group of related commands\n * can be prefixed with a colon (e.g. \"docs:generate\", \"docs:deploy\",\n * \"docs:serve\", etc).\n *\n * Scoped commands allow for different parameters to be specified for different\n * provided scoping values. For example, the \"scoped-action --scope A\" command\n * may allow for different scoped arguments to be specified than the \"scoped-action\n * --scope B\" command.\n *\n * Scoped arguments are specified after the \"--\" pseudo-argument. For example,\n * \"scoped-action --scope A -- --scopedFoo --scopedBar\".\n *\n * @public\n */\nexport abstract class ScopedCommandLineAction extends CommandLineAction {\n private _options: ICommandLineActionOptions;\n private _scopingParameters: CommandLineParameter[];\n private _unscopedParserOptions: ICommandLineParserOptions | undefined;\n private _scopedCommandLineParser: InternalScopedCommandLineParser | undefined;\n private _subparserState: IRegisterDefinedParametersState | undefined;\n\n /**\n * The required group name to apply to all scoping parameters. At least one parameter\n * must be defined with this group name.\n */\n public static readonly ScopingParameterGroup: typeof SCOPING_PARAMETER_GROUP = SCOPING_PARAMETER_GROUP;\n\n public constructor(options: ICommandLineActionOptions) {\n super(options);\n\n this._options = options;\n this._scopingParameters = [];\n\n // Consume the remainder of the command-line, which will later be passed the scoped parser.\n // This will also prevent developers from calling this.defineCommandLineRemainder(...) since\n // we will have already defined it.\n this.defineCommandLineRemainder({\n description:\n 'Scoped parameters. Must be prefixed with \"--\", ex. \"-- --scopedParameter ' +\n 'foo --scopedFlag\". For more information on available scoped parameters, use \"-- --help\".'\n });\n }\n\n /**\n * {@inheritDoc CommandLineParameterProvider.parameters}\n */\n public get parameters(): ReadonlyArray<CommandLineParameter> {\n if (this._scopedCommandLineParser) {\n return [...super.parameters, ...this._scopedCommandLineParser.parameters];\n } else {\n return super.parameters;\n }\n }\n\n /**\n * {@inheritdoc CommandLineParameterProvider._processParsedData}\n * @internal\n */\n public override _processParsedData(\n parserOptions: ICommandLineParserOptions,\n data: ICommandLineParserData\n ): void {\n super._processParsedData(parserOptions, data);\n\n // This should never happen because the super method should throw if parameters haven't been registered,\n // but guard against this just in-case.\n if (this._subparserState === undefined) {\n throw new Error('Parameters have not been registered');\n }\n\n this._unscopedParserOptions = parserOptions;\n\n // Generate the scoped parser using the parent parser information. We can only create this after we\n // have parsed the data, since the parameter values are used during construction.\n this._scopedCommandLineParser = new InternalScopedCommandLineParser({\n ...parserOptions,\n actionOptions: this._options,\n aliasAction: data.aliasAction,\n aliasDocumentation: data.aliasDocumentation,\n unscopedActionParameters: this.parameters as CommandLineParameter[],\n registerDefinedParametersState: this._subparserState,\n onDefineScopedParameters: this.onDefineScopedParameters.bind(this)\n });\n }\n\n /**\n * {@inheritdoc CommandLineAction._executeAsync}\n * @internal\n */\n public override async _executeAsync(): Promise<void> {\n if (!this._unscopedParserOptions || !this._scopedCommandLineParser) {\n throw new Error('The CommandLineAction parameters must be processed before execution.');\n }\n if (!this.remainder) {\n throw new Error('Parameters must be defined before execution.');\n }\n\n // The '--' argument is required to separate the action parameters from the scoped parameters,\n // so it needs to be trimmed. If remainder values are provided but no '--' is found, then throw.\n const scopedArgs: string[] = [];\n if (this.remainder.values.length) {\n if (this.remainder.values[0] !== '--') {\n throw new CommandLineParserExitError(\n // argparse sets exit code 2 for invalid arguments\n 2,\n // model the message off of the built-in \"unrecognized arguments\" message\n `${this.renderUsageText()}\\n${this._unscopedParserOptions.toolFilename} ${this.actionName}: ` +\n `error: Unrecognized arguments: ${this.remainder.values[0]}.\\n`\n );\n }\n for (const scopedArg of this.remainder.values.slice(1)) {\n scopedArgs.push(scopedArg);\n }\n }\n\n // Call the scoped parser using only the scoped args to handle parsing\n await this._scopedCommandLineParser.executeWithoutErrorHandlingAsync(scopedArgs);\n\n // Only call execute if the parser reached the execute stage. This may not be true if\n // the parser exited early due to a specified '--help' parameter.\n if (this._scopedCommandLineParser.canExecute) {\n await super._executeAsync();\n }\n\n return;\n }\n\n /** @internal */\n public _registerDefinedParameters(state: IRegisterDefinedParametersState): void {\n if (!this._scopingParameters.length) {\n throw new Error(\n 'No scoping parameters defined. At least one scoping parameter must be defined. ' +\n 'Scoping parameters are defined by setting the parameterGroupName to ' +\n 'ScopedCommandLineAction.ScopingParameterGroupName.'\n );\n }\n\n super._registerDefinedParameters(state);\n\n const { parentParameterNames } = state;\n const updatedParentParameterNames: Set<string> = new Set([\n ...parentParameterNames,\n ...this._registeredParameterParserKeysByName.keys()\n ]);\n\n this._subparserState = {\n ...state,\n parentParameterNames: updatedParentParameterNames\n };\n }\n\n /**\n * Retrieves the scoped CommandLineParser, which is populated after the ScopedCommandLineAction is executed.\n * @internal\n */\n protected _getScopedCommandLineParser(): CommandLineParser {\n if (!this._scopedCommandLineParser) {\n throw new Error('The scoped CommandLineParser is only populated after the action is executed.');\n }\n return this._scopedCommandLineParser;\n }\n\n /** @internal */\n protected _defineParameter(parameter: CommandLineParameter): void {\n super._defineParameter(parameter);\n if (parameter.parameterGroup === ScopedCommandLineAction.ScopingParameterGroup) {\n this._scopingParameters.push(parameter);\n }\n }\n\n /**\n * The child class should implement this hook to define its scoped command-line\n * parameters, e.g. by calling scopedParameterProvider.defineFlagParameter(). These\n * parameters will only be available if the action is invoked with a scope.\n *\n * @remarks\n * onDefineScopedParameters is called after the unscoped parameters have been parsed.\n * The values they provide can be used to vary the defined scope parameters.\n */\n protected abstract onDefineScopedParameters(scopedParameterProvider: CommandLineParameterProvider): void;\n\n /**\n * {@inheritDoc CommandLineAction.onExecuteAsync}\n */\n protected abstract onExecuteAsync(): Promise<void>;\n}\n"]}
@@ -0,0 +1,166 @@
1
+ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
2
+ // See LICENSE in the project root for license information.
3
+ import stringArgv from 'string-argv';
4
+ import { CommandLineParameterKind, CommandLineParameterWithArgument } from '../parameters/BaseClasses';
5
+ import { CommandLineChoiceParameter } from '../parameters/CommandLineChoiceParameter';
6
+ import { CommandLineAction } from './CommandLineAction';
7
+ import { CommandLineConstants } from '../Constants';
8
+ const DEFAULT_WORD_TO_AUTOCOMPLETE = '';
9
+ const DEFAULT_POSITION = 0;
10
+ export class TabCompleteAction extends CommandLineAction {
11
+ constructor(actions, globalParameters) {
12
+ super({
13
+ actionName: CommandLineConstants.TabCompletionActionName,
14
+ summary: 'Provides tab completion.',
15
+ documentation: 'Provides tab completion.'
16
+ });
17
+ this._actions = new Map();
18
+ for (const action of actions) {
19
+ const parameterNameToParameterInfoMap = new Map();
20
+ for (const parameter of action.parameters) {
21
+ parameterNameToParameterInfoMap.set(parameter.longName, parameter);
22
+ if (parameter.shortName) {
23
+ parameterNameToParameterInfoMap.set(parameter.shortName, parameter);
24
+ }
25
+ }
26
+ this._actions.set(action.actionName, parameterNameToParameterInfoMap);
27
+ }
28
+ this._globalParameters = new Map();
29
+ for (const parameter of globalParameters) {
30
+ this._globalParameters.set(parameter.longName, parameter);
31
+ if (parameter.shortName) {
32
+ this._globalParameters.set(parameter.shortName, parameter);
33
+ }
34
+ }
35
+ this._wordToCompleteParameter = this.defineStringParameter({
36
+ parameterLongName: '--word',
37
+ argumentName: 'WORD',
38
+ description: `The word to complete.`,
39
+ defaultValue: DEFAULT_WORD_TO_AUTOCOMPLETE
40
+ });
41
+ this._positionParameter = this.defineIntegerParameter({
42
+ parameterLongName: '--position',
43
+ argumentName: 'INDEX',
44
+ description: `The position in the word to be completed.`,
45
+ defaultValue: DEFAULT_POSITION
46
+ });
47
+ }
48
+ async onExecuteAsync() {
49
+ const commandLine = this._wordToCompleteParameter.value;
50
+ const caretPosition = this._positionParameter.value || commandLine.length;
51
+ for await (const value of this.getCompletionsAsync(commandLine, caretPosition)) {
52
+ // eslint-disable-next-line no-console
53
+ console.log(value);
54
+ }
55
+ }
56
+ async *getCompletionsAsync(commandLine, caretPosition = commandLine.length) {
57
+ const actions = this._actions;
58
+ if (!commandLine || !caretPosition) {
59
+ yield* this._getAllActions();
60
+ return;
61
+ }
62
+ const tokens = Array.from(this.tokenizeCommandLine(commandLine));
63
+ // offset arguments by the number of global params in the input
64
+ const globalParameterOffset = this._getGlobalParameterOffset(tokens);
65
+ if (tokens.length < 2 + globalParameterOffset) {
66
+ yield* this._getAllActions();
67
+ return;
68
+ }
69
+ const lastToken = tokens[tokens.length - 1];
70
+ const secondLastToken = tokens[tokens.length - 2];
71
+ const lastCharacterIsWhitespace = !commandLine.slice(-1).trim();
72
+ const completePartialWord = caretPosition === commandLine.length && !lastCharacterIsWhitespace;
73
+ if (completePartialWord && tokens.length === 2 + globalParameterOffset) {
74
+ for (const actionName of actions.keys()) {
75
+ if (actionName.indexOf(tokens[1 + globalParameterOffset]) === 0) {
76
+ yield actionName;
77
+ }
78
+ }
79
+ }
80
+ else {
81
+ for (const actionName of actions.keys()) {
82
+ if (actionName === tokens[1 + globalParameterOffset]) {
83
+ const parameterNameMap = actions.get(actionName);
84
+ const parameterNames = Array.from(parameterNameMap.keys());
85
+ if (completePartialWord) {
86
+ for (const parameterName of parameterNames) {
87
+ if (parameterName === secondLastToken) {
88
+ const values = await this._getParameterValueCompletionsAsync(parameterNameMap.get(parameterName));
89
+ if (values.size > 0) {
90
+ yield* this._completeParameterValues(values, lastToken);
91
+ return;
92
+ }
93
+ }
94
+ }
95
+ yield* this._completeParameterValues(parameterNames, lastToken);
96
+ }
97
+ else {
98
+ for (const parameterName of parameterNames) {
99
+ if (parameterName === lastToken) {
100
+ const values = await this._getParameterValueCompletionsAsync(parameterNameMap.get(parameterName));
101
+ if (values.size > 0) {
102
+ yield* values;
103
+ return;
104
+ }
105
+ }
106
+ }
107
+ for (const parameterName of parameterNames) {
108
+ if (parameterName === lastToken &&
109
+ parameterNameMap.get(parameterName).kind !== CommandLineParameterKind.Flag) {
110
+ // The parameter is expecting a value, so don't suggest parameter names again
111
+ return;
112
+ }
113
+ }
114
+ yield* parameterNames;
115
+ }
116
+ break;
117
+ }
118
+ }
119
+ }
120
+ }
121
+ *_getAllActions() {
122
+ yield* this._actions.keys();
123
+ yield* this._globalParameters.keys();
124
+ }
125
+ tokenizeCommandLine(commandLine) {
126
+ return stringArgv(commandLine);
127
+ }
128
+ async _getParameterValueCompletionsAsync(parameter) {
129
+ var _a;
130
+ let choiceParameterValues;
131
+ if (parameter.kind === CommandLineParameterKind.Choice) {
132
+ choiceParameterValues = parameter.alternatives;
133
+ }
134
+ else if (parameter.kind !== CommandLineParameterKind.Flag) {
135
+ let parameterWithArgumentOrChoices = undefined;
136
+ if (parameter instanceof CommandLineParameterWithArgument ||
137
+ parameter instanceof CommandLineChoiceParameter) {
138
+ parameterWithArgumentOrChoices = parameter;
139
+ }
140
+ const completionValues = await ((_a = parameterWithArgumentOrChoices === null || parameterWithArgumentOrChoices === void 0 ? void 0 : parameterWithArgumentOrChoices.getCompletionsAsync) === null || _a === void 0 ? void 0 : _a.call(parameterWithArgumentOrChoices));
141
+ choiceParameterValues = completionValues instanceof Set ? completionValues : new Set(completionValues);
142
+ }
143
+ return choiceParameterValues !== null && choiceParameterValues !== void 0 ? choiceParameterValues : new Set();
144
+ }
145
+ _getGlobalParameterOffset(tokens) {
146
+ const globalParameters = this._globalParameters;
147
+ let count = 0;
148
+ outer: for (let i = 1; i < tokens.length; i++) {
149
+ for (const globalParameter of globalParameters.values()) {
150
+ if (tokens[i] !== globalParameter.longName && tokens[i] !== globalParameter.shortName) {
151
+ break outer;
152
+ }
153
+ }
154
+ count++;
155
+ }
156
+ return count;
157
+ }
158
+ *_completeParameterValues(choiceParameterValues, lastToken) {
159
+ for (const choiceParameterValue of choiceParameterValues) {
160
+ if (choiceParameterValue.indexOf(lastToken) === 0) {
161
+ yield choiceParameterValue;
162
+ }
163
+ }
164
+ }
165
+ }
166
+ //# sourceMappingURL=TabCompletionAction.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"TabCompletionAction.js","sourceRoot":"","sources":["../../src/providers/TabCompletionAction.ts"],"names":[],"mappings":"AAAA,4FAA4F;AAC5F,2DAA2D;AAE3D,OAAO,UAAU,MAAM,aAAa,CAAC;AAIrC,OAAO,EACL,wBAAwB,EAExB,gCAAgC,EAEjC,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,0BAA0B,EAAE,MAAM,0CAA0C,CAAC;AACtF,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AAEpD,MAAM,4BAA4B,GAAW,EAAE,CAAC;AAChD,MAAM,gBAAgB,GAAW,CAAC,CAAC;AAEnC,MAAM,OAAO,iBAAkB,SAAQ,iBAAiB;IAMtD,YACE,OAAyC,EACzC,gBAAyD;QAEzD,KAAK,CAAC;YACJ,UAAU,EAAE,oBAAoB,CAAC,uBAAuB;YACxD,OAAO,EAAE,0BAA0B;YACnC,aAAa,EAAE,0BAA0B;SAC1C,CAAC,CAAC;QAEH,IAAI,CAAC,QAAQ,GAAG,IAAI,GAAG,EAAE,CAAC;QAC1B,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;YAC7B,MAAM,+BAA+B,GAAsC,IAAI,GAAG,EAAE,CAAC;YACrF,KAAK,MAAM,SAAS,IAAI,MAAM,CAAC,UAAU,EAAE,CAAC;gBAC1C,+BAA+B,CAAC,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CAAE,mBAAmB,8EAAI,CAAA,CAAC;YAChE,qBAAqB,GAAG,gBAAgB,YAAY,GAAG,CAAC,CAAC,CAAC,gBAAgB,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,gBAAgB,CAAC,CAAC;QACzG,CAAC;QAED,OAAO,qBAAqB,aAArB,qBAAqB,cAArB,qBAAqB,GAAI,IAAI,GAAG,EAAE,CAAC;IAC5C,CAAC;IAEO,yBAAyB,CAAC,MAAgB;QAChD,MAAM,gBAAgB,GAAsC,IAAI,CAAC,iBAAiB,CAAC;QACnF,IAAI,KAAK,GAAW,CAAC,CAAC;QAEtB,KAAK,EAAE,KAAK,IAAI,CAAC,GAAW,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;YACtD,KAAK,MAAM,eAAe,IAAI,gBAAgB,CAAC,MAAM,EAAE,EAAE,CAAC;gBACxD,IAAI,MAAM,CAAC,CAAC,CAAC,KAAK,eAAe,CAAC,QAAQ,IAAI,MAAM,CAAC,CAAC,CAAC,KAAK,eAAe,CAAC,SAAS,EAAE,CAAC;oBACtF,MAAM,KAAK,CAAC;gBACd,CAAC;YACH,CAAC;YACD,KAAK,EAAE,CAAC;QACV,CAAC;QAED,OAAO,KAAK,CAAC;IACf,CAAC;IAEO,CAAC,wBAAwB,CAC/B,qBAAkE,EAClE,SAAiB;QAEjB,KAAK,MAAM,oBAAoB,IAAI,qBAAqB,EAAE,CAAC;YACzD,IAAI,oBAAoB,CAAC,OAAO,CAAC,SAAS,CAAC,KAAK,CAAC,EAAE,CAAC;gBAClD,MAAM,oBAAoB,CAAC;YAC7B,CAAC;QACH,CAAC;IACH,CAAC;CACF","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 stringArgv from 'string-argv';\n\nimport type { IRequiredCommandLineIntegerParameter } from '../parameters/CommandLineIntegerParameter';\nimport type { IRequiredCommandLineStringParameter } from '../parameters/CommandLineStringParameter';\nimport {\n CommandLineParameterKind,\n type CommandLineParameterBase,\n CommandLineParameterWithArgument,\n type CommandLineParameter\n} from '../parameters/BaseClasses';\nimport { CommandLineChoiceParameter } from '../parameters/CommandLineChoiceParameter';\nimport { CommandLineAction } from './CommandLineAction';\nimport { CommandLineConstants } from '../Constants';\n\nconst DEFAULT_WORD_TO_AUTOCOMPLETE: string = '';\nconst DEFAULT_POSITION: number = 0;\n\nexport class TabCompleteAction extends CommandLineAction {\n private readonly _wordToCompleteParameter: IRequiredCommandLineStringParameter;\n private readonly _positionParameter: IRequiredCommandLineIntegerParameter;\n private readonly _actions: Map<string, Map<string, CommandLineParameter>>;\n private readonly _globalParameters: Map<string, CommandLineParameter>;\n\n public constructor(\n actions: ReadonlyArray<CommandLineAction>,\n globalParameters: ReadonlyArray<CommandLineParameterBase>\n ) {\n super({\n actionName: CommandLineConstants.TabCompletionActionName,\n summary: 'Provides tab completion.',\n documentation: 'Provides tab completion.'\n });\n\n this._actions = new Map();\n for (const action of actions) {\n const parameterNameToParameterInfoMap: Map<string, CommandLineParameter> = new Map();\n for (const parameter of action.parameters) {\n parameterNameToParameterInfoMap.set(parameter.longName, parameter as CommandLineParameter);\n if (parameter.shortName) {\n parameterNameToParameterInfoMap.set(parameter.shortName, parameter as CommandLineParameter);\n }\n }\n this._actions.set(action.actionName, parameterNameToParameterInfoMap);\n }\n\n this._globalParameters = new Map<string, CommandLineParameter>();\n for (const parameter of globalParameters) {\n this._globalParameters.set(parameter.longName, parameter as CommandLineParameter);\n if (parameter.shortName) {\n this._globalParameters.set(parameter.shortName, parameter as CommandLineParameter);\n }\n }\n\n this._wordToCompleteParameter = this.defineStringParameter({\n parameterLongName: '--word',\n argumentName: 'WORD',\n description: `The word to complete.`,\n defaultValue: DEFAULT_WORD_TO_AUTOCOMPLETE\n });\n\n this._positionParameter = this.defineIntegerParameter({\n parameterLongName: '--position',\n argumentName: 'INDEX',\n description: `The position in the word to be completed.`,\n defaultValue: DEFAULT_POSITION\n });\n }\n\n protected override async onExecuteAsync(): Promise<void> {\n const commandLine: string = this._wordToCompleteParameter.value;\n const caretPosition: number = this._positionParameter.value || commandLine.length;\n\n for await (const value of this.getCompletionsAsync(commandLine, caretPosition)) {\n // eslint-disable-next-line no-console\n console.log(value);\n }\n }\n\n public async *getCompletionsAsync(\n commandLine: string,\n caretPosition: number = commandLine.length\n ): AsyncIterable<string> {\n const actions: Map<string, Map<string, CommandLineParameter>> = this._actions;\n\n if (!commandLine || !caretPosition) {\n yield* this._getAllActions();\n return;\n }\n\n const tokens: string[] = Array.from(this.tokenizeCommandLine(commandLine));\n\n // offset arguments by the number of global params in the input\n const globalParameterOffset: number = this._getGlobalParameterOffset(tokens);\n\n if (tokens.length < 2 + globalParameterOffset) {\n yield* this._getAllActions();\n return;\n }\n\n const lastToken: string = tokens[tokens.length - 1];\n const secondLastToken: string = tokens[tokens.length - 2];\n\n const lastCharacterIsWhitespace: boolean = !commandLine.slice(-1).trim();\n const completePartialWord: boolean = caretPosition === commandLine.length && !lastCharacterIsWhitespace;\n\n if (completePartialWord && tokens.length === 2 + globalParameterOffset) {\n for (const actionName of actions.keys()) {\n if (actionName.indexOf(tokens[1 + globalParameterOffset]) === 0) {\n yield actionName;\n }\n }\n } else {\n for (const actionName of actions.keys()) {\n if (actionName === tokens[1 + globalParameterOffset]) {\n const parameterNameMap: Map<string, CommandLineParameter> = actions.get(actionName)!;\n\n const parameterNames: string[] = Array.from(parameterNameMap.keys());\n\n if (completePartialWord) {\n for (const parameterName of parameterNames) {\n if (parameterName === secondLastToken) {\n const values: ReadonlySet<string> = await this._getParameterValueCompletionsAsync(\n parameterNameMap.get(parameterName)!\n );\n if (values.size > 0) {\n yield* this._completeParameterValues(values, lastToken);\n return;\n }\n }\n }\n yield* this._completeParameterValues(parameterNames, lastToken);\n } else {\n for (const parameterName of parameterNames) {\n if (parameterName === lastToken) {\n const values: ReadonlySet<string> = await this._getParameterValueCompletionsAsync(\n parameterNameMap.get(parameterName)!\n );\n if (values.size > 0) {\n yield* values;\n return;\n }\n }\n }\n for (const parameterName of parameterNames) {\n if (\n parameterName === lastToken &&\n parameterNameMap.get(parameterName)!.kind !== CommandLineParameterKind.Flag\n ) {\n // The parameter is expecting a value, so don't suggest parameter names again\n return;\n }\n }\n\n yield* parameterNames;\n }\n\n break;\n }\n }\n }\n }\n\n private *_getAllActions(): IterableIterator<string> {\n yield* this._actions.keys();\n yield* this._globalParameters.keys();\n }\n\n public tokenizeCommandLine(commandLine: string): string[] {\n return stringArgv(commandLine);\n }\n\n private async _getParameterValueCompletionsAsync(\n parameter: CommandLineParameter\n ): Promise<ReadonlySet<string>> {\n let choiceParameterValues: ReadonlySet<string> | undefined;\n if (parameter.kind === CommandLineParameterKind.Choice) {\n choiceParameterValues = parameter.alternatives;\n } else if (parameter.kind !== CommandLineParameterKind.Flag) {\n let parameterWithArgumentOrChoices:\n | CommandLineParameterWithArgument\n | CommandLineChoiceParameter\n | undefined = undefined;\n if (\n parameter instanceof CommandLineParameterWithArgument ||\n parameter instanceof CommandLineChoiceParameter\n ) {\n parameterWithArgumentOrChoices = parameter;\n }\n\n const completionValues: ReadonlyArray<string> | ReadonlySet<string> | undefined =\n await parameterWithArgumentOrChoices?.getCompletionsAsync?.();\n choiceParameterValues = completionValues instanceof Set ? completionValues : new Set(completionValues);\n }\n\n return choiceParameterValues ?? new Set();\n }\n\n private _getGlobalParameterOffset(tokens: string[]): number {\n const globalParameters: Map<string, CommandLineParameter> = this._globalParameters;\n let count: number = 0;\n\n outer: for (let i: number = 1; i < tokens.length; i++) {\n for (const globalParameter of globalParameters.values()) {\n if (tokens[i] !== globalParameter.longName && tokens[i] !== globalParameter.shortName) {\n break outer;\n }\n }\n count++;\n }\n\n return count;\n }\n\n private *_completeParameterValues(\n choiceParameterValues: ReadonlyArray<string> | ReadonlySet<string>,\n lastToken: string\n ): IterableIterator<string> {\n for (const choiceParameterValue of choiceParameterValues) {\n if (choiceParameterValue.indexOf(lastToken) === 0) {\n yield choiceParameterValue;\n }\n }\n }\n}\n"]}
package/package.json CHANGED
@@ -1,27 +1,49 @@
1
1
  {
2
2
  "name": "@rushstack/ts-command-line",
3
- "version": "5.1.7",
3
+ "version": "5.3.0",
4
4
  "description": "An object-oriented command-line parser for TypeScript",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "https://github.com/microsoft/rushstack.git",
8
8
  "directory": "libraries/ts-command-line"
9
9
  },
10
- "main": "lib/index.js",
11
- "typings": "dist/ts-command-line.d.ts",
10
+ "main": "./lib-commonjs/index.js",
11
+ "module": "./lib-esm/index.js",
12
+ "types": "./dist/ts-command-line.d.ts",
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/ts-command-line.d.ts",
16
+ "import": "./lib-esm/index.js",
17
+ "require": "./lib-commonjs/index.js"
18
+ },
19
+ "./lib/*": {
20
+ "types": "./lib-dts/*.d.ts",
21
+ "import": "./lib-esm/*.js",
22
+ "require": "./lib-commonjs/*.js"
23
+ },
24
+ "./package.json": "./package.json"
25
+ },
26
+ "typesVersions": {
27
+ "*": {
28
+ "lib/*": [
29
+ "lib-dts/*"
30
+ ]
31
+ }
32
+ },
12
33
  "license": "MIT",
13
34
  "dependencies": {
14
35
  "@types/argparse": "1.0.38",
15
36
  "argparse": "~1.0.9",
16
37
  "string-argv": "~0.3.1",
17
- "@rushstack/terminal": "0.21.0"
38
+ "@rushstack/terminal": "0.22.0"
18
39
  },
19
40
  "devDependencies": {
20
41
  "@rushstack/heft": "1.1.7",
21
42
  "eslint": "~9.37.0",
22
- "@rushstack/node-core-library": "5.19.1",
23
- "decoupled-local-node-rig": "1.0.0"
43
+ "decoupled-local-node-rig": "1.0.0",
44
+ "@rushstack/node-core-library": "5.20.0"
24
45
  },
46
+ "sideEffects": false,
25
47
  "scripts": {
26
48
  "build": "heft build --clean",
27
49
  "_phase:build": "heft run --only build -- --clean",
@@ -1 +0,0 @@
1
- {"version":3,"file":"CommandLineParser.d.ts","sourceRoot":"","sources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AC;QAEH,MAAM,WAAW,GAAoC;YACnD,GAAG,KAAK;YACR,oBAAoB,EAAE,2BAA2B;SAClD,CAAC;QACF,KAAK,MAAM,MAAM,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;YACnC,MAAM,CAAC,0BAA0B,CAAC,WAAW,CAAC,CAAC;QACjD,CAAC;IACH,CAAC;IAEO,oBAAoB;QAC1B,IAAI,IAAI,CAAC,SAAS,IAAI,IAAI,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YAC9C,+CAA+C;YAC/C,MAAM,IAAI,KAAK,CAAC,oFAAoF,CAAC,CAAC;QACxG,CAAC;IACH,CAAC;IAED;;;OAGG;IACgB,kBAAkB;QACnC,OAAO,IAAI,CAAC,eAAe,CAAC;IAC9B,CAAC;IAED;;;OAGG;IACO,KAAK,CAAC,cAAc;QAC5B,IAAI,IAAI,CAAC,cAAc,EAAE,CAAC;YACxB,MAAM,IAAI,CAAC,cAAc,CAAC,aAAa,EAAE,CAAC;QAC5C,CAAC;IACH,CAAC;CACF;AAjSD,8CAiSC","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.\n// See LICENSE in the project root for license information.\n\nimport type * as argparse from 'argparse';\n\nimport { Colorize } from '@rushstack/terminal';\n\nimport type { CommandLineAction } from './CommandLineAction';\nimport type { AliasCommandLineAction } from './AliasCommandLineAction';\nimport {\n CommandLineParameterProvider,\n type IRegisterDefinedParametersState,\n type ICommandLineParserData\n} from './CommandLineParameterProvider';\nimport { CommandLineParserExitError, CustomArgumentParser } from './CommandLineParserExitError';\nimport { TabCompleteAction } from './TabCompletionAction';\nimport { TypeUuid, uuidAlreadyReportedError } from '../TypeUuidLite';\nimport { escapeSprintf } from '../escapeSprintf';\n\n/**\n * Options for the {@link CommandLineParser} constructor.\n * @public\n */\nexport interface ICommandLineParserOptions {\n /**\n * The name of your tool when invoked from the command line\n */\n toolFilename: string;\n\n /**\n * General documentation that is included in the \"--help\" main page\n */\n toolDescription: string;\n\n /**\n * An optional string to append at the end of the \"--help\" main page. If not provided, an epilog\n * will be automatically generated based on the toolFilename.\n */\n toolEpilog?: string;\n\n /**\n * Set to true to auto-define a tab completion action. False by default.\n */\n enableTabCompletionAction?: boolean;\n}\n\n/**\n * The \"argparse\" library is a relatively advanced command-line parser with features such\n * as word-wrapping and intelligible error messages (that are lacking in other similar\n * libraries such as commander, yargs, and nomnom). Unfortunately, its ruby-inspired API\n * is awkward to use. The abstract base classes CommandLineParser and CommandLineAction\n * provide a wrapper for \"argparse\" that makes defining and consuming arguments quick\n * and simple, and enforces that appropriate documentation is provided for each parameter.\n *\n * @public\n */\nexport abstract class CommandLineParser extends CommandLineParameterProvider {\n /**\n * Reports which CommandLineAction was specified on the command line.\n * @remarks\n * The value will be assigned before onExecute() is invoked.\n */\n public selectedAction: CommandLineAction | undefined;\n\n private readonly _argumentParser: argparse.ArgumentParser;\n private _actionsSubParser: argparse.SubParser | undefined;\n private readonly _options: ICommandLineParserOptions;\n private readonly _actions: CommandLineAction[];\n private readonly _actionsByName: Map<string, CommandLineAction>;\n private _executed: boolean = false;\n private _tabCompleteActionWasAdded: boolean = false;\n\n public constructor(options: ICommandLineParserOptions) {\n super();\n\n this._options = options;\n this._actions = [];\n this._actionsByName = new Map<string, CommandLineAction>();\n\n const { toolFilename, toolDescription, toolEpilog } = options;\n\n this._argumentParser = new CustomArgumentParser({\n addHelp: true,\n prog: toolFilename,\n description: escapeSprintf(toolDescription),\n epilog: Colorize.bold(\n escapeSprintf(\n toolEpilog ?? `For detailed help about a specific command, use: ${toolFilename} <command> -h`\n )\n )\n });\n }\n\n /**\n * Returns the list of actions that were defined for this CommandLineParser object.\n */\n public get actions(): ReadonlyArray<CommandLineAction> {\n return this._actions;\n }\n\n /**\n * Defines a new action that can be used with the CommandLineParser instance.\n */\n public addAction(action: CommandLineAction): void {\n if (!this._actionsSubParser) {\n this._actionsSubParser = this._argumentParser.addSubparsers({\n metavar: '<command>',\n dest: 'action'\n });\n }\n\n action._buildParser(this._actionsSubParser);\n this._actions.push(action);\n this._actionsByName.set(action.actionName, action);\n }\n\n /**\n * Retrieves the action with the specified name. If no matching action is found,\n * an exception is thrown.\n */\n public getAction(actionName: string): CommandLineAction {\n const action: CommandLineAction | undefined = this.tryGetAction(actionName);\n if (!action) {\n throw new Error(`The action \"${actionName}\" was not defined`);\n }\n return action;\n }\n\n /**\n * Retrieves the action with the specified name. If no matching action is found,\n * undefined is returned.\n */\n public tryGetAction(actionName: string): CommandLineAction | undefined {\n return this._actionsByName.get(actionName);\n }\n\n /**\n * The program entry point will call this method to begin parsing command-line arguments\n * and executing the corresponding action.\n *\n * @remarks\n * The returned promise will never reject: If an error occurs, it will be printed\n * to stderr, process.exitCode will be set to 1, and the promise will resolve to false.\n * This simplifies the most common usage scenario where the program entry point doesn't\n * want to be involved with the command-line logic, and will discard the promise without\n * a then() or catch() block.\n *\n * If your caller wants to trap and handle errors, use {@link CommandLineParser.executeWithoutErrorHandlingAsync}\n * instead.\n *\n * @param args - the command-line arguments to be parsed; if omitted, then\n * the process.argv will be used\n */\n public async executeAsync(args?: string[]): Promise<boolean> {\n if (this._options.enableTabCompletionAction && !this._tabCompleteActionWasAdded) {\n this.addAction(new TabCompleteAction(this.actions, this.parameters));\n this._tabCompleteActionWasAdded = true;\n }\n\n try {\n await this.executeWithoutErrorHandlingAsync(args);\n return true;\n } catch (err) {\n if (err instanceof CommandLineParserExitError) {\n // executeWithoutErrorHandlingAsync() handles the successful cases,\n // so here we can assume err has a nonzero exit code\n if (err.message) {\n // eslint-disable-next-line no-console\n console.error(err.message);\n }\n if (!process.exitCode) {\n process.exitCode = err.exitCode;\n }\n } else if (TypeUuid.isInstanceOf(err, uuidAlreadyReportedError)) {\n // AlreadyReportedError\n if (!process.exitCode) {\n process.exitCode = 1;\n }\n } else {\n let message: string = ((err as Error).message || 'An unknown error occurred').trim();\n\n // If the message doesn't already start with \"Error:\" then add a prefix\n if (!/^(error|internal error|warning)\\b/i.test(message)) {\n message = 'Error: ' + message;\n }\n\n // eslint-disable-next-line no-console\n console.error();\n // eslint-disable-next-line no-console\n console.error(Colorize.red(message));\n\n if (!process.exitCode) {\n process.exitCode = 1;\n }\n }\n\n return false;\n }\n }\n\n /**\n * This is similar to {@link CommandLineParser.executeAsync}, except that execution errors\n * simply cause the promise to reject. It is the caller's responsibility to trap\n */\n public async executeWithoutErrorHandlingAsync(args?: string[]): Promise<void> {\n try {\n if (this._executed) {\n // In the future we could allow the same parser to be invoked multiple times\n // with different arguments. We'll do that work as soon as someone encounters\n // a real world need for it.\n throw new Error('executeAsync() was already called for this parser instance');\n }\n this._executed = true;\n\n this._validateDefinitions();\n\n // Register the parameters before we print help or parse the CLI\n const initialState: IRegisterDefinedParametersState = {\n parentParameterNames: new Set()\n };\n this._registerDefinedParameters(initialState);\n\n if (!args) {\n // 0=node.exe, 1=script name\n args = process.argv.slice(2);\n }\n if (this.actions.length > 0) {\n if (args.length === 0) {\n // Parsers that use actions should print help when 0 args are provided. Allow\n // actionless parsers to continue on zero args.\n this._argumentParser.printHelp();\n return;\n }\n // Alias actions may provide a list of default params to add after the action name.\n // Since we don't know which params are required and which are optional, perform a\n // manual search for the action name to obtain the default params and insert them if\n // any are found. We will guess that the action name is the first arg that doesn't\n // start with a hyphen.\n const actionNameIndex: number | undefined = args.findIndex((x) => !x.startsWith('-'));\n if (actionNameIndex !== undefined) {\n const actionName: string = args[actionNameIndex];\n const action: CommandLineAction | undefined = this.tryGetAction(actionName);\n const aliasAction: AliasCommandLineAction | undefined = action as AliasCommandLineAction;\n if (aliasAction?.defaultParameters?.length) {\n const insertIndex: number = actionNameIndex + 1;\n args = args.slice(0, insertIndex).concat(aliasAction.defaultParameters, args.slice(insertIndex));\n }\n }\n }\n\n const postParse: () => void = () => {\n this._postParse();\n for (const action of this.actions) {\n action._postParse();\n }\n };\n\n function patchFormatUsageForArgumentParser(argumentParser: argparse.ArgumentParser): void {\n const originalFormatUsage: () => string = argumentParser.formatUsage.bind(argumentParser);\n argumentParser.formatUsage = () => {\n postParse();\n return originalFormatUsage();\n };\n }\n\n this._preParse();\n patchFormatUsageForArgumentParser(this._argumentParser);\n for (const action of this.actions) {\n action._preParse();\n patchFormatUsageForArgumentParser(action._getArgumentParser());\n }\n\n const data: ICommandLineParserData = this._argumentParser.parseArgs(args);\n\n postParse();\n this._processParsedData(this._options, data);\n\n this.selectedAction = this.tryGetAction(data.action);\n if (this.actions.length > 0 && !this.selectedAction) {\n const actions: string[] = this.actions.map((x) => x.actionName);\n throw new Error(`An action must be specified (${actions.join(', ')})`);\n }\n\n this.selectedAction?._processParsedData(this._options, data);\n await this.onExecuteAsync();\n } catch (err) {\n if (err instanceof CommandLineParserExitError) {\n if (!err.exitCode) {\n // non-error exit modeled using exception handling\n if (err.message) {\n // eslint-disable-next-line no-console\n console.log(err.message);\n }\n\n return;\n }\n }\n\n throw err;\n }\n }\n\n /** @internal */\n public _registerDefinedParameters(state: IRegisterDefinedParametersState): void {\n super._registerDefinedParameters(state);\n\n const { parentParameterNames } = state;\n const updatedParentParameterNames: Set<string> = new Set([\n ...parentParameterNames,\n ...this._registeredParameterParserKeysByName.keys()\n ]);\n\n const parentState: IRegisterDefinedParametersState = {\n ...state,\n parentParameterNames: updatedParentParameterNames\n };\n for (const action of this._actions) {\n action._registerDefinedParameters(parentState);\n }\n }\n\n private _validateDefinitions(): void {\n if (this.remainder && this.actions.length > 0) {\n // This is apparently not supported by argparse\n throw new Error('defineCommandLineRemainder() cannot be called for a CommandLineParser with actions');\n }\n }\n\n /**\n * {@inheritDoc CommandLineParameterProvider._getArgumentParser}\n * @internal\n */\n protected override _getArgumentParser(): argparse.ArgumentParser {\n return this._argumentParser;\n }\n\n /**\n * This hook allows the subclass to perform additional operations before or after\n * the chosen action is executed.\n */\n protected async onExecuteAsync(): Promise<void> {\n if (this.selectedAction) {\n await this.selectedAction._executeAsync();\n }\n }\n}\n"]}
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes