cac
Command-line queen.
Last updated 7 years ago by rem .
MIT · Repository · Bugs · Original npm · Tarball · package.json
$ npm install cac 
SYNC missed versions from official npm registry.
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

Install

yarn add cac

Usage

Simple Parsing

Use CAC as simple argument parser:

// examples/basic-usage.js
const cli = require('cac')()

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

const parsed = cli.parse()

console.log(JSON.stringify(parsed, null, 2))
2018-11-26 12 28 03

Display Help Message and Version

// examples/help.js
const cli = require('cac')()

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

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

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

cli.parse()
2018-11-25 8 21 14

Command-specific Options

You can attach options to a command.

const cli = require('cac')()

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

cli.help()

cli.parse()

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.

command options

Dash in option names

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

cli
  .command('dev', 'Start dev server')
  .option('--clear-screen', 'Clear screen')
  .action((options) => {
    console.log(options.clearScreen)
  })

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.

const cli = require('cac')()

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

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

cli.parse()

Negated Options

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

cli
  .command('build [project]', 'Build a project')
  .option('--no-config', 'Disable config file')
  .option('--config <path>', 'Use a custom config file')

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:

const cli = require('cac')()

cli
  .command('build <entry> [...otherFiles]', 'Build your app')
  .option('--foo', 'Foo option')
  .action((entry, otherFiles, options) => {
    console.log(entry)
    console.log(otherFiles)
    console.log(options)
  })

cli.help()

cli.parse()
2018-11-25 8 25 30

Dot-nested Options

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

const cli = require('cac')()

cli
  .command('build', 'desc')
  .option('--env <env>', 'Set envs')
  .example('--env.API_SECRET xxx')
  .action((options) => {
    console.log(options)
  })

cli.help()

cli.parse()
2018-11-25 9 37 53

Default Command

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

const cli = require('cac')()

cli
  // Simply omit the command name, just brackets
  .command('[...files]', 'Build files')
  .option('--minimize', 'Minimize output')
  .action((files, options) => {
    console.log(files)
    console.log(options.minimize)
  })

cli.parse()

Supply an array as option value

node cli.js --include project-a
# The parsed options will be:
# { include: 'project-a' }

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

Error Handling

To handle command errors globally:

try {
  // Parse CLI args without running the command
  cli.parse(process.argv, { run: false })
  // Run the command yourself
  // You only need `await` when your command action returns a Promise
  await cli.runMatchedCommand()
} catch (error) {
  // Handle error here..
  // e.g.
  // console.error(error.stack)
  // process.exit(1)
}

With TypeScript

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

yarn add @types/node --dev

Then everything just works out of the box:

const { cac } = require('cac')
// OR ES modules
import { cac } from 'cac'

With Deno

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

const cli = cac('my-program')

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:

const cac = require('cac')
const cli = cac()

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
interface ParsedArgv {
  args: string[]
  options: {
    [k: string]: any
  }
}

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:

type HelpCallback = (sections: HelpSection[]) => void

interface HelpSection {
  title?: string
  body: string
}

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:

const command = cli.command('build [...files]', 'Build given files')

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.

type ActionCallback = (
  // Parsed CLI args
  // The last arg will be an array if it's a variadic argument
  ...args: string | string[] | number | number[]
  // Parsed CLI options
  options: Options
) => any

interface Options {
  [k: string]: any
}

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.

type CommandExample = ((name: string) => string) | string

command.usage(text)

  • Type: (text: string) => Command

Add a usage text for this command.

Events

Listen to commands:

// Listen to the `foo` command
cli.on('command:foo', () => {
  // Do something
})

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

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

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, Released under the MIT License.
Authored and maintained by egoist with help from contributors (list).

Website ยท GitHub @egoist ยท Twitter @_egoistlily

Current Tags

  • 6.7.14                                ...           latest (2 years ago)

