@xmorse/cac 6.0.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) EGOIST <0x142857@gmail.com> (https://github.com/egoist)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,536 @@
1
+ <img width="945" alt="2017-07-26 9 27 05" src="https://user-images.githubusercontent.com/8784712/28623641-373450f4-7249-11e7-854d-1b076dab274d.png">
2
+
3
+ [![NPM version](https://img.shields.io/npm/v/cac.svg?style=flat)](https://npmjs.com/package/cac) [![NPM downloads](https://img.shields.io/npm/dm/cac.svg?style=flat)](https://npmjs.com/package/cac) [![CircleCI](https://circleci.com/gh/cacjs/cac/tree/master.svg?style=shield)](https://circleci.com/gh/cacjs/cac/tree/master) [![Codecov](https://badgen.net/codecov/c/github/cacjs/cac/master)](https://codecov.io/gh/cacjs/cac) [![donate](https://img.shields.io/badge/$-donate-ff69b4.svg?maxAge=2592000&style=flat)](https://github.com/egoist/donate) [![install size](https://badgen.net/packagephobia/install/cac)](https://packagephobia.now.sh/result?p=cac)
4
+
5
+ ## Introduction
6
+
7
+ **C**ommand **A**nd **C**onquer is a JavaScript library for building CLI apps.
8
+
9
+ ## Features
10
+
11
+ - **Super light-weight**: No dependency, just a single file.
12
+ - **Easy to learn**. There're only 4 APIs you need to learn for building simple CLIs: `cli.option` `cli.version` `cli.help` `cli.parse`.
13
+ - **Yet so powerful**. Enable features like default command, git-like subcommands, validation for required arguments and options, variadic arguments, dot-nested options, automated help message generation and so on.
14
+ - **Developer friendly**. Written in TypeScript.
15
+
16
+ ## Table of Contents
17
+
18
+ <!-- toc -->
19
+
20
+ - [Install](#install)
21
+ - [Usage](#usage)
22
+ - [Simple Parsing](#simple-parsing)
23
+ - [Display Help Message and Version](#display-help-message-and-version)
24
+ - [Command-specific Options](#command-specific-options)
25
+ - [Dash in option names](#dash-in-option-names)
26
+ - [Brackets](#brackets)
27
+ - [Negated Options](#negated-options)
28
+ - [Variadic Arguments](#variadic-arguments)
29
+ - [Dot-nested Options](#dot-nested-options)
30
+ - [Default Command](#default-command)
31
+ - [Supply an array as option value](#supply-an-array-as-option-value)
32
+ - [Error Handling](#error-handling)
33
+ - [With TypeScript](#with-typescript)
34
+ - [With Deno](#with-deno)
35
+ - [Projects Using CAC](#projects-using-cac)
36
+ - [References](#references)
37
+ - [CLI Instance](#cli-instance)
38
+ - [cac(name?)](#cacname)
39
+ - [cli.command(name, description, config?)](#clicommandname-description-config)
40
+ - [cli.option(name, description, config?)](#clioptionname-description-config)
41
+ - [cli.parse(argv?)](#cliparseargv)
42
+ - [cli.version(version, customFlags?)](#cliversionversion-customflags)
43
+ - [cli.help(callback?)](#clihelpcallback)
44
+ - [cli.outputHelp()](#clioutputhelp)
45
+ - [cli.usage(text)](#cliusagetext)
46
+ - [Command Instance](#command-instance)
47
+ - [command.option()](#commandoption)
48
+ - [command.action(callback)](#commandactioncallback)
49
+ - [command.alias(name)](#commandaliasname)
50
+ - [command.allowUnknownOptions()](#commandallowunknownoptions)
51
+ - [command.example(example)](#commandexampleexample)
52
+ - [command.usage(text)](#commandusagetext)
53
+ - [Events](#events)
54
+ - [FAQ](#faq)
55
+ - [How is the name written and pronounced?](#how-is-the-name-written-and-pronounced)
56
+ - [Why not use Commander.js?](#why-not-use-commanderjs)
57
+ - [Project Stats](#project-stats)
58
+ - [Contributing](#contributing)
59
+ - [Author](#author)
60
+
61
+ <!-- tocstop -->
62
+
63
+ ## Install
64
+
65
+ ```bash
66
+ yarn add cac
67
+ ```
68
+
69
+ ## Usage
70
+
71
+ ### Simple Parsing
72
+
73
+ Use CAC as simple argument parser:
74
+
75
+ ```js
76
+ // examples/basic-usage.js
77
+ const cli = require('cac')()
78
+
79
+ cli.option('--type <type>', 'Choose a project type', {
80
+ default: 'node',
81
+ })
82
+
83
+ const parsed = cli.parse()
84
+
85
+ console.log(JSON.stringify(parsed, null, 2))
86
+ ```
87
+
88
+ <img width="500" alt="2018-11-26 12 28 03" src="https://user-images.githubusercontent.com/8784712/48981576-2a871000-f112-11e8-8151-80f61e9b9908.png">
89
+
90
+ ### Display Help Message and Version
91
+
92
+ ```js
93
+ // examples/help.js
94
+ const cli = require('cac')()
95
+
96
+ cli.option('--type [type]', 'Choose a project type', {
97
+ default: 'node',
98
+ })
99
+ cli.option('--name <name>', 'Provide your name')
100
+
101
+ cli.command('lint [...files]', 'Lint files').action((files, options) => {
102
+ console.log(files, options)
103
+ })
104
+
105
+ // Display help message when `-h` or `--help` appears
106
+ cli.help()
107
+ // Display version number when `-v` or `--version` appears
108
+ // It's also used in help message
109
+ cli.version('0.0.0')
110
+
111
+ cli.parse()
112
+ ```
113
+
114
+ <img width="500" alt="2018-11-25 8 21 14" src="https://user-images.githubusercontent.com/8784712/48979012-acb20d00-f0ef-11e8-9cc6-8ffca00ab78a.png">
115
+
116
+ ### Command-specific Options
117
+
118
+ You can attach options to a command.
119
+
120
+ ```js
121
+ const cli = require('cac')()
122
+
123
+ cli
124
+ .command('rm <dir>', 'Remove a dir')
125
+ .option('-r, --recursive', 'Remove recursively')
126
+ .action((dir, options) => {
127
+ console.log('remove ' + dir + (options.recursive ? ' recursively' : ''))
128
+ })
129
+
130
+ cli.help()
131
+
132
+ cli.parse()
133
+ ```
134
+
135
+ A command's options are validated when the command is used. Any unknown options will be reported as an error. However, if an action-based command does not define an action, then the options are not validated. If you really want to use unknown options, use [`command.allowUnknownOptions`](#commandallowunknownoptions).
136
+
137
+ <img alt="command options" width="500" src="https://user-images.githubusercontent.com/8784712/49065552-49dc8500-f259-11e8-9c7b-a7c32d70920e.png">
138
+
139
+ ### Dash in option names
140
+
141
+ Options in kebab-case should be referenced in camelCase in your code:
142
+
143
+ ```js
144
+ cli
145
+ .command('dev', 'Start dev server')
146
+ .option('--clear-screen', 'Clear screen')
147
+ .action((options) => {
148
+ console.log(options.clearScreen)
149
+ })
150
+ ```
151
+
152
+ In fact `--clear-screen` and `--clearScreen` are both mapped to `options.clearScreen`.
153
+
154
+ ### Brackets
155
+
156
+ When using brackets in command name, angled brackets indicate required command arguments, while square bracket indicate optional arguments.
157
+
158
+ When using brackets in option name, angled brackets indicate that a string / number value is required, while square bracket indicate that the value can also be `true`.
159
+
160
+ ```js
161
+ const cli = require('cac')()
162
+
163
+ cli
164
+ .command('deploy <folder>', 'Deploy a folder to AWS')
165
+ .option('--scale [level]', 'Scaling level')
166
+ .action((folder, options) => {
167
+ // ...
168
+ })
169
+
170
+ cli
171
+ .command('build [project]', 'Build a project')
172
+ .option('--out <dir>', 'Output directory')
173
+ .action((folder, options) => {
174
+ // ...
175
+ })
176
+
177
+ cli.parse()
178
+ ```
179
+
180
+ ### Negated Options
181
+
182
+ To allow an option whose value is `false`, you need to manually specify a negated option:
183
+
184
+ ```js
185
+ cli
186
+ .command('build [project]', 'Build a project')
187
+ .option('--no-config', 'Disable config file')
188
+ .option('--config <path>', 'Use a custom config file')
189
+ ```
190
+
191
+ This will let CAC set the default value of `config` to true, and you can use `--no-config` flag to set it to `false`.
192
+
193
+ ### Variadic Arguments
194
+
195
+ The last argument of a command can be variadic, and only the last argument. To make an argument variadic you have to add `...` to the start of argument name, just like the rest operator in JavaScript. Here is an example:
196
+
197
+ ```js
198
+ const cli = require('cac')()
199
+
200
+ cli
201
+ .command('build <entry> [...otherFiles]', 'Build your app')
202
+ .option('--foo', 'Foo option')
203
+ .action((entry, otherFiles, options) => {
204
+ console.log(entry)
205
+ console.log(otherFiles)
206
+ console.log(options)
207
+ })
208
+
209
+ cli.help()
210
+
211
+ cli.parse()
212
+ ```
213
+
214
+ <img width="500" alt="2018-11-25 8 25 30" src="https://user-images.githubusercontent.com/8784712/48979056-47125080-f0f0-11e8-9d8f-3219e0beb0ed.png">
215
+
216
+ ### Dot-nested Options
217
+
218
+ Dot-nested options will be merged into a single option.
219
+
220
+ ```js
221
+ const cli = require('cac')()
222
+
223
+ cli
224
+ .command('build', 'desc')
225
+ .option('--env <env>', 'Set envs')
226
+ .example('--env.API_SECRET xxx')
227
+ .action((options) => {
228
+ console.log(options)
229
+ })
230
+
231
+ cli.help()
232
+
233
+ cli.parse()
234
+ ```
235
+
236
+ <img width="500" alt="2018-11-25 9 37 53" src="https://user-images.githubusercontent.com/8784712/48979771-6ada9400-f0fa-11e8-8192-e541b2cfd9da.png">
237
+
238
+ ### Default Command
239
+
240
+ Register a command that will be used when no other command is matched.
241
+
242
+ ```js
243
+ const cli = require('cac')()
244
+
245
+ cli
246
+ // Simply omit the command name, just brackets
247
+ .command('[...files]', 'Build files')
248
+ .option('--minimize', 'Minimize output')
249
+ .action((files, options) => {
250
+ console.log(files)
251
+ console.log(options.minimize)
252
+ })
253
+
254
+ cli.parse()
255
+ ```
256
+
257
+ ### Supply an array as option value
258
+
259
+ ```bash
260
+ node cli.js --include project-a
261
+ # The parsed options will be:
262
+ # { include: 'project-a' }
263
+
264
+ node cli.js --include project-a --include project-b
265
+ # The parsed options will be:
266
+ # { include: ['project-a', 'project-b'] }
267
+ ```
268
+
269
+ ### Error Handling
270
+
271
+ To handle command errors globally:
272
+
273
+ ```js
274
+ try {
275
+ // Parse CLI args without running the command
276
+ cli.parse(process.argv, { run: false })
277
+ // Run the command yourself
278
+ // You only need `await` when your command action returns a Promise
279
+ await cli.runMatchedCommand()
280
+ } catch (error) {
281
+ // Handle error here..
282
+ // e.g.
283
+ // console.error(error.stack)
284
+ // process.exit(1)
285
+ }
286
+ ```
287
+
288
+ ### With TypeScript
289
+
290
+ First you need `@types/node` to be installed as a dev dependency in your project:
291
+
292
+ ```bash
293
+ yarn add @types/node --dev
294
+ ```
295
+
296
+ Then everything just works out of the box:
297
+
298
+ ```js
299
+ const { cac } = require('cac')
300
+ // OR ES modules
301
+ import { cac } from 'cac'
302
+ ```
303
+
304
+ ### With Deno
305
+
306
+ ```ts
307
+ import { cac } from 'https://unpkg.com/cac/mod.ts'
308
+
309
+ const cli = cac('my-program')
310
+ ```
311
+
312
+ ## Projects Using CAC
313
+
314
+ Projects that use **CAC**:
315
+
316
+ - [VuePress](https://github.com/vuejs/vuepress): :memo: Minimalistic Vue-powered static site generator.
317
+ - [SAO](https://github.com/egoist/sao): ⚔️ Futuristic scaffolding tool.
318
+ - [DocPad](https://github.com/docpad/docpad): 🏹 Powerful Static Site Generator.
319
+ - [Poi](https://github.com/egoist/poi): ⚡️ Delightful web development.
320
+ - [bili](https://github.com/egoist/bili): 🥂 Schweizer Armeemesser for bundling JavaScript libraries.
321
+ - [Lad](https://github.com/ladjs/lad): 👦 Lad scaffolds a Koa webapp and API framework for Node.js.
322
+ - [Lass](https://github.com/lassjs/lass): 💁🏻 Scaffold a modern package boilerplate for Node.js.
323
+ - [Foy](https://github.com/zaaack/foy): 🏗 A lightweight and modern task runner and build tool for general purpose.
324
+ - [Vuese](https://github.com/vuese/vuese): 🤗 One-stop solution for vue component documentation.
325
+ - [NUT](https://github.com/nut-project/nut): 🌰 A framework born for microfrontends
326
+ - Feel free to add yours here...
327
+
328
+ ## References
329
+
330
+ **💁 Check out [the generated docs](https://cac-api-doc.egoist.dev/classes/_cac_.cac.html) from source code if you want a more in-depth API references.**
331
+
332
+ Below is a brief overview.
333
+
334
+ ### CLI Instance
335
+
336
+ CLI instance is created by invoking the `cac` function:
337
+
338
+ ```js
339
+ const cac = require('cac')
340
+ const cli = cac()
341
+ ```
342
+
343
+ #### cac(name?)
344
+
345
+ Create a CLI instance, optionally specify the program name which will be used to display in help and version message. When not set we use the basename of `argv[1]`.
346
+
347
+ #### cli.command(name, description, config?)
348
+
349
+ - Type: `(name: string, description: string) => Command`
350
+
351
+ Create a command instance.
352
+
353
+ The option also accepts a third argument `config` for additional command config:
354
+
355
+ - `config.allowUnknownOptions`: `boolean` Allow unknown options in this command.
356
+ - `config.ignoreOptionDefaultValue`: `boolean` Don't use the options's default value in parsed options, only display them in help message.
357
+
358
+ #### cli.option(name, description, config?)
359
+
360
+ - Type: `(name: string, description: string, config?: OptionConfig) => CLI`
361
+
362
+ Add a global option.
363
+
364
+ The option also accepts a third argument `config` for additional option config:
365
+
366
+ - `config.default`: Default value for the option.
367
+ - `config.type`: `any[]` When set to `[]`, the option value returns an array type. You can also use a conversion function such as `[String]`, which will invoke the option value with `String`.
368
+
369
+ #### cli.parse(argv?)
370
+
371
+ - Type: `(argv = process.argv) => ParsedArgv`
372
+
373
+ ```ts
374
+ interface ParsedArgv {
375
+ args: string[]
376
+ options: {
377
+ [k: string]: any
378
+ }
379
+ }
380
+ ```
381
+
382
+ When this method is called, `cli.rawArgs` `cli.args` `cli.options` `cli.matchedCommand` will also be available.
383
+
384
+ #### cli.version(version, customFlags?)
385
+
386
+ - Type: `(version: string, customFlags = '-v, --version') => CLI`
387
+
388
+ Output version number when `-v, --version` flag appears.
389
+
390
+ #### cli.help(callback?)
391
+
392
+ - Type: `(callback?: HelpCallback) => CLI`
393
+
394
+ Output help message when `-h, --help` flag appears.
395
+
396
+ Optional `callback` allows post-processing of help text before it is displayed:
397
+
398
+ ```ts
399
+ type HelpCallback = (sections: HelpSection[]) => void
400
+
401
+ interface HelpSection {
402
+ title?: string
403
+ body: string
404
+ }
405
+ ```
406
+
407
+ #### cli.outputHelp()
408
+
409
+ - Type: `() => CLI`
410
+
411
+ Output help message.
412
+
413
+ #### cli.usage(text)
414
+
415
+ - Type: `(text: string) => CLI`
416
+
417
+ Add a global usage text. This is not used by sub-commands.
418
+
419
+ ### Command Instance
420
+
421
+ Command instance is created by invoking the `cli.command` method:
422
+
423
+ ```js
424
+ const command = cli.command('build [...files]', 'Build given files')
425
+ ```
426
+
427
+ #### command.option()
428
+
429
+ Basically the same as `cli.option` but this adds the option to specific command.
430
+
431
+ #### command.action(callback)
432
+
433
+ - Type: `(callback: ActionCallback) => Command`
434
+
435
+ Use a callback function as the command action when the command matches user inputs.
436
+
437
+ ```ts
438
+ type ActionCallback = (
439
+ // Parsed CLI args
440
+ // The last arg will be an array if it's a variadic argument
441
+ ...args: string | string[] | number | number[]
442
+ // Parsed CLI options
443
+ options: Options
444
+ ) => any
445
+
446
+ interface Options {
447
+ [k: string]: any
448
+ }
449
+ ```
450
+
451
+ #### command.alias(name)
452
+
453
+ - Type: `(name: string) => Command`
454
+
455
+ Add an alias name to this command, the `name` here can't contain brackets.
456
+
457
+ #### command.allowUnknownOptions()
458
+
459
+ - Type: `() => Command`
460
+
461
+ Allow unknown options in this command, by default CAC will log an error when unknown options are used.
462
+
463
+ #### command.example(example)
464
+
465
+ - Type: `(example: CommandExample) => Command`
466
+
467
+ Add an example which will be displayed at the end of help message.
468
+
469
+ ```ts
470
+ type CommandExample = ((name: string) => string) | string
471
+ ```
472
+
473
+ #### command.usage(text)
474
+
475
+ - Type: `(text: string) => Command`
476
+
477
+ Add a usage text for this command.
478
+
479
+ ### Events
480
+
481
+ Listen to commands:
482
+
483
+ ```js
484
+ // Listen to the `foo` command
485
+ cli.on('command:foo', () => {
486
+ // Do something
487
+ })
488
+
489
+ // Listen to the default command
490
+ cli.on('command:!', () => {
491
+ // Do something
492
+ })
493
+
494
+ // Listen to unknown commands
495
+ cli.on('command:*', () => {
496
+ console.error('Invalid command: %s', cli.args.join(' '))
497
+ process.exit(1)
498
+ })
499
+ ```
500
+
501
+ ## FAQ
502
+
503
+ ### How is the name written and pronounced?
504
+
505
+ CAC, or cac, pronounced `C-A-C`.
506
+
507
+ This project is dedicated to our lovely C.C. sama. Maybe CAC stands for C&C as well :P
508
+
509
+ <img src="http://i.giphy.com/v3FeH4swox9mg.gif" width="400"/>
510
+
511
+ ### Why not use Commander.js?
512
+
513
+ CAC is very similar to Commander.js, while the latter does not support dot nested options, i.e. something like `--env.API_SECRET foo`. Besides, you can't use unknown options in Commander.js either.
514
+
515
+ _And maybe more..._
516
+
517
+ Basically I made CAC to fulfill my own needs for building CLI apps like [Poi](https://poi.js.org), [SAO](https://sao.vercel.app) and all my CLI apps. It's small, simple but powerful :P
518
+
519
+ ## Project Stats
520
+
521
+ ![Alt](https://repobeats.axiom.co/api/embed/58caf6203631bcdb9bbe22f0728a0af1683dc0bb.svg 'Repobeats analytics image')
522
+
523
+ ## Contributing
524
+
525
+ 1. Fork it!
526
+ 2. Create your feature branch: `git checkout -b my-new-feature`
527
+ 3. Commit your changes: `git commit -am 'Add some feature'`
528
+ 4. Push to the branch: `git push origin my-new-feature`
529
+ 5. Submit a pull request :D
530
+
531
+ ## Author
532
+
533
+ **CAC** © [EGOIST](https://github.com/egoist), Released under the [MIT](./LICENSE) License.<br>
534
+ Authored and maintained by egoist with help from contributors ([list](https://github.com/cacjs/cac/contributors)).
535
+
536
+ > [Website](https://egoist.dev) · GitHub [@egoist](https://github.com/egoist) · Twitter [@\_egoistlily](https://twitter.com/_egoistlily)