@rushstack/ts-command-line 4.17.0 → 4.17.2

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 (31) hide show
  1. package/LICENSE +23 -23
  2. package/README.md +251 -251
  3. package/dist/tsdoc-metadata.json +1 -1
  4. package/lib/CommandLineHelper.js.map +1 -1
  5. package/lib/Constants.js.map +1 -1
  6. package/lib/index.js.map +1 -1
  7. package/lib/parameters/BaseClasses.js +2 -2
  8. package/lib/parameters/BaseClasses.js.map +1 -1
  9. package/lib/parameters/CommandLineChoiceListParameter.js.map +1 -1
  10. package/lib/parameters/CommandLineChoiceParameter.js.map +1 -1
  11. package/lib/parameters/CommandLineDefinition.js.map +1 -1
  12. package/lib/parameters/CommandLineFlagParameter.js.map +1 -1
  13. package/lib/parameters/CommandLineIntegerListParameter.js.map +1 -1
  14. package/lib/parameters/CommandLineIntegerParameter.js.map +1 -1
  15. package/lib/parameters/CommandLineRemainder.js.map +1 -1
  16. package/lib/parameters/CommandLineStringListParameter.js.map +1 -1
  17. package/lib/parameters/CommandLineStringParameter.js.map +1 -1
  18. package/lib/parameters/EnvironmentVariableParser.js.map +1 -1
  19. package/lib/providers/AliasCommandLineAction.js.map +1 -1
  20. package/lib/providers/CommandLineAction.js.map +1 -1
  21. package/lib/providers/CommandLineParameterProvider.js +1 -1
  22. package/lib/providers/CommandLineParameterProvider.js.map +1 -1
  23. package/lib/providers/CommandLineParser.js.map +1 -1
  24. package/lib/providers/CommandLineParserExitError.js.map +1 -1
  25. package/lib/providers/DynamicCommandLineAction.js.map +1 -1
  26. package/lib/providers/DynamicCommandLineParser.js.map +1 -1
  27. package/lib/providers/ScopedCommandLineAction.js +1 -1
  28. package/lib/providers/ScopedCommandLineAction.js.map +1 -1
  29. package/lib/providers/TabCompletionAction.js +7 -11
  30. package/lib/providers/TabCompletionAction.js.map +1 -1
  31. package/package.json +3 -3
package/LICENSE CHANGED
@@ -1,24 +1,24 @@
1
- @rushstack/ts-command-line
2
-
3
- Copyright (c) Microsoft Corporation. All rights reserved.
4
-
5
- MIT License
6
-
7
- Permission is hereby granted, free of charge, to any person obtaining
8
- a copy of this software and associated documentation files (the
9
- "Software"), to deal in the Software without restriction, including
10
- without limitation the rights to use, copy, modify, merge, publish,
11
- distribute, sublicense, and/or sell copies of the Software, and to
12
- permit persons to whom the Software is furnished to do so, subject to
13
- the following conditions:
14
-
15
- The above copyright notice and this permission notice shall be
16
- included in all copies or substantial portions of the Software.
17
-
18
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
22
- LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
23
- OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
1
+ @rushstack/ts-command-line
2
+
3
+ Copyright (c) Microsoft Corporation. All rights reserved.
4
+
5
+ MIT License
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining
8
+ a copy of this software and associated documentation files (the
9
+ "Software"), to deal in the Software without restriction, including
10
+ without limitation the rights to use, copy, modify, merge, publish,
11
+ distribute, sublicense, and/or sell copies of the Software, and to
12
+ permit persons to whom the Software is furnished to do so, subject to
13
+ the following conditions:
14
+
15
+ The above copyright notice and this permission notice shall be
16
+ included in all copies or substantial portions of the Software.
17
+
18
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
22
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
23
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
24
24
  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,251 +1,251 @@
