0
# Command Line Interface
1
2
Options and arguments definition system with parsing, validation, and help generation for creating command-line tools with Yeoman generators.
3
4
## Capabilities
5
6
### Option Definition
7
8
Define command line options with type validation, defaults, and help text.
9
10
```typescript { .api }
11
/**
12
* Adds an option to the set of generator expected options
13
* By default, generators get all the CLI options parsed by nopt as this.options hash
14
* @param name - Option name or option specification object
15
* @param config - Option configuration
16
* @returns This generator for chaining
17
*/
18
option(name: string | CliOptionSpec | CliOptionSpec[], config?: Partial<Omit<CliOptionSpec, 'name'>>): this;
19
```
20
21
**Usage Examples:**
22
23
```typescript
24
export default class MyGenerator extends Generator {
25
constructor(args, opts) {
26
super(args, opts);
27
28
// Basic boolean option
29
this.option('skip-install', {
30
type: Boolean,
31
description: 'Skip npm install',
32
default: false
33
});
34
35
// String option with alias
36
this.option('project-name', {
37
type: String,
38
alias: 'n',
39
description: 'Name of the project',
40
default: 'my-project'
41
});
42
43
// Number option
44
this.option('port', {
45
type: Number,
46
description: 'Server port number',
47
default: 3000
48
});
49
50
// Hidden option (not shown in help)
51
this.option('internal-flag', {
52
type: Boolean,
53
hide: true,
54
description: 'Internal use only'
55
});
56
57
// Option with storage
58
this.option('author', {
59
type: String,
60
description: 'Author name',
61
storage: this.config // Store in generator config
62
});
63
}
64
65
initializing() {
66
// Access options
67
if (this.options.skipInstall) {
68
this.log('Skipping npm install...');
69
}
70
71
this.log(`Project name: ${this.options.projectName}`);
72
this.log(`Port: ${this.options.port}`);
73
}
74
}
75
```
76
77
### Argument Definition
78
79
Define positional command line arguments with type validation and requirements.
80
81
```typescript { .api }
82
/**
83
* Adds an argument to the class and creates an attribute getter for it
84
* Arguments are different from options - they are retrieved based on their position
85
* @param name - Argument name
86
* @param config - Argument configuration
87
* @returns This generator for chaining
88
*/
89
argument(name: string, config?: Partial<ArgumentSpec>): this;
90
```
91
92
**Usage Examples:**
93
94
```typescript
95
export default class MyGenerator extends Generator {
96
constructor(args, opts) {
97
super(args, opts);
98
99
// Required string argument
100
this.argument('appname', {
101
type: String,
102
description: 'Name of the application',
103
required: true
104
});
105
106
// Optional argument with default
107
this.argument('template', {
108
type: String,
109
description: 'Template to use',
110
required: false,
111
default: 'basic'
112
});
113
114
// Array argument (captures remaining arguments)
115
this.argument('features', {
116
type: Array,
117
description: 'Features to include',
118
required: false,
119
default: []
120
});
121
}
122
123
initializing() {
124
// Access arguments
125
this.log(`App name: ${this.options.appname}`);
126
this.log(`Template: ${this.options.template}`);
127
this.log(`Features: ${this.options.features.join(', ')}`);
128
129
// Also available as this.args array
130
this.log(`Raw arguments: ${this.args.join(' ')}`);
131
}
132
}
133
```
134
135
### Help Generation
136
137
Automatic help text generation with usage information and option/argument documentation.
138
139
```typescript { .api }
140
/**
141
* Generate help message for the generator
142
* @returns Complete help message with usage, options, and arguments
143
*/
144
help(): string;
145
146
/**
147
* Generate usage information for this generator
148
* @returns Usage line showing proper command syntax
149
*/
150
usage(): string;
151
152
/**
153
* Set custom description to append on help output
154
* @param description - Description text
155
* @returns This generator for chaining
156
*/
157
desc(description: string): this;
158
159
/**
160
* Get help text for arguments
161
* @returns Formatted table of arguments with descriptions
162
*/
163
argumentsHelp(): string;
164
165
/**
166
* Get help text for options
167
* @returns Formatted table of options with descriptions
168
*/
169
optionsHelp(): string;
170
```
171
172
**Usage Examples:**
173
174
```typescript
175
export default class MyGenerator extends Generator {
176
constructor(args, opts) {
177
super(args, opts);
178
179
// Set generator description
180
this.desc('Generate a new Node.js project with customizable features');
181
182
// Define options and arguments
183
this.argument('name', {
184
type: String,
185
description: 'Project name',
186
required: true
187
});
188
189
this.option('typescript', {
190
type: Boolean,
191
alias: 't',
192
description: 'Use TypeScript',
193
default: false
194
});
195
196
this.option('package-manager', {
197
type: String,
198
alias: 'pm',
199
description: 'Package manager to use',
200
default: 'npm'
201
});
202
}
203
204
// Users can run: yo myapp --help
205
// This will automatically generate help text like:
206
//
207
// Usage:
208
// yo myapp <name> [options]
209
//
210
// Generate a new Node.js project with customizable features
211
//
212
// Options:
213
// -t, --typescript Use TypeScript Default: false
214
// --pm, --package-manager Package manager to use Default: npm
215
// -h, --help Print the generator's options and usage
216
//
217
// Arguments:
218
// name Project name Type: String Required: true
219
}
220
```
221
222
### Option Parsing
223
224
Automatic parsing and validation of command line options and arguments.
225
226
```typescript { .api }
227
/**
228
* Parse command line options and arguments
229
* Usually called automatically, but can be called manually
230
*/
231
parseOptions(): void;
232
233
/**
234
* Check that all required arguments are present
235
* Throws error if required arguments are missing
236
*/
237
checkRequiredArgs(): void;
238
```
239
240
**Usage Example:**
241
242
```typescript
243
export default class MyGenerator extends Generator {
244
constructor(args, opts) {
245
super(args, opts);
246
247
this.argument('name', { type: String, required: true });
248
this.option('force', { type: Boolean, default: false });
249
250
// Parsing is automatic, but you can force it
251
if (this.features.skipParseOptions) {
252
this.parseOptions();
253
}
254
}
255
256
initializing() {
257
// Arguments and options are parsed and available
258
this.log(`Creating project: ${this.options.name}`);
259
260
if (this.options.force) {
261
this.log('Force mode enabled');
262
}
263
}
264
}
265
```
266
267
### Built-in Options
268
269
Standard options available in all generators.
270
271
```typescript { .api }
272
// Built-in options (automatically available)
273
interface BuiltInOptions {
274
help: boolean; // -h, --help: Print generator help
275
skipCache: boolean; // --skip-cache: Do not remember prompt answers
276
skipInstall: boolean; // --skip-install: Do not automatically install dependencies
277
forceInstall: boolean; // --force-install: Fail on install dependencies error
278
askAnswered: boolean; // --ask-answered: Show prompts for already configured options
279
}
280
```
281
282
**Usage Example:**
283
284
```typescript
285
export default class MyGenerator extends Generator {
286
constructor(args, opts) {
287
super(args, opts);
288
289
// Built-in options are always available
290
if (this.options.help) {
291
// Help will be shown automatically, this won't run
292
return;
293
}
294
}
295
296
async prompting() {
297
// skipCache affects prompt behavior
298
if (!this.options.skipCache) {
299
this.log('Using cached answers...');
300
}
301
302
this.answers = await this.prompt([...]);
303
}
304
305
install() {
306
// skipInstall affects install behavior
307
if (!this.options.skipInstall) {
308
this.spawnCommand('npm', ['install']);
309
}
310
}
311
}
312
```
313
314
### Advanced Option Configuration
315
316
Complex option configurations with custom types and validation.
317
318
**Usage Examples:**
319
320
```typescript
321
export default class MyGenerator extends Generator {
322
constructor(args, opts) {
323
super(args, opts);
324
325
// Custom type converter
326
this.option('features', {
327
type: (val) => val.split(','),
328
description: 'Comma-separated list of features',
329
default: []
330
});
331
332
// Multiple option objects at once
333
this.option([
334
{
335
name: 'verbose',
336
type: Boolean,
337
alias: 'v',
338
description: 'Verbose output',
339
default: false
340
},
341
{
342
name: 'config-file',
343
type: String,
344
description: 'Path to config file',
345
storage: this.config
346
}
347
]);
348
349
// Required option
350
this.option('api-key', {
351
type: String,
352
required: true,
353
description: 'API key for service'
354
});
355
}
356
357
initializing() {
358
// Validate custom requirements
359
if (this.options.features.includes('database') && !this.options.dbUrl) {
360
throw new Error('Database feature requires --db-url option');
361
}
362
}
363
}
364
```
365
366
### Option Storage Integration
367
368
Automatic persistence of option values to configuration storage.
369
370
**Usage Example:**
371
372
```typescript
373
export default class MyGenerator extends Generator {
374
constructor(args, opts) {
375
super(args, opts);
376
377
// Options with storage are automatically persisted
378
this.option('author-name', {
379
type: String,
380
description: 'Author name',
381
storage: this.config, // Store in .yo-rc.json
382
default: 'Anonymous'
383
});
384
385
this.option('git-email', {
386
type: String,
387
description: 'Git email',
388
storage: 'config', // Store in this.config by name
389
default: async () => await this.git.email()
390
});
391
}
392
393
configuring() {
394
// Stored options are automatically available in config
395
const authorName = this.config.get('authorName');
396
const gitEmail = this.config.get('gitEmail');
397
398
this.log(`Config author: ${authorName}`);
399
this.log(`Config email: ${gitEmail}`);
400
}
401
}
402
```
403
404
## Types
405
406
```typescript { .api }
407
interface CliOptionSpec {
408
name: string;
409
type: typeof Boolean | typeof String | typeof Number | ((opt: string) => any);
410
required?: boolean;
411
alias?: string;
412
default?: any;
413
description?: string;
414
hide?: boolean;
415
storage?: string | Storage;
416
}
417
418
interface ArgumentSpec {
419
name: string;
420
description?: string;
421
required?: boolean;
422
optional?: boolean;
423
type: typeof String | typeof Number | typeof Array | typeof Object;
424
default?: any;
425
}
426
```