What is cac?
The cac npm package is a simple yet powerful framework for building command-line applications. It allows developers to parse arguments, generate help messages, and create commands with options and sub-commands.
What are cac's main functionalities?
Command Parsing
This feature allows you to define commands with required and optional arguments. The code sample demonstrates how to create a command 'init' that requires a project name and accepts an optional type argument.
{"const cac = require('cac');\nconst cli = cac();\ncli.command('init <name>', 'Initialize a project')\n .option('--type <type>', 'Project type')\n .action((name, options) => {\n console.log(`Initializing project: ${name} with type: ${options.type}`);\n });\ncli.help();\ncli.parse();"}
Help Generation
Automatically generates help information for the defined commands and options. The code sample shows how to define a 'build' command and an option to minify the output, with automatic help generation.
{"const cac = require('cac');\nconst cli = cac();\ncli.command('build', 'Build the project')\n .option('--minify', 'Minify the output')\ncli.help();\ncli.parse();"}
Sub-commands
Supports the creation of sub-commands for more complex CLI structures. The code sample illustrates how to create a 'deploy' command with sub-commands for different deployment providers like AWS and Azure.
{"const cac = require('cac');\nconst cli = cac();\nconst deploy = cli.command('deploy <provider>', 'Deploy your project');\ndeploy.command('aws', 'Deploy to AWS')\n .action(() => {\n console.log('Deploying to AWS...');\n });\ndeploy.command('azure', 'Deploy to Azure')\n .action(() => {\n console.log('Deploying to Azure...');\n });\ncli.help();\ncli.parse();"}
Other packages similar to cac
commander
Commander is one of the most popular npm packages for building command-line interfaces. It offers similar functionalities to cac, such as command parsing, option management, and automatic help generation. Commander has a more extensive feature set and a larger community, but cac is known for its simplicity and ease of use.
yargs
Yargs is another well-known package for building command-line tools. It provides a rich API for argument parsing, command chaining, and validation. Yargs is more verbose and configurable compared to cac, which might be preferred for more complex CLI applications.
meow
Meow is a lightweight CLI helper with a minimalistic approach. It is less feature-rich than cac but is very straightforward to use for simple command-line applications. Meow is a good choice for those who need something simpler than cac and do not require complex command structures.
Introduction
Command And Conquer, the queen living in your command line, is a minimalistic but pluggable CLI framework.
Install
yarn add cac
Table of contents
Usage
Use ./examples/simple.js
as example:
const cac = require('cac')
const cli = cac()
const defaultCommand = cli.command('*', {
desc: 'The default command'
}, (input, flags) => {
if (flags.age) {
console.log(`${input[0]} is ${flags.age} years old`)
}
})
defaultCommand.option('age', {
desc: 'tell me the age'
})
cli.command('bob', {
desc: 'Command for bob'
}, () => {
console.log('This is a command dedicated to bob!')
})
cli.parse()
Then run it:
And the Help Documentation is ready out of the box:
Friends
Projects that use CAC:
- SAO: ⚔️ Futuristic scaffolding tool.
- Poi: ⚡️ Delightful web development.
- bili: 🥂 Schweizer Armeemesser for bundling JavaScript libraries.
- lass: 💁🏻 Scaffold a modern package boilerplate for Node.js.
- Feel free to add yours here...
Documentation
cli.option(name, [option])
Register an option globally, i.e. for all commands
- name:
string
option name - option:
object
string
- desc:
string
description - alias:
string
Array<string>
option name alias - type:
string
option type, valid values: boolean
string
- default:
any
option default value - required:
boolean
mark option as required - choices:
Array<any>
limit valid values for the option
cli.command(name, [option], [handler])
- name:
string
- option:
object
string
(string
is used as desc
)
- desc:
string
description - alias:
string
Array<string>
command name alias - examples:
Array<string>
command examples
- handler:
function
command handler
- input:
Array<string>
cli arguments - flags:
object
cli flags
const command = cli.command('init', 'init a new project', (input, flags) => {
const folderName = input[0]
console.log(`init project in folder ${folderName}`)
})
cli.command
returns a command instance.
command
command.option(name, [option])
Same as cli.option but it adds options for specified command.
cli.parse([argv], [option])
- argv:
Array<string>
Defaults to process.argv.slice(2)
- option
- run:
boolean
Defaults to true
Run command after parsed argv.
cli.showHelp()
Display cli helps, must be called after cli.parse()
cli.use(plugin)
- plugin:
Plugin
Array<Plugin>
Apply a plugin to cli instance:
cli.use(plugin(options))
function plugin(options) {
return cli => {
}
}
cli.bin
Type: string
The filename of executed file.
e.g. It's cli.js
when you run node ./cli.js
.
cli.argv
A getter which simply returns cli.parse(null, { run: false })
Add extra help messages to the bottom of help.
help
Type: string
object
The help
could be a string
or in { title, body }
format.
Events
error
Error handler for errors in your command handler:
cli.on('error', err => {
console.error('command failed:', err)
process.exit(1)
})
parsed
Emit after CAC parsed cli arguments:
cli.on('parsed', (command, input, flags) => {
})
executed
Emit after CAC executed commands or outputed help / version number:
cli.on('executed', (command, input, flags) => {
})
FAQ
Why not commander.js
yargs
caporal.js
or meow
?
CAC
is simpler and less opinionated comparing to commander.js
yargs
caporal.js
.
Commander.js does not support chaining option which is a feature I like a lot. It's not really actively maintained at the time of writing either.
Yargs has a powerful API, but it's so massive that my brain trembles. Meow is simple and elegant but I have to manully construct the help message, which will be annoying. And I want it to support sub-command too.
And none of them are pluggable.
So why creating a new thing instead of pull request?
I would ask me myself why there's preact
instead of PR to react
, and why yarn
instead of PR to npm
? It's obvious.
CAC is kind of like a combination of the simplicity of Meow and the powerful features of the rest. And our help log is inspired by Caporal.js, I guess it might be the most elegant one out there?
How is the name written and pronounced?
CAC, not Cac or cac, pronounced C-A-C
.
And this project is dedicated to our lovely C.C. sama. Maybe CAC stands for C&C as well :P
Contributing
- Fork it!
- Create your feature branch:
git checkout -b my-new-feature
- Commit your changes:
git commit -am 'Add some feature'
- Push to the branch:
git push origin my-new-feature
- Submit a pull request :D
Author
cac © egoist, Released under the MIT License.
Authored and maintained by egoist with help from contributors (list).
egoist.moe · GitHub @egoist · Twitter @_egoistlily