120 Versions

  • 6.7.14                                ...           2 years ago
  • 6.7.13                                ...           2 years ago
  • 6.7.12                                ...           3 years ago
  • 6.7.11                                ...           3 years ago
  • 6.7.10                                ...           3 years ago
  • 6.7.9                                ...           3 years ago
  • 6.7.8                                ...           3 years ago
  • 6.7.7                                ...           3 years ago
  • 6.7.6                                ...           3 years ago
  • 6.7.5                                ...           3 years ago
  • 6.7.4                                ...           3 years ago
  • 6.7.3                                ...           4 years ago
  • 6.7.2                                ...           4 years ago
  • 6.7.1                                ...           4 years ago
  • 6.7.0                                ...           4 years ago
  • 6.6.1                                ...           4 years ago
  • 6.6.0                                ...           4 years ago
  • 6.5.13                                ...           4 years ago
  • 6.5.12                                ...           4 years ago
  • 6.5.11                                ...           4 years ago
  • 6.5.10                                ...           4 years ago
  • 6.5.9                                ...           5 years ago
  • 6.5.8                                ...           5 years ago
  • 6.5.7                                ...           5 years ago
  • 6.5.6                                ...           5 years ago
  • 6.5.5                                ...           5 years ago
  • 6.5.4                                ...           5 years ago
  • 6.5.3                                ...           5 years ago
  • 6.5.2                                ...           5 years ago
  • 6.5.1                                ...           6 years ago
  • 6.5.0                                ...           6 years ago
  • 6.4.3                                ...           6 years ago
  • 6.4.2                                ...           6 years ago
  • 6.4.1                                ...           6 years ago
  • 6.4.0                                ...           6 years ago
  • 6.3.12                                ...           6 years ago
  • 6.3.11                                ...           6 years ago
  • 6.3.10                                ...           6 years ago
  • 6.3.9                                ...           6 years ago
  • 6.3.8                                ...           6 years ago
  • 6.3.7                                ...           6 years ago
  • 6.3.6                                ...           6 years ago
  • 6.3.5                                ...           6 years ago
  • 6.3.4                                ...           6 years ago
  • 6.3.3                                ...           6 years ago
  • 6.3.2                                ...           6 years ago
  • 6.3.1                                ...           6 years ago
  • 6.3.0                                ...           6 years ago
  • 6.2.6                                ...           6 years ago
  • 6.2.5                                ...           6 years ago
  • 6.2.4                                ...           6 years ago
  • 6.2.3                                ...           6 years ago
  • 6.2.2                                ...           6 years ago
  • 6.2.1                                ...           6 years ago
  • 6.2.0                                ...           6 years ago
  • 6.1.3                                ...           6 years ago
  • 6.1.2                                ...           6 years ago
  • 6.1.1                                ...           6 years ago
  • 6.1.0                                ...           6 years ago
  • 6.0.2                                ...           6 years ago
  • 6.0.1                                ...           6 years ago
  • 6.0.0                                ...           6 years ago
  • 5.0.16                                ...           6 years ago
  • 5.0.15                                ...           6 years ago
  • 5.0.14                                ...           6 years ago
  • 5.0.13                                ...           6 years ago
  • 5.0.12                                ...           6 years ago
  • 5.0.11                                ...           6 years ago
  • 5.0.10                                ...           7 years ago
  • 5.0.9                                ...           7 years ago
  • 5.0.8                                ...           7 years ago
  • 5.0.7                                ...           7 years ago
  • 5.0.6                                ...           7 years ago
  • 5.0.5                                ...           7 years ago
  • 5.0.4                                ...           7 years ago
  • 5.0.3                                ...           7 years ago
  • 5.0.2                                ...           7 years ago
  • 5.0.1                                ...           7 years ago
  • 5.0.0                                ...           7 years ago
  • 4.4.4                                ...           7 years ago
  • 4.4.3                                ...           7 years ago
  • 4.4.2                                ...           7 years ago
  • 4.4.1                                ...           7 years ago
  • 4.4.0                                ...           7 years ago
  • 4.3.7                                ...           7 years ago
  • 4.3.6                                ...           7 years ago
  • 4.3.5                                ...           7 years ago
  • 4.3.4                                ...           7 years ago
  • 4.3.3                                ...           7 years ago
  • 4.3.2                                ...           7 years ago
  • 4.3.1                                ...           7 years ago
  • 4.3.0                                ...           7 years ago
  • 4.2.4                                ...           7 years ago
  • 4.2.3                                ...           7 years ago
  • 4.2.2                                ...           7 years ago
  • 4.2.1                                ...           7 years ago
  • 4.2.0                                ...           7 years ago
  • 4.1.1                                ...           7 years ago
  • 4.1.0                                ...           7 years ago
  • 4.0.0                                ...           7 years ago
  • 3.0.4                                ...           8 years ago
  • 3.0.3                                ...           8 years ago
  • 3.0.2                                ...           8 years ago
  • 3.0.1                                ...           8 years ago
  • 3.0.0                                ...           8 years ago
  • 2.3.2                                ...           8 years ago
  • 2.3.1                                ...           8 years ago
  • 2.3.0                                ...           8 years ago
  • 2.2.2                                ...           8 years ago
  • 2.2.1                                ...           8 years ago
  • 2.2.0                                ...           8 years ago
  • 2.1.1                                ...           8 years ago
  • 2.1.0                                ...           8 years ago
  • 2.0.3                                ...           8 years ago
  • 2.0.2                                ...           8 years ago
  • 2.0.1                                ...           8 years ago
  • 2.0.0                                ...           8 years ago
  • 1.0.0                                ...           9 years ago
  • 0.1.0                                ...           9 years ago
  • 0.0.0                                ...           9 years ago
Maintainers (2)
Downloads
Total 1
Today 0
This Week 0
This Month 0
Last Day 0
Last Week 0
Last Month 0
Dependencies (6)
Dev Dependencies (8)

© 2010 - cnpmjs.org x YWFE | Home | YWFE