Command And Conquer is a JavaScript library for building CLI apps.
cli.option
cli.version
cli.help
cli.parse
.yarn add cac
Use CAC as simple argument parser:
<img width="500" alt="2018-11-26 12 28 03" src="https://user-images.githubusercontent.com/8784712/48981576-2a871000-f112-11e8-8151-80f61e9b9908.png">// 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))
<img width="500" alt="2018-11-25 8 21 14" src="https://user-images.githubusercontent.com/8784712/48979012-acb20d00-f0ef-11e8-9cc6-8ffca00ab78a.png">// 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()
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
.
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
.
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()
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
.
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:
<img width="500" alt="2018-11-25 8 25 30" src="https://user-images.githubusercontent.com/8784712/48979056-47125080-f0f0-11e8-9d8f-3219e0beb0ed.png">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.
<img width="500" alt="2018-11-25 9 37 53" src="https://user-images.githubusercontent.com/8784712/48979771-6ada9400-f0fa-11e8-8192-e541b2cfd9da.png">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()
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'] }
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) }
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'
import { cac } from 'https://unpkg.com/cac/mod.ts' const cli = cac('my-program')
Projects that use CAC:
💁 Check out the generated docs from source code if you want a more in-depth API references.
Below is a brief overview.
CLI instance is created by invoking the cac
function:
const cac = require('cac') const cli = cac()
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]
.
(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.(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
.(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 }
() => CLI
Output help message.
(text: string) => CLI
Add a global usage text. This is not used by sub-commands.
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 a variadic 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 = ((name: string) => string) | string
(text: string) => Command
Add a usage text for this command.
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) })
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
<img src="http://i.giphy.com/v3FeH4swox9mg.gif" width="400"/>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
字节跳动发布的AI编程神器IDE
Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。
全能AI智能助手,随时解答生活与工作的多样问题
问小白,由元石科技研发的AI智能助手,快速准确地解答各种生活和工作问题,包括但不限于搜索、规划和社交互动,帮助用户在日常生活中提高效率,轻松管理个人事务。
实时语音翻译/同声传译工具
Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。
一键生成PPT和Word,让学习生活更轻松
讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。
深度推理能力全新升级,全面对标OpenAI o1
科大讯飞的星火大模型,支持语言理解、知识问答和文本创作等多功能,适用于多种文件和业务场景,提升办公和日常生活的效率。讯飞星火是一个提供丰富智能服务的平台,涵盖科技资讯、图像创作、写作辅助、编程解答、科研文献解读等功能,能为不同需求的用户提供便捷高效的帮助,助力用户轻松获取信息、解决问题,满足多样化使用场景。
一种基于大语言模型的高效单流解耦语音令牌文本到语音合成模型
Spark-TTS 是一个基于 PyTorch 的开源文本到语音合成项目,由多个知名机构联合参与。该项目提供了高效的 LLM(大语言模型)驱动的语音合成方案,支持语音克隆和语音创建功能,可通过命令行界面(CLI)和 Web UI 两种方式使用。用户可以根据需求调整语音的性别、音高、速度等参数,生成高质量的语音。该项目适用于多种场景,如有声读物制作、智能语音助手开发等。
AI助力,做PPT更简单!
咔片是一款轻量化在线演示设计工具,借助 AI 技术,实现从内容生成到智能设计的一站式 PPT 制作服务。支持多种文档格式导入生成 PPT,提供海量模板、智能美化、素材替换等功能,适用于销售、教师、学生等各类人群,能高效制作出高品质 PPT,满足不同场景演示需求。
选题、配图、成文,一站式创作,让内容运营更高效
讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。
专业的AI公文写作平台,公文写作神器
AI 材料星,专业的 AI 公文写作辅助平台,为体制内工作人员提供高效的公文写作解决方案。拥有海量公文文库、9 大核心 AI 功能,支持 30 + 文稿类型生成,助力快速完成领导讲话、工作总结、述职报告等材料,提升办公效率,是体制打工人的得力写作神器。
OpenAI Agents SDK,助力开发者便捷使用 OpenAI 相关功能。
openai-agents-python 是 OpenAI 推出的一款强大 Python SDK,它为开发者提供了与 OpenAI 模型交互的高效工具,支持工具调用、结果处理、追踪等功能,涵盖多种应用场景,如研究助手、财务研究等,能显著提升开发效率,让开发者更轻松地利用 OpenAI 的技术优势。
最新AI工具、AI资讯
独家AI资源、AI项目落地
微信扫一扫关注公众号