Security News
RubyGems.org Adds New Maintainer Role
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
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.
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();"}
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 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 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.
Command And Conquer is a JavaScript library for building CLI apps.
yarn add cac
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))
// 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 `-h` or `--help` appears
cli.version('0.0.0')
cli.parse()
You can attach options to a command.
const cli = require('cac')()
cli
.command('rm <dir>')
.option('-r, --recursive', 'Remove recursively')
.action((dir, options) => {
console.log('remove ' + dir + (options.recursive ? ' recursively' : ''))
})
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
.
When using brackets in command name, angled brackets indicate required command arguments, while sqaure bracket indicate optional arguments.
When using brackets in option name, angled brackets indicate that the option value is required, while sqaure bracket indicate that the value is optional.
const cli = require('cac')()
cli
.command('deploy <folder>', 'Deploy a folder to AWS')
.option('--scale [level]', 'Scaling level')
.action((folder, options) => {
console.log(folder)
console.log(options)
})
cli.parse()
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()
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()
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()
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'
Projects that use CAC:
CLI instance is created by invoking the cac
function:
const cac = require('cac')
const cli = cac()
(name: string, description: string) => Command
Create a command instance.
(name: string, description: string, config?: OptionConfig) => CLI
Add a global option.
The option also accepts a third argument config
for addtional config:
config.default
: Default value for the option.config.coerce
: (value: any) => newValue
A function to process the option value.(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.
(version: string, customFlags = '-v, --version') => CLI
Output version number when -v, --version
flag appears.
(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
}
(subCommand?: boolean) => CLI
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.
Command instance is created by invoking the cli.command
method:
const command = cli.command('build [...files]', 'Build given files')
Basically the same as cli.option
but this adds the option to specific command.
(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 an varadic argument
...args: string | string[] | number | number[]
// Parsed CLI options
options: Options
) => any
interface Options {
[k: string]: any
}
(name: string) => Command
Add an alias name to this command, the name
here can't contain brackets.
() => Command
Allow unknown options in this command, by default CAC will log an error when unknown options are used.
(example: CommandExample) => Command
Add an example which will be displayed at the end of help message.
type CommandExample = ((bin: string) => string) | string
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: %', cli.args.join(' '))
process.exit(1)
})
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
git checkout -b my-new-feature
git commit -am 'Add some feature'
git push origin my-new-feature
CAC © EGOIST, Released under the MIT License.
Authored and maintained by egoist with help from contributors (list).
Website · GitHub @egoist · Twitter @_egoistlily
FAQs
Simple yet powerful framework for building command-line apps.
The npm package cac receives a total of 3,289,368 weekly downloads. As such, cac popularity was classified as popular.
We found that cac demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 3 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.
Security News
Research
Socket's threat research team has detected five malicious npm packages targeting Roblox developers, deploying malware to steal credentials and personal data.