CAC

Simple yet powerful framework for building command-line apps.

README

2017-07-26 9 27 05
NPM version NPM downloads CircleCI Codecov donate chat install size

Introduction


Command And Conquer is a JavaScript library for building CLI apps.

Features


- Super light-weight: No dependency, just a single file.
- Easy to learn. There're only 4 APIs you need to learn for building simple CLIs: cli.option cli.version cli.help cli.parse.
- 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.
- Developer friendly. Written in TypeScript.

Table of Contents




  - Brackets
  - With Deno
    - cac(name?)
    - cli.usage(text)
  - Events
- FAQ



Install


  1. ``` sh
  2. yarn add cac
  3. ```

Usage


Simple Parsing


Use CAC as simple argument parser:

  1. ``` js
  2. // examples/basic-usage.js
  3. const cli = require('cac')()

  4. cli.option('--type <type>', 'Choose a project type', {
  5.   default: 'node',
  6. })

  7. const parsed = cli.parse()

  8. console.log(JSON.stringify(parsed, null, 2))
  9. ```

2018-11-26 12 28 03

Display Help Message and Version


  1. ``` js
  2. // examples/help.js
  3. const cli = require('cac')()

  4. cli.option('--type [type]', 'Choose a project type', {
  5.   default: 'node',
  6. })
  7. cli.option('--name <name>', 'Provide your name')

  8. cli.command('lint [...files]', 'Lint files').action((files, options) => {
  9.   console.log(files, options)
  10. })

  11. // Display help message when `-h` or `--help` appears
  12. cli.help()
  13. // Display version number when `-v` or `--version` appears
  14. // It's also used in help message
  15. cli.version('0.0.0')

  16. cli.parse()
  17. ```

2018-11-25 8 21 14

Command-specific Options


You can attach options to a command.

  1. ``` js
  2. const cli = require('cac')()

  3. cli
  4.   .command('rm <dir>', 'Remove a dir')
  5.   .option('-r, --recursive', 'Remove recursively')
  6.   .action((dir, options) => {
  7.     console.log('remove ' + dir + (options.recursive ? ' recursively' : ''))
  8.   })

  9. cli.help()

  10. cli.parse()
  11. ```

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).

command options

Dash in option names


Options in kebab-case should be referenced in camelCase in your code:

  1. ``` js
  2. cli
  3.   .command('dev', 'Start dev server')
  4.   .option('--clear-screen', 'Clear screen')
  5.   .action((options) => {
  6.     console.log(options.clearScreen)
  7.   })
  8. ```

In fact --clear-screen and --clearScreen are both mapped to options.clearScreen.

Brackets


When using brackets in command name, angled brackets indicate required command arguments, while square bracket indicate optional arguments.

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.

  1. ``` js
  2. const cli = require('cac')()

  3. cli
  4.   .command('deploy <folder>', 'Deploy a folder to AWS')
  5.   .option('--scale [level]', 'Scaling level')
  6.   .action((folder, options) => {
  7.     // ...
  8.   })

  9. cli
  10.   .command('build [project]', 'Build a project')
  11.   .option('--out <dir>', 'Output directory')
  12.   .action((folder, options) => {
  13.     // ...
  14.   })

  15. cli.parse()
  16. ```

Negated Options


To allow an option whose value is false, you need to manually specify a negated option:

  1. ``` js
  2. cli
  3.   .command('build [project]', 'Build a project')
  4.   .option('--no-config', 'Disable config file')
  5.   .option('--config <path>', 'Use a custom config file')
  6. ```

This will let CAC set the default value of config to true, and you can use --no-config flag to set it to false.

Variadic Arguments


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:

  1. ``` js
  2. const cli = require('cac')()

  3. cli
  4.   .command('build <entry> [...otherFiles]', 'Build your app')
  5.   .option('--foo', 'Foo option')
  6.   .action((entry, otherFiles, options) => {
  7.     console.log(entry)
  8.     console.log(otherFiles)
  9.     console.log(options)
  10.   })

  11. cli.help()

  12. cli.parse()
  13. ```

2018-11-25 8 25 30

Dot-nested Options


Dot-nested options will be merged into a single option.

  1. ``` js
  2. const cli = require('cac')()

  3. cli
  4.   .command('build', 'desc')
  5.   .option('--env <env>', 'Set envs')
  6.   .example('--env.API_SECRET xxx')
  7.   .action((options) => {
  8.     console.log(options)
  9.   })

  10. cli.help()

  11. cli.parse()
  12. ```

2018-11-25 9 37 53

Default Command


Register a command that will be used when no other command is matched.

  1. ``` js
  2. const cli = require('cac')()

  3. cli
  4.   // Simply omit the command name, just brackets
  5.   .command('[...files]', 'Build files')
  6.   .option('--minimize', 'Minimize output')
  7.   .action((files, options) => {
  8.     console.log(files)
  9.     console.log(options.minimize)
  10.   })

  11. cli.parse()
  12. ```

Supply an array as option value


  1. ``` sh
  2. node cli.js --include project-a
  3. # The parsed options will be:
  4. # { include: 'project-a' }

  5. node cli.js --include project-a --include project-b
  6. # The parsed options will be:
  7. # { include: ['project-a', 'project-b'] }
  8. ```

Error Handling


To handle command errors globally:

  1. ``` js
  2. try {
  3.   // Parse CLI args without running the command
  4.   cli.parse(process.argv, { run: false })
  5.   // Run the command yourself
  6.   // You only need `await` when your command action returns a Promise
  7.   await cli.runMatchedCommand()
  8. } catch (error) {
  9.   // Handle error here..
  10.   // e.g.
  11.   // console.error(error.stack)
  12.   // process.exit(1)
  13. }
  14. ```

