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) [![chat](https://img.shields.io/badge/chat-on%20discord-7289DA.svg?style=flat)](https://chat.egoist.moe) [![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 |
|
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 | - [Brackets](#brackets)
|
26 | - [Variadic Arguments](#variadic-arguments)
|
27 | - [Dot-nested Options](#dot-nested-options)
|
28 | - [Default Command](#default-command)
|
29 | - [Supply an array as option value](#supply-an-array-as-option-value)
|
30 | - [With TypeScript](#with-typescript)
|
31 | - [With Deno](#with-deno)
|
32 | - [Projects Using CAC](#projects-using-cac)
|
33 | - [References](#references)
|
34 | - [CLI Instance](#cli-instance)
|
35 | - [cac(name?)](#cacname)
|
36 | - [cli.command(name, description, config?)](#clicommandname-description-config)
|
37 | - [cli.option(name, description, config?)](#clioptionname-description-config)
|
38 | - [cli.parse(argv?)](#cliparseargv)
|
39 | - [cli.version(version, customFlags?)](#cliversionversion-customflags)
|
40 | - [cli.help(callback?)](#clihelpcallback)
|
41 | - [cli.outputHelp(subCommand?)](#clioutputhelpsubcommand)
|
42 | - [Command Instance](#command-instance)
|
43 | - [command.option()](#commandoption)
|
44 | - [command.action(callback)](#commandactioncallback)
|
45 | - [command.alias(name)](#commandaliasname)
|
46 | - [command.allowUnknownOptions()](#commandallowunknownoptions)
|
47 | - [command.example(example)](#commandexampleexample)
|
48 | - [Events](#events)
|
49 | - [FAQ](#faq)
|
50 | - [How is the name written and pronounced?](#how-is-the-name-written-and-pronounced)
|
51 | - [Why not use Commander.js?](#why-not-use-commanderjs)
|
52 | - [Contributing](#contributing)
|
53 | - [Author](#author)
|
54 |
|
55 |
|
56 |
|
57 | ## Install
|
58 |
|
59 | ```bash
|
60 | yarn add cac
|
61 | ```
|
62 |
|
63 | ## Usage
|
64 |
|
65 | ### Simple Parsing
|
66 |
|
67 | Use CAC as simple argument parser:
|
68 |
|
69 | ```js
|
70 | // examples/basic-usage.js
|
71 | const cli = require('cac')()
|
72 |
|
73 | cli.option('--type <type>', 'Choose a project type', {
|
74 | default: 'node'
|
75 | })
|
76 |
|
77 | const parsed = cli.parse()
|
78 |
|
79 | console.log(JSON.stringify(parsed, null, 2))
|
80 | ```
|
81 |
|
82 | <img width="500" alt="2018-11-26 12 28 03" src="https://user-images.githubusercontent.com/8784712/48981576-2a871000-f112-11e8-8151-80f61e9b9908.png">
|
83 |
|
84 | ### Display Help Message and Version
|
85 |
|
86 | ```js
|
87 | // examples/help.js
|
88 | const cli = require('cac')()
|
89 |
|
90 | cli.option('--type [type]', 'Choose a project type', {
|
91 | default: 'node'
|
92 | })
|
93 | cli.option('--name <name>', 'Provide your name')
|
94 |
|
95 | cli.command('lint [...files]', 'Lint files').action((files, options) => {
|
96 | console.log(files, options)
|
97 | })
|
98 |
|
99 | // Display help message when `-h` or `--help` appears
|
100 | cli.help()
|
101 | // Display version number when `-v` or `--version` appears
|
102 | // It's also used in help message
|
103 | cli.version('0.0.0')
|
104 |
|
105 | cli.parse()
|
106 | ```
|
107 |
|
108 | <img width="500" alt="2018-11-25 8 21 14" src="https://user-images.githubusercontent.com/8784712/48979012-acb20d00-f0ef-11e8-9cc6-8ffca00ab78a.png">
|
109 |
|
110 | ### Command-specific Options
|
111 |
|
112 | You can attach options to a command.
|
113 |
|
114 | ```js
|
115 | const cli = require('cac')()
|
116 |
|
117 | cli
|
118 | .command('rm <dir>', 'Remove a dir')
|
119 | .option('-r, --recursive', 'Remove recursively')
|
120 | .action((dir, options) => {
|
121 | console.log('remove ' + dir + (options.recursive ? ' recursively' : ''))
|
122 | })
|
123 |
|
124 | cli.help()
|
125 |
|
126 | cli.parse()
|
127 | ```
|
128 |
|
129 | 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).
|
130 |
|
131 | <img alt="command options" width="500" src="https://user-images.githubusercontent.com/8784712/49065552-49dc8500-f259-11e8-9c7b-a7c32d70920e.png">
|
132 |
|
133 | ### Brackets
|
134 |
|
135 | When using brackets in command name, angled brackets indicate required command arguments, while square bracket indicate optional arguments.
|
136 |
|
137 | 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`.
|
138 |
|
139 | ```js
|
140 | const cli = require('cac')()
|
141 |
|
142 | cli
|
143 | .command('deploy <folder>', 'Deploy a folder to AWS')
|
144 | .option('--scale [level]', 'Scaling level')
|
145 | .action((folder, options) => {
|
146 | // ...
|
147 | })
|
148 |
|
149 | cli
|
150 | .command('build [project]', 'Build a project')
|
151 | .option('--out <dir>', 'Output directory')
|
152 | .action((folder, options) => {
|
153 | // ...
|
154 | })
|
155 |
|
156 | cli.parse()
|
157 | ```
|
158 |
|
159 | To allow an option whose value is `false`, you need to manually speicfy a negated option:
|
160 |
|
161 | ```js
|
162 | cli
|
163 | .command('build [project]', 'Build a project')
|
164 | .option('--no-config', 'Disable config file')
|
165 | .option('--config <path>', 'Use a custom config file')
|
166 | ```
|
167 |
|
168 | This will let CAC set the default value of `config` to true, and you can use `--no-config` flag to set it to `false`.
|
169 |
|
170 | ### Variadic Arguments
|
171 |
|
172 | 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:
|
173 |
|
174 | ```js
|
175 | const cli = require('cac')()
|
176 |
|
177 | cli
|
178 | .command('build <entry> [...otherFiles]', 'Build your app')
|
179 | .option('--foo', 'Foo option')
|
180 | .action((entry, otherFiles, options) => {
|
181 | console.log(entry)
|
182 | console.log(otherFiles)
|
183 | console.log(options)
|
184 | })
|
185 |
|
186 | cli.help()
|
187 |
|
188 | cli.parse()
|
189 | ```
|
190 |
|
191 | <img width="500" alt="2018-11-25 8 25 30" src="https://user-images.githubusercontent.com/8784712/48979056-47125080-f0f0-11e8-9d8f-3219e0beb0ed.png">
|
192 |
|
193 | ### Dot-nested Options
|
194 |
|
195 | Dot-nested options will be merged into a single option.
|
196 |
|
197 | ```js
|
198 | const cli = require('cac')()
|
199 |
|
200 | cli
|
201 | .command('build', 'desc')
|
202 | .option('--env <env>', 'Set envs')
|
203 | .example('--env.API_SECRET xxx')
|
204 | .action(options => {
|
205 | console.log(options)
|
206 | })
|
207 |
|
208 | cli.help()
|
209 |
|
210 | cli.parse()
|
211 | ```
|
212 |
|
213 | <img width="500" alt="2018-11-25 9 37 53" src="https://user-images.githubusercontent.com/8784712/48979771-6ada9400-f0fa-11e8-8192-e541b2cfd9da.png">
|
214 |
|
215 | ### Default Command
|
216 |
|
217 | Register a command that will be used when no other command is matched.
|
218 |
|
219 | ```js
|
220 | const cli = require('cac')()
|
221 |
|
222 | cli
|
223 | // Simply omit the command name, just brackets
|
224 | .command('[...files]', 'Build files')
|
225 | .option('--minimize', 'Minimize output')
|
226 | .action((files, options) => {
|
227 | console.log(files)
|
228 | console.log(options.minimize)
|
229 | })
|
230 |
|
231 | cli.parse()
|
232 | ```
|
233 |
|
234 | ### Supply an array as option value
|
235 |
|
236 | ```bash
|
237 | node cli.js --include project-a
|
238 | # The parsed options will be:
|
239 | # { include: 'project-a' }
|
240 |
|
241 | node cli.js --include project-a --include project-b
|
242 | # The parsed options will be:
|
243 | # { include: ['project-a', 'project-b'] }
|
244 | ```
|
245 |
|
246 | ### With TypeScript
|
247 |
|
248 | First you need `@types/node` to be installed as a dev dependency in your project:
|
249 |
|
250 | ```bash
|
251 | yarn add @types/node --dev
|
252 | ```
|
253 |
|
254 | Then everything just works out of the box:
|
255 |
|
256 | ```js
|
257 | const { cac } = require('cac')
|
258 | // OR ES modules
|
259 | import { cac } from 'cac'
|
260 | ```
|
261 |
|
262 | ### With Deno
|
263 |
|
264 | ```ts
|
265 | import { cac } from 'https://unpkg.com/cac/mod.js'
|
266 |
|
267 | // ...
|
268 | ```
|
269 |
|
270 | ## Projects Using CAC
|
271 |
|
272 | Projects that use **CAC**:
|
273 |
|
274 | - [VuePress](https://github.com/vuejs/vuepress): :memo: Minimalistic Vue-powered static site generator.
|
275 | - [SAO](https://github.com/egoist/sao): ⚔️ Futuristic scaffolding tool.
|
276 | - [DocPad](https://github.com/docpad/docpad): 🏹 Powerful Static Site Generator.
|
277 | - [Poi](https://github.com/egoist/poi): ⚡️ Delightful web development.
|
278 | - [bili](https://github.com/egoist/bili): 🥂 Schweizer Armeemesser for bundling JavaScript libraries.
|
279 | - [lass](https://github.com/lassjs/lass): 💁🏻 Scaffold a modern package boilerplate for Node.js.
|
280 | - [Foy](https://github.com/zaaack/foy): 🏗 A lightweight and modern task runner and build tool for general purpose.
|
281 | - Feel free to add yours here...
|
282 |
|
283 | ## References
|
284 |
|
285 | **💁 Check out [the generated docs](https://cac-api-doc.egoist.sh/classes/_cac_.cac.html) from source code if you want a more in-depth API references.**
|
286 |
|
287 | Below is a brief overview.
|
288 |
|
289 | ### CLI Instance
|
290 |
|
291 | CLI instance is created by invoking the `cac` function:
|
292 |
|
293 | ```js
|
294 | const { cac } = require('cac')
|
295 | const cli = cac()
|
296 | ```
|
297 |
|
298 | #### cac(name?)
|
299 |
|
300 | 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]`.
|
301 |
|
302 | #### cli.command(name, description, config?)
|
303 |
|
304 | - Type: `(name: string, description: string) => Command`
|
305 |
|
306 | Create a command instance.
|
307 |
|
308 | The option also accepts a third argument `config` for additional command config:
|
309 |
|
310 | - `config.allowUnknownOptions`: `boolean` Allow unknown options in this command.
|
311 | - `config.ignoreOptionDefaultValue`: `boolean` Don't use the options's default value in parsed options, only display them in help message.
|
312 |
|
313 | #### cli.option(name, description, config?)
|
314 |
|
315 | - Type: `(name: string, description: string, config?: OptionConfig) => CLI`
|
316 |
|
317 | Add a global option.
|
318 |
|
319 | The option also accepts a third argument `config` for additional option config:
|
320 |
|
321 | - `config.default`: Default value for the option.
|
322 | - `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`.
|
323 |
|
324 | #### cli.parse(argv?)
|
325 |
|
326 | - Type: `(argv = process.argv) => ParsedArgv`
|
327 |
|
328 | ```ts
|
329 | interface ParsedArgv {
|
330 | args: string[]
|
331 | options: {
|
332 | [k: string]: any
|
333 | }
|
334 | }
|
335 | ```
|
336 |
|
337 | When this method is called, `cli.rawArgs` `cli.args` `cli.options` `cli.matchedCommand` will also be available.
|
338 |
|
339 | #### cli.version(version, customFlags?)
|
340 |
|
341 | - Type: `(version: string, customFlags = '-v, --version') => CLI`
|
342 |
|
343 | Output version number when `-v, --version` flag appears.
|
344 |
|
345 | #### cli.help(callback?)
|
346 |
|
347 | - Type: `(callback?: HelpCallback) => CLI`
|
348 |
|
349 | Output help message when `-h, --help` flag appears.
|
350 |
|
351 | Optional `callback` allows post-processing of help text before it is displayed:
|
352 |
|
353 | ```ts
|
354 | type HelpCallback = (sections: HelpSection[]) => void
|
355 |
|
356 | interface HelpSection {
|
357 | title?: string
|
358 | body: string
|
359 | }
|
360 | ```
|
361 |
|
362 | #### cli.outputHelp(subCommand?)
|
363 |
|
364 | - Type: `(subCommand?: boolean) => CLI`
|
365 |
|
366 | Output help message. Optional `subCommand` argument if you want to output the help message for the matched sub-command instead of the global help message.
|
367 |
|
368 | ### Command Instance
|
369 |
|
370 | Command instance is created by invoking the `cli.command` method:
|
371 |
|
372 | ```js
|
373 | const command = cli.command('build [...files]', 'Build given files')
|
374 | ```
|
375 |
|
376 | #### command.option()
|
377 |
|
378 | Basically the same as `cli.option` but this adds the option to specific command.
|
379 |
|
380 | #### command.action(callback)
|
381 |
|
382 | - Type: `(callback: ActionCallback) => Command`
|
383 |
|
384 | Use a callback function as the command action when the command matches user inputs.
|
385 |
|
386 | ```ts
|
387 | type ActionCallback = (
|
388 | // Parsed CLI args
|
389 | // The last arg will be an array if it's an varadic argument
|
390 | ...args: string | string[] | number | number[]
|
391 | // Parsed CLI options
|
392 | options: Options
|
393 | ) => any
|
394 |
|
395 | interface Options {
|
396 | [k: string]: any
|
397 | }
|
398 | ```
|
399 |
|
400 | #### command.alias(name)
|
401 |
|
402 | - Type: `(name: string) => Command`
|
403 |
|
404 | Add an alias name to this command, the `name` here can't contain brackets.
|
405 |
|
406 | #### command.allowUnknownOptions()
|
407 |
|
408 | - Type: `() => Command`
|
409 |
|
410 | Allow unknown options in this command, by default CAC will log an error when unknown options are used.
|
411 |
|
412 | #### command.example(example)
|
413 |
|
414 | - Type: `(example: CommandExample) => Command`
|
415 |
|
416 | Add an example which will be displayed at the end of help message.
|
417 |
|
418 | ```ts
|
419 | type CommandExample = ((name: string) => string) | string
|
420 | ```
|
421 |
|
422 | ### Events
|
423 |
|
424 | Listen to commands:
|
425 |
|
426 | ```js
|
427 | // Listen to the `foo` command
|
428 | cli.on('command:foo', () => {
|
429 | // Do something
|
430 | })
|
431 |
|
432 | // Listen to the default command
|
433 | cli.on('command:!', () => {
|
434 | // Do something
|
435 | })
|
436 |
|
437 | // Listen to unknown commands
|
438 | cli.on('command:*', () => {
|
439 | console.error('Invalid command: %', cli.args.join(' '))
|
440 | process.exit(1)
|
441 | })
|
442 | ```
|
443 |
|
444 | ## FAQ
|
445 |
|
446 | ### How is the name written and pronounced?
|
447 |
|
448 | CAC, or cac, pronounced `C-A-C`.
|
449 |
|
450 | This project is dedicated to our lovely C.C. sama. Maybe CAC stands for C&C as well :P
|
451 |
|
452 | <img src="http://i.giphy.com/v3FeH4swox9mg.gif" width="400"/>
|
453 |
|
454 | ### Why not use Commander.js?
|
455 |
|
456 | 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.
|
457 |
|
458 | _And maybe more..._
|
459 |
|
460 | Basically I made CAC to fulfill my own needs for building CLI apps like [Poi](https://poi.js.org), [SAO](https://saojs.org) and all my CLI apps. It's small, simple but powerful :P
|
461 |
|
462 | ## Contributing
|
463 |
|
464 | 1. Fork it!
|
465 | 2. Create your feature branch: `git checkout -b my-new-feature`
|
466 | 3. Commit your changes: `git commit -am 'Add some feature'`
|
467 | 4. Push to the branch: `git push origin my-new-feature`
|
468 | 5. Submit a pull request :D
|
469 |
|
470 | ## Author
|
471 |
|
472 | **CAC** © [EGOIST](https://github.com/egoist), Released under the [MIT](./LICENSE) License.<br>
|
473 | Authored and maintained by egoist with help from contributors ([list](https://github.com/cacjs/cac/contributors)).
|
474 |
|
475 | > [Website](https://egoist.sh) · GitHub [@egoist](https://github.com/egoist) · Twitter [@\_egoistlily](https://twitter.com/_egoistlily)
|