{"id":13646904,"url":"https://github.com/CleverCloud/cliparse-node","last_synced_at":"2025-04-21T21:31:44.323Z","repository":{"id":25957145,"uuid":"29398918","full_name":"CleverCloud/cliparse-node","owner":"CleverCloud","description":"Declarative CLI parsing for node","archived":false,"fork":false,"pushed_at":"2024-07-25T14:02:44.000Z","size":641,"stargazers_count":84,"open_issues_count":3,"forks_count":9,"subscribers_count":8,"default_branch":"master","last_synced_at":"2025-04-16T07:07:37.421Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/CleverCloud.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2015-01-17T17:21:14.000Z","updated_at":"2024-07-25T14:02:48.000Z","dependencies_parsed_at":"2024-01-14T10:00:07.885Z","dependency_job_id":"0ea5dc56-1d91-42e5-87cb-9e3bc1bd5984","html_url":"https://github.com/CleverCloud/cliparse-node","commit_stats":null,"previous_names":["divarvel/cliparse-node"],"tags_count":16,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/CleverCloud%2Fcliparse-node","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/CleverCloud%2Fcliparse-node/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/CleverCloud%2Fcliparse-node/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/CleverCloud%2Fcliparse-node/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/CleverCloud","download_url":"https://codeload.github.com/CleverCloud/cliparse-node/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250136766,"owners_count":21380886,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-02T01:03:14.539Z","updated_at":"2025-04-21T21:31:43.967Z","avatar_url":"https://github.com/CleverCloud.png","language":"JavaScript","funding_links":[],"categories":["JavaScript"],"sub_categories":[],"readme":"# Declarative CLI parsing for node apps\n\n[![Build Status](https://travis-ci.org/CleverCloud/cliparse-node.svg?branch=master)](https://travis-ci.org/CleverCloud/cliparse-node)\n[![Coverage Status](https://coveralls.io/repos/github/CleverCloud/cliparse-node/badge.svg?branch=master)](https://coveralls.io/github/CleverCloud/cliparse-node?branch=master)\n\nThis is a library designed to express command-line options. It supports\ncommands and subcommands (at an arbitrary depth), automatically generates help\ntext and `usage` contents. You can use custom parsers for attributes and\noptions values (types supported out of the box: `int`, `bool`, `string`).\n\nIts design is vaguely inspired from\n[optparse-applicative](https://hackage.haskell.org/package/optparse-applicative)\nwhich is a great CLI parsing library. JS being not as expressive as Haskell, a\ndirect port is not possible.\n\n\u003e Disclaimer:\n\u003e\n\u003e This library has been started by @divarvel as part of his job at Clever Cloud. Since he\n\u003e left the company and doesn't use cliparse nor wishes to maintain it anymore, we\n\u003e mutually agreed to transfer ownership of the project to CleverCloud.\n\u003e\n\u003e Big thanks to him for producing this library!\n\n\n## Enough talk, show me the code\n\n```bash\nnpm install cliparse\n```\n\n```javascript\n#!/usr/bin/env node\n\nvar cliparse = require(\"cliparse\");\nvar parsers = cliparse.parsers;\n\nfunction echoModule(params) {\n    \n}\n\nfunction addModule(params) {\n    \n}\n\nvar cliParser = cliparse.cli({\n  name: \"my-executable\",\n  description: \"Simple CLI written for the sake of the example\",\n  commands: [\n\n    cliparse.command(\n      \"echo\",\n      { description: \"Display the given value\",\n        args: [ cliparse.argument(\"value\", { description: \"Simple value\" })],\n        options: [ cliparse.flag(\"reverse\", { aliases: [\"r\"], description: \"Reverse the value\"}) ]\n      },\n      echoModule),\n\n    cliparse.command(\n      \"add2\",\n      { description: \"Add 2 to the given integer and display the result\",\n        args: [\n          cliparse.argument(\"int\",\n            { default: 0,\n              parser: parsers.intParser,\n              description: \"Int to add 2 to\" })\n        ]\n      },\n      addModule)\n  ]\n});\n\ncliparse.parse(cliParser);\n```\n\nWhere `echoModule` and `addModule` are callbacks taking a `{ args: ['value'], options: {key: 'value'} }` parameter.\n\n### Generated output\n\n#### Top-level help\n\n```\n$ my-executable --help\nUsage: my-executable\nSimple CLI written for the sake of the example.\n\n\nOptions:\n[--help, -?]                    Display help about this program\n\nAvailable commands:\nhelp                            Display help about this program\necho VALUE                      Display the given value\nadd2 [INT]                      Add 2 to the given integer and display the result\n```\n\n#### Command-level help\n\n```\n$ my-executable echo --help\nUsage : my-executable echo VALUE\ndisplay the given value\n\nArguments:\nVALUE                           Simple value\n\nOptions:\n[--help, -?]                    Display help about this program\n[--reverse, -r]                 Reverse the value\n```\n\n## Subcommands\n\nThe `command` constructor takes an optional `commands` attribute which allows\nyou to nest subcommands at an arbitrary level.\n\n```javascript\nvar testCli = cliparse.cli({\n  name: \"testCli\",\n  description: \"Simple CLI written for the sake of the example\",\n  commands: [\n    cliparse.command(\n      \"number\",\n      { description: \"perform simple arithmetic calculations\",\n        commands: [\n          cliparse.command(\n            \"add\",\n            { description: \"add two integers\",\n              args: [ intArgument, intArgument]\n            }, numberModule.add),\n          cliparse.command(\n            \"multiply\",\n            { description: \"multiply two integers\",\n              args: [ intArgument, intArgument]\n            }, numberModule.multiply)\n        ]\n      }),\n  ]\n});\n```\n\n## Help command\n\nAn help command is automatically generated, with the following syntax:\n\n```bash\n$ my-executable help \u003ccommand\u003e \u003csubcommand\u003e \u003c...\u003e\n```\n\nIt can be disabled by setting `helpCommand` to `false` in `cliparse.cli` options.\n\n## Autocompletion\n\nCLI parse allows you to generate autocompletion scripts for bash and zsh (work\nin progress). Generate the script in your npm post-install hook and add it to\nyour users shell completion scripts to enable it.\n\nIt supports completion on commands, options and arguments, as well as on the\nhelp command. Completion on options and arguments are configurable: you can\ndeclare your own completion methods.\n\nAll the completion logic is handled within your app, so it will work with\ndynamically defined commands.\n\n### Bash\n\nGenerate the completion script and put it in bash completion dir:\n\n```bash\n$ my-executable --bash-autocomplete-script /complete/path/to/my-executable \u003e ~/.bash_completion.d/my-executable\n```\n\nNormally `.bash_completion.d` is automatically sourced. You can put the file\nwhere you want and source it manually.\n\n### ZSH\n\nGenerate the completion script and put it in zsh completion dir:\n\n```bash\n$ my-executable --zsh-autocomplete-script /complete/path/to/my-executable \u003e ~/.zsh.d/completion/_my-executable\n```\n\nThe file name **must** be `_my-executable` (if your executable is named\n`my-executable`). You can put the file where you want as long as it's in a\ndirectory listed in `$fpath`.\n\n### Custom completion\n\nYou can have custom completion for option or arguments, by passing a custom\ncomplete function (see [API](#option)).\n\nFor instance to complete on a list of colors:\n\n```javascript\nvar colorCompleter = function() {\n  return autocomplete.words(['mauve', 'blue', 'yellow', 'purple', 'parabolic']);\n};\n```\n\nTo complete on a list of files:\n\n```javascript\nvar fileCompleter = function() {\n  return autocomplete.files;\n};\n```\n\nThe `complete` function can also return a promise for async results.\n\n## API\n\n### `cli`\n\n```javascript\ncli(opts, cb);\n```\n\nWhere opts can contain\n\n - `name`: the name of the executable (if not provided, `process.argv` is used)\n - `description`: a one-line description of the executable\n - `version`: the version number of the executable (displayed by `--version`.\n   Default value: `null`\n - `options`: array of top-level options (constructed with `option` or `flag`). Default\n   value: `[]`.\n - `commands`: array of commands (constructed with `command`). Default value: `[]`\n - `args`: array of arguments (constructed with `argument`). If your app\n   doesn't have commands.\n - `helpCommand`: Generate a `help` command. Default value: `true`.\n\nIf your application is not solely made of commands, you can pass an action\ncallback. If you don't give a callback, calling your application without any\nargument will display a `usage` message describing the available commands.\n\n### `option`\n\n```javascript\noption(name, opts);\n```\n\nWhere name is the name of the flag, and opts can contain\n\n - `aliases`: array of other names (the shorthand name for instance. Default\n   value: `[]`\n - `metavar`: the name of the value of the option (if applicable: for flags,\n  see below)\n - `parser`: the parser used to parse the value. Default value: `stringParser`\n   which is a noop parser returning the string.\n - `description`: a single-line description of what the option is about. Default\n   value: the empty string.\n - `required`: make option mandatory\n - `default`: value used if the option is not given any value. If set,\n   overrides the `required` setting.\n - `complete`: a function returning completion results for the option (or a\n   promise of results). Default value: a function returning an empty result.\n - `expects_value`: does the option expect a value? Default: true. Rather than\n   setting it yourself, use `flag`.\n\n\n### `flag`\n\nShorthand for flags (ie options with boolean values, defaulting to `false`,\ndoesn't expect a value)\n\n```javascript\nflag(name, opts);\n```\n\nActs like `option`, with different defaults:\n\n - `parser` defaults to `booleanParser`, which parses boolean values\n - `default` defaults to `false`\n\n### `argument`\n\n```javascript\nargument(name, opts);\n```\n\nWhere opts can contain\n\n - `parser`: ther parser used to parse the value of the argument. Default\n   value: `stringParser`\n - `description`: a single-line description of what the argument is about.\n - `default`: value used if the argument is not given any value\n - `complete`: a function returning completion results for the argument. Default\n   value: a function returning an empty result.\n\n### `command`\n\n```javascript\ncommand(name, opts, cb);\n```\n\nWhere `name` is the name of the command , and `opts` can contain\n\n - `description`: a single line description of the command\n - `args`: array of arguments (constructed with `argument`). Default value: `[]`\n - `options`: array of options (constructed with `option`). Default value:\n   `[]`\n- `privateOptions`: array of options that will not be inherited in sub commands. Default value:\n   `[]`\n - `commands`: array of subcommands (constructed with `command`). Default\n   value: `[]`\n\n`cb` is a callback which is called when the command match (if no subcommand\nmatch). It is called with a `{ args: ['value'], options: {key: 'value'}}` object. `opts` contains\nboth the options of the command and the options of the parent commands.\n\n### Parsers\n\nBasic scalar types (`int`, `bool`, and `string`) are already supported. It is\npossible to declare your own parsers to validate more specific types of values\n(eg. enums).\n\nA parser is a function `String -\u003e Result` where `Result` is either \n\n - `{ success: \u003cparsed value\u003e }`\n - or `{ error: \u003cerror message\u003e }`\n\nParser results can be constructed with `parsers.success(\u003cvalue\u003e)` and\n`parsers.error(\u003creason\u003e)`.\n\nFor instance, to parse an hexadecimal RBG color:\n\n```javascript\nvar colorParser = function(input) {\n  var pattern = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i;\n  var matches = input.match(pattern);\n  if(matches !== null) {\n    var components = matches.slice(1,4)\n          .map(function(x) { return parseInt(x, 16); });\n    return parsers.success(components);\n  } else {\n    return parsers.error(\"invalid color code\");\n  }\n}\n```\n\n### Autocompletion helpers\n\n#### Autocompletion results\n\n`autocomplete.empty`: no results\n\n`autocomplete.words([…])`: list of words\n\n`autocomplete.glob(\u003cglob\u003e)`: files matching glob (eg. `*.log`).\n\n`autocomplete.files`: files\n\n`autocomplete.directories`: directories\n\nYou can combine autocompletion results:\n\n`autocomplete.mappend(\u003cresult1, result2\u003e)`: combine results from `result1` and\n`result2`. As globs can't be combined, the last one wins (if set).\n\n`autocomplete.mconcat([ \u003cresults\u003e ])`: reduce a list of result to a composite\nresult with `mappend`. If the list is empty, then `empty` is returned.\n\n## Contributing\n\nMake sure you don't break anything.\n\n```bash\nnpm test\n```\n\n## ToDo\n\n### For `0.3.0`\n\n - [x] Declare flags as boolean options in minimist\n - [ ] [Variadic arguments](https://github.com/divarvel/cliparse-node/issues/7)\n - [ ] [Parse failure on unrecognized options / arguments](https://github.com/divarvel/cliparse-node/issues/1)\n - [ ] [Cleaner display of errors](https://github.com/divarvel/cliparse-node/issues/8)\n\n### Later\n\n - [ ] [Dedicated ZSH completion (help welcome :-\\])](https://github.com/divarvel/cliparse-node/issues/9)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FCleverCloud%2Fcliparse-node","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FCleverCloud%2Fcliparse-node","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FCleverCloud%2Fcliparse-node/lists"}