With TypeScript


First you need @types/node to be installed as a dev dependency in your project:

  1. ``` sh
  2. yarn add @types/node --dev
  3. ```

Then everything just works out of the box:

  1. ``` js
  2. const { cac } = require('cac')
  3. // OR ES modules
  4. import { cac } from 'cac'
  5. ```

With Deno


  1. ```ts
  2. import { cac } from 'https://unpkg.com/cac/mod.ts'

  3. const cli = cac('my-program')
  4. ```

Projects Using CAC


Projects that use CAC:

- VuePress: :memo: Minimalistic Vue-powered static site generator.
- SAO: ⚔️ Futuristic scaffolding tool.
- DocPad: 🏹 Powerful Static Site Generator.
- Poi: ⚡️ Delightful web development.
- bili: 🥂 Schweizer Armeemesser for bundling JavaScript libraries.
- Lad: 👦 Lad scaffolds a Koa webapp and API framework for Node.js.
- Lass: 💁🏻 Scaffold a modern package boilerplate for Node.js.
- Foy: 🏗 A lightweight and modern task runner and build tool for general purpose.
- Vuese: 🤗 One-stop solution for vue component documentation.
- NUT: 🌰 A framework born for microfrontends
- Feel free to add yours here...

References


💁 Check out the generated docs from source code if you want a more in-depth API references.

Below is a brief overview.

CLI Instance


CLI instance is created by invoking the cac function:

  1. ``` js
  2. const cac = require('cac')
  3. const cli = cac()
  4. ```

cac(name?)


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].

cli.command(name, description, config?)


- Type: (name: string, description: string) => Command

Create a command instance.

The option also accepts a third argument config for additional command config:

- config.allowUnknownOptions: boolean Allow unknown options in this command.
- config.ignoreOptionDefaultValue: boolean Don't use the options's default value in parsed options, only display them in help message.

cli.option(name, description, config?)


- Type: (name: string, description: string, config?: OptionConfig) => CLI

Add a global option.

The option also accepts a third argument config for additional option config:

- config.default: Default value for the option.
- 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.

cli.parse(argv?)


- Type: (argv = process.argv) => ParsedArgv

  1. ```ts
  2. interface ParsedArgv {
  3.   args: string[]
  4.   options: {
  5.     [k: string]: any
  6.   }
  7. }
  8. ```

When this method is called, cli.rawArgs cli.args cli.options cli.matchedCommand will also be available.

cli.version(version, customFlags?)


- Type: (version: string, customFlags = '-v, --version') => CLI

Output version number when -v, --version flag appears.

cli.help(callback?)


- Type: (callback?: HelpCallback) => CLI

Output help message when -h, --help flag appears.

Optional callback allows post-processing of help text before it is displayed:

  1. ```ts
  2. type HelpCallback = (sections: HelpSection[]) => void

  3. interface HelpSection {
  4.   title?: string
  5.   body: string
  6. }
  7. ```

cli.outputHelp()


- Type: () => CLI

Output help message.

cli.usage(text)


- Type: (text: string) => CLI

Add a global usage text. This is not used by sub-commands.

Command Instance


Command instance is created by invoking the cli.command method:

  1. ``` js
  2. const command = cli.command('build [...files]', 'Build given files')
  3. ```

command.option()


Basically the same as cli.option but this adds the option to specific command.

command.action(callback)


- Type: (callback: ActionCallback) => Command

Use a callback function as the command action when the command matches user inputs.

  1. ```ts
  2. type ActionCallback = (
  3.   // Parsed CLI args
  4.   // The last arg will be an array if it's a variadic argument
  5.   ...args: string | string[] | number | number[]
  6.   // Parsed CLI options
  7.   options: Options
  8. ) => any

  9. interface Options {
  10.   [k: string]: any
  11. }
  12. ```

command.alias(name)


- Type: (name: string) => Command

Add an alias name to this command, the name here can't contain brackets.

command.allowUnknownOptions()


- Type: () => Command

Allow unknown options in this command, by default CAC will log an error when unknown options are used.

command.example(example)


- Type: (example: CommandExample) => Command

Add an example which will be displayed at the end of help message.

  1. ```ts
  2. type CommandExample = ((name: string) => string) | string
  3. ```

command.usage(text)


- Type: (text: string) => Command

Add a usage text for this command.

Events


Listen to commands:

  1. ``` js
  2. // Listen to the `foo` command
  3. cli.on('command:foo', () => {
  4.   // Do something
  5. })

  6. // Listen to the default command
  7. cli.on('command:!', () => {
  8.   // Do something
  9. })

  10. // Listen to unknown commands
  11. cli.on('command:*', () => {
  12.   console.error('Invalid command: %s', cli.args.join(' '))
  13.   process.exit(1)
  14. })
  15. ```

FAQ


How is the name written and pronounced?


CAC, or cac, pronounced C-A-C.

This project is dedicated to our lovely C.C. sama. Maybe CAC stands for C&C as well :P


Why not use Commander.js?


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.

_And maybe more..._

Basically I made CAC to fulfill my own needs for building CLI apps like Poi, SAO and all my CLI apps. It's small, simple but powerful :P

Project Stats


Alt

Contributing


1. Fork it!
2. Create your feature branch: git checkout -b my-new-feature
3. Commit your changes: git commit -am 'Add some feature'
4. Push to the branch: git push origin my-new-feature
5. Submit a pull request :D

Author


**CAC** © [EGOIST](https://github.com/egoist), Released under the [MIT](./LICENSE) License.
Authored and maintained by egoist with help from contributors (list).

Website · GitHub @egoist · Twitter @\_egoistlily