版博士V2.0程序
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

README.md 15 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. <img width="945" alt="2017-07-26 9 27 05" src="https://user-images.githubusercontent.com/8784712/28623641-373450f4-7249-11e7-854d-1b076dab274d.png">
  2. [![NPM version](https://img.shields.io/npm/v/cac.svg?style=flat)](https://npmjs.com/package/cac) [![NPM downloads](https://img.shields.io/npm/dm/cac.svg?style=flat)](https://npmjs.com/package/cac) [![CircleCI](https://circleci.com/gh/cacjs/cac/tree/master.svg?style=shield)](https://circleci.com/gh/cacjs/cac/tree/master) [![Codecov](https://badgen.net/codecov/c/github/cacjs/cac/master)](https://codecov.io/gh/cacjs/cac) [![donate](https://img.shields.io/badge/$-donate-ff69b4.svg?maxAge=2592000&style=flat)](https://github.com/egoist/donate) [![chat](https://img.shields.io/badge/chat-on%20discord-7289DA.svg?style=flat)](https://chat.egoist.moe) [![install size](https://badgen.net/packagephobia/install/cac)](https://packagephobia.now.sh/result?p=cac)
  3. ## Introduction
  4. **C**ommand **A**nd **C**onquer is a JavaScript library for building CLI apps.
  5. ## Features
  6. - **Super light-weight**: No dependency, just a single file.
  7. - **Easy to learn**. There're only 4 APIs you need to learn for building simple CLIs: `cli.option` `cli.version` `cli.help` `cli.parse`.
  8. - **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.
  9. - **Developer friendly**. Written in TypeScript.
  10. ## Table of Contents
  11. <!-- toc -->
  12. - [Install](#install)
  13. - [Usage](#usage)
  14. - [Simple Parsing](#simple-parsing)
  15. - [Display Help Message and Version](#display-help-message-and-version)
  16. - [Command-specific Options](#command-specific-options)
  17. - [Dash in option names](#dash-in-option-names)
  18. - [Brackets](#brackets)
  19. - [Negated Options](#negated-options)
  20. - [Variadic Arguments](#variadic-arguments)
  21. - [Dot-nested Options](#dot-nested-options)
  22. - [Default Command](#default-command)
  23. - [Supply an array as option value](#supply-an-array-as-option-value)
  24. - [Error Handling](#error-handling)
  25. - [With TypeScript](#with-typescript)
  26. - [With Deno](#with-deno)
  27. - [Projects Using CAC](#projects-using-cac)
  28. - [References](#references)
  29. - [CLI Instance](#cli-instance)
  30. - [cac(name?)](#cacname)
  31. - [cli.command(name, description, config?)](#clicommandname-description-config)
  32. - [cli.option(name, description, config?)](#clioptionname-description-config)
  33. - [cli.parse(argv?)](#cliparseargv)
  34. - [cli.version(version, customFlags?)](#cliversionversion-customflags)
  35. - [cli.help(callback?)](#clihelpcallback)
  36. - [cli.outputHelp()](#clioutputhelp)
  37. - [cli.usage(text)](#cliusagetext)
  38. - [Command Instance](#command-instance)
  39. - [command.option()](#commandoption)
  40. - [command.action(callback)](#commandactioncallback)
  41. - [command.alias(name)](#commandaliasname)
  42. - [command.allowUnknownOptions()](#commandallowunknownoptions)
  43. - [command.example(example)](#commandexampleexample)
  44. - [command.usage(text)](#commandusagetext)
  45. - [Events](#events)
  46. - [FAQ](#faq)
  47. - [How is the name written and pronounced?](#how-is-the-name-written-and-pronounced)
  48. - [Why not use Commander.js?](#why-not-use-commanderjs)
  49. - [Project Stats](#project-stats)
  50. - [Contributing](#contributing)
  51. - [Author](#author)
  52. <!-- tocstop -->
  53. ## Install
  54. ```bash
  55. yarn add cac
  56. ```
  57. ## Usage
  58. ### Simple Parsing
  59. Use CAC as simple argument parser:
  60. ```js
  61. // examples/basic-usage.js
  62. const cli = require('cac')()
  63. cli.option('--type <type>', 'Choose a project type', {
  64. default: 'node',
  65. })
  66. const parsed = cli.parse()
  67. console.log(JSON.stringify(parsed, null, 2))
  68. ```
  69. <img width="500" alt="2018-11-26 12 28 03" src="https://user-images.githubusercontent.com/8784712/48981576-2a871000-f112-11e8-8151-80f61e9b9908.png">
  70. ### Display Help Message and Version
  71. ```js
  72. // examples/help.js
  73. const cli = require('cac')()
  74. cli.option('--type [type]', 'Choose a project type', {
  75. default: 'node',
  76. })
  77. cli.option('--name <name>', 'Provide your name')
  78. cli.command('lint [...files]', 'Lint files').action((files, options) => {
  79. console.log(files, options)
  80. })
  81. // Display help message when `-h` or `--help` appears
  82. cli.help()
  83. // Display version number when `-v` or `--version` appears
  84. // It's also used in help message
  85. cli.version('0.0.0')
  86. cli.parse()
  87. ```
  88. <img width="500" alt="2018-11-25 8 21 14" src="https://user-images.githubusercontent.com/8784712/48979012-acb20d00-f0ef-11e8-9cc6-8ffca00ab78a.png">
  89. ### Command-specific Options
  90. You can attach options to a command.
  91. ```js
  92. const cli = require('cac')()
  93. cli
  94. .command('rm <dir>', 'Remove a dir')
  95. .option('-r, --recursive', 'Remove recursively')
  96. .action((dir, options) => {
  97. console.log('remove ' + dir + (options.recursive ? ' recursively' : ''))
  98. })
  99. cli.help()
  100. cli.parse()
  101. ```
  102. 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).
  103. <img alt="command options" width="500" src="https://user-images.githubusercontent.com/8784712/49065552-49dc8500-f259-11e8-9c7b-a7c32d70920e.png">
  104. ### Dash in option names
  105. Options in kebab-case should be referenced in camelCase in your code:
  106. ```js
  107. cli
  108. .command('dev', 'Start dev server')
  109. .option('--clear-screen', 'Clear screen')
  110. .action((options) => {
  111. console.log(options.clearScreen)
  112. })
  113. ```
  114. In fact `--clear-screen` and `--clearScreen` are both mapped to `options.clearScreen`.
  115. ### Brackets
  116. When using brackets in command name, angled brackets indicate required command arguments, while square bracket indicate optional arguments.
  117. 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`.
  118. ```js
  119. const cli = require('cac')()
  120. cli
  121. .command('deploy <folder>', 'Deploy a folder to AWS')
  122. .option('--scale [level]', 'Scaling level')
  123. .action((folder, options) => {
  124. // ...
  125. })
  126. cli
  127. .command('build [project]', 'Build a project')
  128. .option('--out <dir>', 'Output directory')
  129. .action((folder, options) => {
  130. // ...
  131. })
  132. cli.parse()
  133. ```
  134. ### Negated Options
  135. To allow an option whose value is `false`, you need to manually specify a negated option:
  136. ```js
  137. cli
  138. .command('build [project]', 'Build a project')
  139. .option('--no-config', 'Disable config file')
  140. .option('--config <path>', 'Use a custom config file')
  141. ```
  142. This will let CAC set the default value of `config` to true, and you can use `--no-config` flag to set it to `false`.
  143. ### Variadic Arguments
  144. 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:
  145. ```js
  146. const cli = require('cac')()
  147. cli
  148. .command('build <entry> [...otherFiles]', 'Build your app')
  149. .option('--foo', 'Foo option')
  150. .action((entry, otherFiles, options) => {
  151. console.log(entry)
  152. console.log(otherFiles)
  153. console.log(options)
  154. })
  155. cli.help()
  156. cli.parse()
  157. ```
  158. <img width="500" alt="2018-11-25 8 25 30" src="https://user-images.githubusercontent.com/8784712/48979056-47125080-f0f0-11e8-9d8f-3219e0beb0ed.png">
  159. ### Dot-nested Options
  160. Dot-nested options will be merged into a single option.
  161. ```js
  162. const cli = require('cac')()
  163. cli
  164. .command('build', 'desc')
  165. .option('--env <env>', 'Set envs')
  166. .example('--env.API_SECRET xxx')
  167. .action((options) => {
  168. console.log(options)
  169. })
  170. cli.help()
  171. cli.parse()
  172. ```
  173. <img width="500" alt="2018-11-25 9 37 53" src="https://user-images.githubusercontent.com/8784712/48979771-6ada9400-f0fa-11e8-8192-e541b2cfd9da.png">
  174. ### Default Command
  175. Register a command that will be used when no other command is matched.
  176. ```js
  177. const cli = require('cac')()
  178. cli
  179. // Simply omit the command name, just brackets
  180. .command('[...files]', 'Build files')
  181. .option('--minimize', 'Minimize output')
  182. .action((files, options) => {
  183. console.log(files)
  184. console.log(options.minimize)
  185. })
  186. cli.parse()
  187. ```
  188. ### Supply an array as option value
  189. ```bash
  190. node cli.js --include project-a
  191. # The parsed options will be:
  192. # { include: 'project-a' }
  193. node cli.js --include project-a --include project-b
  194. # The parsed options will be:
  195. # { include: ['project-a', 'project-b'] }
  196. ```
  197. ### Error Handling
  198. To handle command errors globally:
  199. ```js
  200. try {
  201. // Parse CLI args without running the command
  202. cli.parse(process.argv, { run: false })
  203. // Run the command yourself
  204. // You only need `await` when your command action returns a Promise
  205. await cli.runMatchedCommand()
  206. } catch (error) {
  207. // Handle error here..
  208. // e.g.
  209. // console.error(error.stack)
  210. // process.exit(1)
  211. }
  212. ```
  213. ### With TypeScript
  214. First you need `@types/node` to be installed as a dev dependency in your project:
  215. ```bash
  216. yarn add @types/node --dev
  217. ```
  218. Then everything just works out of the box:
  219. ```js
  220. const { cac } = require('cac')
  221. // OR ES modules
  222. import { cac } from 'cac'
  223. ```
  224. ### With Deno
  225. ```ts
  226. import { cac } from 'https://unpkg.com/cac/mod.ts'
  227. const cli = cac('my-program')
  228. ```
  229. ## Projects Using CAC
  230. Projects that use **CAC**:
  231. - [VuePress](https://github.com/vuejs/vuepress): :memo: Minimalistic Vue-powered static site generator.
  232. - [SAO](https://github.com/egoist/sao): ⚔️ Futuristic scaffolding tool.
  233. - [DocPad](https://github.com/docpad/docpad): 🏹 Powerful Static Site Generator.
  234. - [Poi](https://github.com/egoist/poi): ⚡️ Delightful web development.
  235. - [bili](https://github.com/egoist/bili): 🥂 Schweizer Armeemesser for bundling JavaScript libraries.
  236. - [Lad](https://github.com/ladjs/lad): 👦 Lad scaffolds a Koa webapp and API framework for Node.js.
  237. - [Lass](https://github.com/lassjs/lass): 💁🏻 Scaffold a modern package boilerplate for Node.js.
  238. - [Foy](https://github.com/zaaack/foy): 🏗 A lightweight and modern task runner and build tool for general purpose.
  239. - [Vuese](https://github.com/vuese/vuese): 🤗 One-stop solution for vue component documentation.
  240. - [NUT](https://github.com/nut-project/nut): 🌰 A framework born for microfrontends
  241. - Feel free to add yours here...
  242. ## References
  243. **💁 Check out [the generated docs](https://cac-api-doc.egoist.sh/classes/_cac_.cac.html) from source code if you want a more in-depth API references.**
  244. Below is a brief overview.
  245. ### CLI Instance
  246. CLI instance is created by invoking the `cac` function:
  247. ```js
  248. const cac = require('cac')
  249. const cli = cac()
  250. ```
  251. #### cac(name?)
  252. 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]`.
  253. #### cli.command(name, description, config?)
  254. - Type: `(name: string, description: string) => Command`
  255. Create a command instance.
  256. The option also accepts a third argument `config` for additional command config:
  257. - `config.allowUnknownOptions`: `boolean` Allow unknown options in this command.
  258. - `config.ignoreOptionDefaultValue`: `boolean` Don't use the options's default value in parsed options, only display them in help message.
  259. #### cli.option(name, description, config?)
  260. - Type: `(name: string, description: string, config?: OptionConfig) => CLI`
  261. Add a global option.
  262. The option also accepts a third argument `config` for additional option config:
  263. - `config.default`: Default value for the option.
  264. - `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`.
  265. #### cli.parse(argv?)
  266. - Type: `(argv = process.argv) => ParsedArgv`
  267. ```ts
  268. interface ParsedArgv {
  269. args: string[]
  270. options: {
  271. [k: string]: any
  272. }
  273. }
  274. ```
  275. When this method is called, `cli.rawArgs` `cli.args` `cli.options` `cli.matchedCommand` will also be available.
  276. #### cli.version(version, customFlags?)
  277. - Type: `(version: string, customFlags = '-v, --version') => CLI`
  278. Output version number when `-v, --version` flag appears.
  279. #### cli.help(callback?)
  280. - Type: `(callback?: HelpCallback) => CLI`
  281. Output help message when `-h, --help` flag appears.
  282. Optional `callback` allows post-processing of help text before it is displayed:
  283. ```ts
  284. type HelpCallback = (sections: HelpSection[]) => void
  285. interface HelpSection {
  286. title?: string
  287. body: string
  288. }
  289. ```
  290. #### cli.outputHelp()
  291. - Type: `() => CLI`
  292. Output help message.
  293. #### cli.usage(text)
  294. - Type: `(text: string) => CLI`
  295. Add a global usage text. This is not used by sub-commands.
  296. ### Command Instance
  297. Command instance is created by invoking the `cli.command` method:
  298. ```js
  299. const command = cli.command('build [...files]', 'Build given files')
  300. ```
  301. #### command.option()
  302. Basically the same as `cli.option` but this adds the option to specific command.
  303. #### command.action(callback)
  304. - Type: `(callback: ActionCallback) => Command`
  305. Use a callback function as the command action when the command matches user inputs.
  306. ```ts
  307. type ActionCallback = (
  308. // Parsed CLI args
  309. // The last arg will be an array if it's a variadic argument
  310. ...args: string | string[] | number | number[]
  311. // Parsed CLI options
  312. options: Options
  313. ) => any
  314. interface Options {
  315. [k: string]: any
  316. }
  317. ```
  318. #### command.alias(name)
  319. - Type: `(name: string) => Command`
  320. Add an alias name to this command, the `name` here can't contain brackets.
  321. #### command.allowUnknownOptions()
  322. - Type: `() => Command`
  323. Allow unknown options in this command, by default CAC will log an error when unknown options are used.
  324. #### command.example(example)
  325. - Type: `(example: CommandExample) => Command`
  326. Add an example which will be displayed at the end of help message.
  327. ```ts
  328. type CommandExample = ((name: string) => string) | string
  329. ```
  330. #### command.usage(text)
  331. - Type: `(text: string) => Command`
  332. Add a usage text for this command.
  333. ### Events
  334. Listen to commands:
  335. ```js
  336. // Listen to the `foo` command
  337. cli.on('command:foo', () => {
  338. // Do something
  339. })
  340. // Listen to the default command
  341. cli.on('command:!', () => {
  342. // Do something
  343. })
  344. // Listen to unknown commands
  345. cli.on('command:*', () => {
  346. console.error('Invalid command: %s', cli.args.join(' '))
  347. process.exit(1)
  348. })
  349. ```
  350. ## FAQ
  351. ### How is the name written and pronounced?
  352. CAC, or cac, pronounced `C-A-C`.
  353. This project is dedicated to our lovely C.C. sama. Maybe CAC stands for C&C as well :P
  354. <img src="http://i.giphy.com/v3FeH4swox9mg.gif" width="400"/>
  355. ### Why not use Commander.js?
  356. 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.
  357. _And maybe more..._
  358. Basically I made CAC to fulfill my own needs for building CLI apps like [Poi](https://poi.js.org), [SAO](https://sao.vercel.app) and all my CLI apps. It's small, simple but powerful :P
  359. ## Project Stats
  360. ![Alt](https://repobeats.axiom.co/api/embed/58caf6203631bcdb9bbe22f0728a0af1683dc0bb.svg 'Repobeats analytics image')
  361. ## Contributing
  362. 1. Fork it!
  363. 2. Create your feature branch: `git checkout -b my-new-feature`
  364. 3. Commit your changes: `git commit -am 'Add some feature'`
  365. 4. Push to the branch: `git push origin my-new-feature`
  366. 5. Submit a pull request :D
  367. ## Author
  368. **CAC** © [EGOIST](https://github.com/egoist), Released under the [MIT](./LICENSE) License.<br>
  369. Authored and maintained by egoist with help from contributors ([list](https://github.com/cacjs/cac/contributors)).
  370. > [Website](https://egoist.sh) · GitHub [@egoist](https://github.com/egoist) · Twitter [@\_egoistlily](https://twitter.com/_egoistlily)