1
- # ts-command-line
2
-
3
- This library helps you create professional command-line tools using TypeScript. By "professional", we mean:
4
-
5
- - **no gotchas for users**: Seems obvious, but try typing "`npm install --save-dex`" instead of "`npm install --save-dev`" sometime. The command seems to execute successfully, but it doesn't save anything! The misspelled flag was silently ignored. This lack of rigor plagues many familiar Node.js tools and can be confusing and frustrating. For a great user experience, a command line tool should always be strict about its syntax.
6
-
7
- - **no gotchas for developers**: Many command-line libraries store their parsed data in a simple JavaScript object. This is convenient for small projects. But suppose a large project has many different source files that define and read parameters. If you try to read `data['output-dir']` when it wasn't defined, or if you misspell the key name, your tool will silently behave as if the parameter was omitted. And is `data['max-count']` a string or a number? Hard to tell! We solve this by modeling each parameter kind as a real TypeScript class.
8
-
9
- - **simple by design**: Making a CLI is similar to making a graphical UI -- some people have a knack for clean and intuitive designs, but your average developer... needs some help. :-) Keeping things simple is the best help. **ts-command-line** intentionally provides a minimalist set of CLI building blocks that encourage simple designs. If your app has lots of knobs and switches, we recommend NOT to design a complex CLI with hundreds of parameters. Move those options into a commented config file with a published JSON schema.
10
-
11
- - **automatic documentation**: Some command-line libraries treat the `--help` docs as someone else's job. **ts-command-line** requires each every parameter to follow a standardized naming pattern and have a documentation string. It will automatically generate the `--help` docs for you. If you like to write long paragraphs, no problem -- they will be word-wrapped correctly. *[golf clap]*
12
-
13
- - **structure and extensibility**: Instead of a simple function chain, **ts-command-line** provides a "scaffold" pattern that makes it easy to find and understand the command-line implementation for any tool project. The scaffold model is generally recommended, but there's also a "dynamic" model if you need it. See below for examples.
14
-
15
- - **environment variable mappings**: Any CLI parameter can be associated with an environment variable. If the parameter is not explicitly provided, the value from the environment will be used. The associated environment variables are automatically documented in the `--help`.
16
-
17
- Internally, the implementation is based on [argparse](https://www.npmjs.com/package/argparse) and the Python approach to command-lines.
18
-
19
- Compared to other libraries, **ts-command-line** doesn't provide zillions of custom syntaxes and bells and whistles. Instead it aims to be a simple, consistent, and professional solution for your command-line tool. Give it a try!
20
-
21
- ### Some Terminology
22
-
23
- Suppose that we want to parse a command-line like this:
24
-
25
- ```
26
- widget --verbose push --force --max-count 123
27
- ```
28
-
29
- In this example, we can identify the following components:
30
-
31
- - The **tool name** in this example is `widget`. This is the name of your Node.js bin script.
32
- - The **parameters** are `--verbose`, `--force`, and `--max-count`.
33
- - The value "123" is the **argument** for the `--max-count` integer parameter. (Flags don't have arguments, because their value is determined by whether the flag was provided or not.)
34
- - Similar to Git's command-line, the `push` token is called an **action**. It acts as sub-command with its own unique set of parameters.
35
- - The `--verbose` flag is a **global parameter** because it precedes the action name. It affects all actions.
36
- - The `--force` flag is an **action parameter** because it comes after the action name. It only applies to that action.
37
-
38
-
39
- ### Parameter Kinds
40
-
41
- Several different kinds of parameters are supported:
42
-
43
- | Parameter Kind | Example | Data Type | Description |
44
- | --- | --- | --- | --- |
45
- | flag | `--verbose` | `boolean` | Value is `true` if the flag was specified on the command line, `false` otherwise. |
46
- | integer | `--max-retry 3` | `int` | The argument is an integer number |
47
- | string | `--title "Hello, world"` | `string` | The argument is a text string. |
48
- | choice | `--color red` | `string` | The argument is must be a string from a list of allowed choices (similar to an enum). |
49
- | string list | `-o file1.txt -o file2.txt` | `string[]` | The argument is a text string. The parameter can be specified multiple times to build a list. |
50
-
51
- Other parameter kinds could be implemented if requested. That said, keeping your CLI grammar simple and systematic makes it easier for users to learn.
52
-
53
-
54
- ## Scaffold Model
55
-
56
- If your tool uses the scaffold model, you will create subclasses of two abstract base classes: `CommandLineParser` for the overall command-line, and `CommandLineAction` for each action.
57
-
58
- Continuing our example from above, suppose we want to start with a couple simple flags like this:
59
-
60
- ```
61
- widget --verbose push --force
62
- ```
63
-
64
- We could define our subclass for the "`push`" action like this:
65
-
66
- ```typescript
67
- export class PushAction extends CommandLineAction {
68
- private _force: CommandLineFlagParameter;
69
- private _protocol: CommandLineChoiceParameter;
70
-
71
- public constructor() {
72
- super({
73
- actionName: 'push',
74
- summary: 'Pushes a widget to the service',
75
- documentation: 'Here we provide a longer description of how our action works.'
76
- });
77
- }
78
-
79
- protected onExecute(): Promise<void> { // abstract
80
- return BusinessLogic.doTheWork(this._force.value, this._protocol.value || "(none)");
81
- }
82
-
83
- protected onDefineParameters(): void { // abstract
84
- this._force = this.defineFlagParameter({
85
- parameterLongName: '--force',
86
- parameterShortName: '-f',
87
- description: 'Push and overwrite any existing state'
88
- });
89
-
90
- this._protocol = this.defineChoiceParameter({
91
- parameterLongName: '--protocol',
92
- description: 'Specify the protocol to use',
93
- alternatives: ['ftp', 'webdav', 'scp'],
94
- environmentVariable: 'WIDGET_PROTOCOL',
95
- defaultValue: 'scp'
96
- });
97
- }
98
- }
99
- ```
100
-
101
- Then we might define the parser subclass like this:
102
-
103
- ```typescript
104
- export class WidgetCommandLine extends CommandLineParser {
105
- private _verbose: CommandLineFlagParameter;
106
-
107
- public constructor() {
108
- super({
109
- toolFilename: 'widget',
110
- toolDescription: 'The "widget" tool is a code sample for using the @rushstack/ts-command-line library.'
111
- });
112
-
113
- this.addAction(new PushAction());
114
- }
115
-
116
- protected onDefineParameters(): void { // abstract
117
- this._verbose = this.defineFlagParameter({
118
- parameterLongName: '--verbose',
119
- parameterShortName: '-v',
120
- description: 'Show extra logging detail'
121
- });
122
- }
123
-
124
- protected onExecute(): Promise<void> { // override
125
- BusinessLogic.configureLogger(this._verbose.value);
126
- return super.onExecute();
127
- }
128
- }
129
- ```
130
-
131
- To invoke the parser, the application entry point will do something like this:
132
-
133
- ```typescript
134
- const commandLine: WidgetCommandLine = new WidgetCommandLine();
135
- commandLine.execute();
136
- ```
137
-
138
- When we run `widget --verbose push --force`, the `PushAction.onExecute()` method will get invoked and then your business logic takes over.
139
-
140
- ---
141
-
142
- **For a more complete example, take a look at the [ts-command-line-test](https://github.com/microsoft/rushstack/tree/main/build-tests/ts-command-line-test) sample project.**
143
-
144
- ---
145
-
146
- #### Testing out the docs
147
-
148
- If you invoke the tool as "`widget --help`", the docs are automatically generated:
149
-
150
- ```
151
- usage: widget [-h] [-v] <command> ...
152
-
153
- The "widget" tool is a code sample for using the @rushstack/ts-command-line
154
- library.
155
-
156
- Positional arguments:
157
- <command>
158
- push Pushes a widget to the service
159
-
160
- Optional arguments:
161
- -h, --help Show this help message and exit.
162
- -v, --verbose Show extra logging detail
163
-
164
- For detailed help about a specific command, use: widget <command> -h
165
- ```
166
-
167
- For help about the `push` action, the user can type "`widget push --help`", which shows this output:
168
-
169
- ```
170
- usage: widget push [-h] [-f] [--protocol {ftp,webdav,scp}]
171
-
172
- Here we provide a longer description of how our action works.
173
-
174
- Optional arguments:
175
- -h, --help Show this help message and exit.
176
- -f, --force Push and overwrite any existing state
177
- --protocol {ftp,webdav,scp}
178
- Specify the protocol to use. This parameter may
179
- alternatively specified via the WIDGET_PROTOCOL
180
- environment variable. The default value is "scp".
181
- ```
182
-
183
- ## Dynamic Model
184
-
185
- The action subclasses provide a simple, recognizable pattern that you can use across all your tooling projects. It's the generally recommended approach. However, there are some cases where we need to break out of the scaffold. For example:
186
-
187
- - Actions or parameters may be discovered at runtime, e.g. from a config file
188
- - The actions and their implementations may sometimes have very different structures
189
-
190
- In this case, you can use the `DynamicCommandLineAction` and `DynamicCommandLineParser` classes which are not abstract (and not intended to be subclassed). Here's our above example rewritten for this model:
191
-
192
- ```typescript
193
- // Define the parser
194
- const commandLineParser: DynamicCommandLineParser = new DynamicCommandLineParser({
195
- toolFilename: 'widget',
196
- toolDescription: 'The "widget" tool is a code sample for using the @rushstack/ts-command-line library.'
197
- });
198
-
199
- commandLineParser.defineFlagParameter({
200
- parameterLongName: '--verbose',
201
- parameterShortName: '-v',
202
- description: 'Show extra logging detail'
203
- });
204
-
205
- // Define the action
206
- const action: DynamicCommandLineAction = new DynamicCommandLineAction({
207
- actionName: 'push',
208
- summary: 'Pushes a widget to the service',
209
- documentation: 'Here we provide a longer description of how our action works.'
210
- });
211
-
212
- commandLineParser.addAction(action);
213
-
214
- action.defineFlagParameter({
215
- parameterLongName: '--force',
216
- parameterShortName: '-f',
217
- description: 'Push and overwrite any existing state'
218
- });
219
-
220
- action.defineChoiceParameter({
221
- parameterLongName: '--protocol',
222
- description: 'Specify the protocol to use',
223
- alternatives: ['ftp', 'webdav', 'scp'],
224
- environmentVariable: 'WIDGET_PROTOCOL',
225
- defaultValue: 'scp'
226
- });
227
-
228
- // Parse the command line
229
- commandLineParser.execute().then(() => {
230
- console.log('The action is: ' + commandLineParser.selectedAction!.actionName);
231
- console.log('The force flag is: ' + action.getFlagParameter('--force').value);
232
- });
233
- ```
234
-
235
- You can also mix the two models. For example, we could augment the `WidgetCommandLine` from the original model by adding `DynamicAction` objects to it.
236
-
237
-
238
- ## Links
239
-
240
- - [CHANGELOG.md](
241
- https://github.com/microsoft/rushstack/blob/main/libraries/ts-command-line/CHANGELOG.md) - Find
242
- out what's new in the latest version
243
- - [API Reference](https://rushstack.io/pages/api/ts-command-line/)
244
-
245
- Here are some real world GitHub projects that illustrate different use cases for **ts-command-line**:
246
-
247
- - [@microsoft/rush](https://www.npmjs.com/package/@microsoft/rush)
248
- - [@microsoft/api-extractor](https://www.npmjs.com/package/@microsoft/api-extractor)
249
- - [@microsoft/api-documenter](https://www.npmjs.com/package/@microsoft/api-documenter)
250
-
251
- `@rushstack/ts-command-line` is part of the [Rush Stack](https://rushstack.io/) family of projects.
1
+ # ts-command-line
2
+
3
+ This library helps you create professional command-line tools using TypeScript. By "professional", we mean:
4
+
5
+ - **no gotchas for users**: Seems obvious, but try typing "`npm install --save-dex`" instead of "`npm install --save-dev`" sometime. The command seems to execute successfully, but it doesn't save anything! The misspelled flag was silently ignored. This lack of rigor plagues many familiar Node.js tools and can be confusing and frustrating. For a great user experience, a command line tool should always be strict about its syntax.
6
+
7
+ - **no gotchas for developers**: Many command-line libraries store their parsed data in a simple JavaScript object. This is convenient for small projects. But suppose a large project has many different source files that define and read parameters. If you try to read `data['output-dir']` when it wasn't defined, or if you misspell the key name, your tool will silently behave as if the parameter was omitted. And is `data['max-count']` a string or a number? Hard to tell! We solve this by modeling each parameter kind as a real TypeScript class.
8
+
9
+ - **simple by design**: Making a CLI is similar to making a graphical UI -- some people have a knack for clean and intuitive designs, but your average developer... needs some help. :-) Keeping things simple is the best help. **ts-command-line** intentionally provides a minimalist set of CLI building blocks that encourage simple designs. If your app has lots of knobs and switches, we recommend NOT to design a complex CLI with hundreds of parameters. Move those options into a commented config file with a published JSON schema.
10
+
11
+ - **automatic documentation**: Some command-line libraries treat the `--help` docs as someone else's job. **ts-command-line** requires each every parameter to follow a standardized naming pattern and have a documentation string. It will automatically generate the `--help` docs for you. If you like to write long paragraphs, no problem -- they will be word-wrapped correctly. *[golf clap]*
12
+
13
+ - **structure and extensibility**: Instead of a simple function chain, **ts-command-line** provides a "scaffold" pattern that makes it easy to find and understand the command-line implementation for any tool project. The scaffold model is generally recommended, but there's also a "dynamic" model if you need it. See below for examples.
14
+
15
+ - **environment variable mappings**: Any CLI parameter can be associated with an environment variable. If the parameter is not explicitly provided, the value from the environment will be used. The associated environment variables are automatically documented in the `--help`.
16
+
17
+ Internally, the implementation is based on [argparse](https://www.npmjs.com/package/argparse) and the Python approach to command-lines.
18
+
19
+ Compared to other libraries, **ts-command-line** doesn't provide zillions of custom syntaxes and bells and whistles. Instead it aims to be a simple, consistent, and professional solution for your command-line tool. Give it a try!
20
+
21
+ ### Some Terminology
22
+
23
+ Suppose that we want to parse a command-line like this:
24
+
25
+ ```
26
+ widget --verbose push --force --max-count 123
27
+ ```
28
+
29
+ In this example, we can identify the following components:
30
+
31
+ - The **tool name** in this example is `widget`. This is the name of your Node.js bin script.
32
+ - The **parameters** are `--verbose`, `--force`, and `--max-count`.
33
+ - The value "123" is the **argument** for the `--max-count` integer parameter. (Flags don't have arguments, because their value is determined by whether the flag was provided or not.)
34
+ - Similar to Git's command-line, the `push` token is called an **action**. It acts as sub-command with its own unique set of parameters.
35
+ - The `--verbose` flag is a **global parameter** because it precedes the action name. It affects all actions.
36
+ - The `--force` flag is an **action parameter** because it comes after the action name. It only applies to that action.
37
+
38
+
39
+ ### Parameter Kinds
40
+
41
+ Several different kinds of parameters are supported:
42
+
43
+ | Parameter Kind | Example | Data Type | Description |
44
+ | --- | --- | --- | --- |
45
+ | flag | `--verbose` | `boolean` | Value is `true` if the flag was specified on the command line, `false` otherwise. |
46
+ | integer | `--max-retry 3` | `int` | The argument is an integer number |
47
+ | string | `--title "Hello, world"` | `string` | The argument is a text string. |
48
+ | choice | `--color red` | `string` | The argument is must be a string from a list of allowed choices (similar to an enum). |
49
+ | string list | `-o file1.txt -o file2.txt` | `string[]` | The argument is a text string. The parameter can be specified multiple times to build a list. |
50
+
51
+ Other parameter kinds could be implemented if requested. That said, keeping your CLI grammar simple and systematic makes it easier for users to learn.
52
+
53
+
54
+ ## Scaffold Model
55
+
56
+ If your tool uses the scaffold model, you will create subclasses of two abstract base classes: `CommandLineParser` for the overall command-line, and `CommandLineAction` for each action.
57
+
58
+ Continuing our example from above, suppose we want to start with a couple simple flags like this:
59
+
60
+ ```
61
+ widget --verbose push --force
62
+ ```
63
+
64
+ We could define our subclass for the "`push`" action like this:
65
+
66
+ ```typescript
67
+ export class PushAction extends CommandLineAction {
68
+ private _force: CommandLineFlagParameter;
69
+ private _protocol: CommandLineChoiceParameter;
70
+
71
+ public constructor() {
72
+ super({
73
+ actionName: 'push',
74
+ summary: 'Pushes a widget to the service',
75
+ documentation: 'Here we provide a longer description of how our action works.'
76
+ });
77
+ }
78
+
79
+ protected onExecute(): Promise<void> { // abstract
80
+ return BusinessLogic.doTheWork(this._force.value, this._protocol.value || "(none)");
81
+ }
82
+
83
+ protected onDefineParameters(): void { // abstract
84
+ this._force = this.defineFlagParameter({
85
+ parameterLongName: '--force',
86
+ parameterShortName: '-f',
87
+ description: 'Push and overwrite any existing state'
88
+ });
89
+
90
+ this._protocol = this.defineChoiceParameter({
91
+ parameterLongName: '--protocol',
92
+ description: 'Specify the protocol to use',
93
+ alternatives: ['ftp', 'webdav', 'scp'],
94
+ environmentVariable: 'WIDGET_PROTOCOL',
95
+ defaultValue: 'scp'
96
+ });
97
+ }
98
+ }
99
+ ```
100
+
101
+ Then we might define the parser subclass like this:
102
+
103
+ ```typescript
104
+ export class WidgetCommandLine extends CommandLineParser {
105
+ private _verbose: CommandLineFlagParameter;
106
+
107
+ public constructor() {
108
+ super({
109
+ toolFilename: 'widget',
110
+ toolDescription: 'The "widget" tool is a code sample for using the @rushstack/ts-command-line library.'
111
+ });
112
+
113
+ this.addAction(new PushAction());
114
+ }
115
+
116
+ protected onDefineParameters(): void { // abstract
117
+ this._verbose = this.defineFlagParameter({
118
+ parameterLongName: '--verbose',
119
+ parameterShortName: '-v',
120
+ description: 'Show extra logging detail'
121
+ });
122
+ }
123
+
124
+ protected onExecute(): Promise<void> { // override
125
+ BusinessLogic.configureLogger(this._verbose.value);
126
+ return super.onExecute();
127
+ }
128
+ }
129
+ ```
130
+
131
+ To invoke the parser, the application entry point will do something like this:
132
+
133
+ ```typescript
134
+ const commandLine: WidgetCommandLine = new WidgetCommandLine();
135
+ commandLine.execute();
136
+ ```
137
+
138
+ When we run `widget --verbose push --force`, the `PushAction.onExecute()` method will get invoked and then your business logic takes over.
139
+
140
+ ---
141
+
142
+ **For a more complete example, take a look at the [ts-command-line-test](https://github.com/microsoft/rushstack/tree/main/build-tests/ts-command-line-test) sample project.**
143
+
144
+ ---
145
+
146
+ #### Testing out the docs
147
+
148
+ If you invoke the tool as "`widget --help`", the docs are automatically generated:
149
+
150
+ ```
151
+ usage: widget [-h] [-v] <command> ...
152
+
153
+ The "widget" tool is a code sample for using the @rushstack/ts-command-line
154
+ library.
155
+
156
+ Positional arguments:
157
+ <command>
158
+ push Pushes a widget to the service
159
+
160
+ Optional arguments:
161
+ -h, --help Show this help message and exit.
162
+ -v, --verbose Show extra logging detail
163
+
164
+ For detailed help about a specific command, use: widget <command> -h
165
+ ```
166
+
167
+ For help about the `push` action, the user can type "`widget push --help`", which shows this output:
168
+
169
+ ```
170
+ usage: widget push [-h] [-f] [--protocol {ftp,webdav,scp}]
171
+
172
+ Here we provide a longer description of how our action works.
173
+
174
+ Optional arguments:
175
+ -h, --help Show this help message and exit.
176
+ -f, --force Push and overwrite any existing state
177
+ --protocol {ftp,webdav,scp}
178
+ Specify the protocol to use. This parameter may
179
+ alternatively specified via the WIDGET_PROTOCOL
180
+ environment variable. The default value is "scp".
181
+ ```
182
+
183
+ ## Dynamic Model
184
+
185
+ The action subclasses provide a simple, recognizable pattern that you can use across all your tooling projects. It's the generally recommended approach. However, there are some cases where we need to break out of the scaffold. For example:
186
+
187
+ - Actions or parameters may be discovered at runtime, e.g. from a config file
188
+ - The actions and their implementations may sometimes have very different structures
189
+
190
+ In this case, you can use the `DynamicCommandLineAction` and `DynamicCommandLineParser` classes which are not abstract (and not intended to be subclassed). Here's our above example rewritten for this model:
191
+
192
+ ```typescript
193
+ // Define the parser
194
+ const commandLineParser: DynamicCommandLineParser = new DynamicCommandLineParser({
195
+ toolFilename: 'widget',
196
+ toolDescription: 'The "widget" tool is a code sample for using the @rushstack/ts-command-line library.'
197
+ });
198
+
199
+ commandLineParser.defineFlagParameter({
200
+ parameterLongName: '--verbose',
201
+ parameterShortName: '-v',
202
+ description: 'Show extra logging detail'
203
+ });
204
+
205
+ // Define the action
206
+ const action: DynamicCommandLineAction = new DynamicCommandLineAction({
207
+ actionName: 'push',
208
+ summary: 'Pushes a widget to the service',
209
+ documentation: 'Here we provide a longer description of how our action works.'
210
+ });
211
+
212
+ commandLineParser.addAction(action);
213
+
214
+ action.defineFlagParameter({
215
+ parameterLongName: '--force',
216
+ parameterShortName: '-f',
217
+ description: 'Push and overwrite any existing state'
218
+ });
219
+
220
+ action.defineChoiceParameter({
221
+ parameterLongName: '--protocol',
222
+ description: 'Specify the protocol to use',
223
+ alternatives: ['ftp', 'webdav', 'scp'],
224
+ environmentVariable: 'WIDGET_PROTOCOL',
225
+ defaultValue: 'scp'
226
+ });
227
+
228
+ // Parse the command line
229
+ commandLineParser.execute().then(() => {
230
+ console.log('The action is: ' + commandLineParser.selectedAction!.actionName);
231
+ console.log('The force flag is: ' + action.getFlagParameter('--force').value);
232
+ });
233
+ ```
234
+
235
+ You can also mix the two models. For example, we could augment the `WidgetCommandLine` from the original model by adding `DynamicAction` objects to it.
236
+
237
+
238
+ ## Links
239
+
240
+ - [CHANGELOG.md](
241
+ https://github.com/microsoft/rushstack/blob/main/libraries/ts-command-line/CHANGELOG.md) - Find
242
+ out what's new in the latest version
243
+ - [API Reference](https://api.rushstack.io/pages/ts-command-line/)
244
+
245
+ Here are some real world GitHub projects that illustrate different use cases for **ts-command-line**:
246
+
247
+ - [@microsoft/rush](https://www.npmjs.com/package/@microsoft/rush)
248
+ - [@microsoft/api-extractor](https://www.npmjs.com/package/@microsoft/api-extractor)
249
+ - [@microsoft/api-documenter](https://www.npmjs.com/package/@microsoft/api-documenter)
250
+
251
+ `@rushstack/ts-command-line` is part of the [Rush Stack](https://rushstack.io/) family of projects.
@@ -5,7 +5,7 @@
5
5
  "toolPackages": [
6
6
  {
7
7
  "packageName": "@microsoft/api-extractor",
8
- "packageVersion": "7.37.1"
8
+ "packageVersion": "7.39.1"
9
9
  }
10
10
  ]
11
11
  }
@@ -1 +1 @@
1
- {"version":3,"file":"CommandLineHelper.js","sourceRoot":"","sources":["../src/CommandLineHelper.ts"],"names":[],"mappings":";AAAA,4FAA4F;AAC5F,2DAA2D;;;AAI3D;;;;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,sEAAiD,CAAC;IAC7F,CAAC;CACF;AATD,8CASC","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.\r\n// See LICENSE in the project root for license information.\r\n\r\nimport { CommandLineConstants } from './Constants';\r\n\r\n/**\r\n * Helpers for working with the ts-command-line API.\r\n *\r\n * @public\r\n */\r\nexport class CommandLineHelper {\r\n /**\r\n * Returns true if the current command line action is tab-complete.\r\n *\r\n * @public\r\n */\r\n public static isTabCompletionActionRequest(argv: string[]): boolean {\r\n return argv && argv.length > 2 && argv[2] === CommandLineConstants.TabCompletionActionName;\r\n }\r\n}\r\n"]}
1
+ {"version":3,"file":"CommandLineHelper.js","sourceRoot":"","sources":["../src/CommandLineHelper.ts"],"names":[],"mappings":";AAAA,4FAA4F;AAC5F,2DAA2D;;;AAI3D;;;;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,sEAAiD,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"]}
@@ -1 +1 @@
1
- {"version":3,"file":"Constants.js","sourceRoot":"","sources":["../src/Constants.ts"],"names":[],"mappings":";AAAA,4FAA4F;AAC5F,2DAA2D;;;AAc9C,QAAA,uBAAuB,GAAkB,MAAM,CAAC,SAAS,CAAC,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.\r\n// See LICENSE in the project root for license information.\r\n\r\n/**\r\n * String constants for command line processing.\r\n *\r\n * @public\r\n */\r\nexport const enum CommandLineConstants {\r\n /**\r\n * The name of the built-in action that serves suggestions for tab-completion\r\n */\r\n TabCompletionActionName = 'tab-complete'\r\n}\r\n\r\nexport const SCOPING_PARAMETER_GROUP: unique symbol = Symbol('scoping');\r\n"]}
1
+ {"version":3,"file":"Constants.js","sourceRoot":"","sources":["../src/Constants.ts"],"names":[],"mappings":";AAAA,4FAA4F;AAC5F,2DAA2D;;;AAc9C,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 const 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"]}
package/lib/index.js.map CHANGED
@@ -1 +1 @@
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,wDAIkC;AAHhC,uHAAA,wBAAwB,OAAA;AACxB,mHAAA,oBAAoB,OAAA;AACpB,+HAAA,gCAAgC,OAAA;AAGlC,kFAAiF;AAAxE,oIAAA,wBAAwB,OAAA;AACjC,sFAAqF;AAA5E,wIAAA,0BAA0B,OAAA;AACnC,8FAA6F;AAApF,gJAAA,8BAA8B,OAAA;AACvC,wFAAuF;AAA9E,0IAAA,2BAA2B,OAAA;AACpC,gGAA+F;AAAtF,kJAAA,+BAA+B,OAAA;AACxC,sFAAqF;AAA5E,wIAAA,0BAA0B,OAAA;AACnC,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;AAIjC,yDAAwD;AAA/C,sHAAA,iBAAiB,OAAA","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.\r\n// See LICENSE in the project root for license information.\r\n\r\n/**\r\n * An object-oriented command-line parser for TypeScript projects.\r\n *\r\n * @packageDocumentation\r\n */\r\n\r\nexport { CommandLineAction, type ICommandLineActionOptions } from './providers/CommandLineAction';\r\nexport { DynamicCommandLineAction } from './providers/DynamicCommandLineAction';\r\nexport { ScopedCommandLineAction } from './providers/ScopedCommandLineAction';\r\nexport {\r\n AliasCommandLineAction,\r\n type IAliasCommandLineActionOptions\r\n} from './providers/AliasCommandLineAction';\r\n\r\nexport type {\r\n IBaseCommandLineDefinition,\r\n IBaseCommandLineDefinitionWithArgument,\r\n ICommandLineFlagDefinition,\r\n ICommandLineStringDefinition,\r\n ICommandLineStringListDefinition,\r\n ICommandLineIntegerDefinition,\r\n ICommandLineIntegerListDefinition,\r\n ICommandLineChoiceDefinition,\r\n ICommandLineChoiceListDefinition,\r\n ICommandLineRemainderDefinition\r\n} from './parameters/CommandLineDefinition';\r\n\r\nexport {\r\n CommandLineParameterKind,\r\n CommandLineParameter,\r\n CommandLineParameterWithArgument\r\n} from './parameters/BaseClasses';\r\n\r\nexport { CommandLineFlagParameter } from './parameters/CommandLineFlagParameter';\r\nexport { CommandLineStringParameter } from './parameters/CommandLineStringParameter';\r\nexport { CommandLineStringListParameter } from './parameters/CommandLineStringListParameter';\r\nexport { CommandLineIntegerParameter } from './parameters/CommandLineIntegerParameter';\r\nexport { CommandLineIntegerListParameter } from './parameters/CommandLineIntegerListParameter';\r\nexport { CommandLineChoiceParameter } from './parameters/CommandLineChoiceParameter';\r\nexport { CommandLineChoiceListParameter } from './parameters/CommandLineChoiceListParameter';\r\nexport { CommandLineRemainder } from './parameters/CommandLineRemainder';\r\n\r\nexport {\r\n CommandLineParameterProvider,\r\n type IScopedLongNameParseResult,\r\n type ICommandLineParserData as _ICommandLineParserData,\r\n type IRegisterDefinedParametersState as _IRegisterDefinedParametersState\r\n} from './providers/CommandLineParameterProvider';\r\n\r\nexport { CommandLineParser, type ICommandLineParserOptions } from './providers/CommandLineParser';\r\nexport { DynamicCommandLineParser } from './providers/DynamicCommandLineParser';\r\n\r\nexport { CommandLineConstants } from './Constants';\r\n\r\nexport { CommandLineHelper } from './CommandLineHelper';\r\n"]}
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,wDAIkC;AAHhC,uHAAA,wBAAwB,OAAA;AACxB,mHAAA,oBAAoB,OAAA;AACpB,+HAAA,gCAAgC,OAAA;AAGlC,kFAAiF;AAAxE,oIAAA,wBAAwB,OAAA;AACjC,sFAAqF;AAA5E,wIAAA,0BAA0B,OAAA;AACnC,8FAA6F;AAApF,gJAAA,8BAA8B,OAAA;AACvC,wFAAuF;AAA9E,0IAAA,2BAA2B,OAAA;AACpC,gGAA+F;AAAtF,kJAAA,+BAA+B,OAAA;AACxC,sFAAqF;AAA5E,wIAAA,0BAA0B,OAAA;AACnC,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;AAIjC,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 CommandLineParameter,\n CommandLineParameterWithArgument\n} from './parameters/BaseClasses';\n\nexport { CommandLineFlagParameter } from './parameters/CommandLineFlagParameter';\nexport { CommandLineStringParameter } from './parameters/CommandLineStringParameter';\nexport { CommandLineStringListParameter } from './parameters/CommandLineStringListParameter';\nexport { CommandLineIntegerParameter } from './parameters/CommandLineIntegerParameter';\nexport { CommandLineIntegerListParameter } from './parameters/CommandLineIntegerListParameter';\nexport { CommandLineChoiceParameter } 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"]}
@@ -23,7 +23,7 @@ var CommandLineParameterKind;
23
23
  CommandLineParameterKind[CommandLineParameterKind["ChoiceList"] = 5] = "ChoiceList";
24
24
  /** Indicates a CommandLineIntegerListParameter */
25
25
  CommandLineParameterKind[CommandLineParameterKind["IntegerList"] = 6] = "IntegerList";
26
- })(CommandLineParameterKind = exports.CommandLineParameterKind || (exports.CommandLineParameterKind = {}));
26
+ })(CommandLineParameterKind || (exports.CommandLineParameterKind = CommandLineParameterKind = {}));
27
27
  /**
28
28
  * Matches kebab-case formatted strings prefixed with double dashes.
29
29
  * Example: "--do-something"
@@ -167,7 +167,7 @@ class CommandLineParameterWithArgument extends CommandLineParameter {
167
167
  this.completions = definition.completions;
168
168
  }
169
169
  }
170
+ exports.CommandLineParameterWithArgument = CommandLineParameterWithArgument;
170
171
  // Matches the first character that *isn't* part of a valid upper-case argument name such as "URL_2"
171
172
  CommandLineParameterWithArgument._invalidArgumentNameRegExp = /[^A-Z_0-9]/;
172
- exports.CommandLineParameterWithArgument = CommandLineParameterWithArgument;
173
173
  //# sourceMappingURL=BaseClasses.js.map