{"id":13447447,"url":"https://github.com/DiegoZoracKy/magicli","last_synced_at":"2025-03-22T01:30:59.591Z","repository":{"id":54876240,"uuid":"109625739","full_name":"DiegoZoracKy/magicli","owner":"DiegoZoracKy","description":"Automagically generates command-line interfaces (CLI) for any module. Expected options and help sections are created automatically based on parameters names, with support to async.","archived":false,"fork":false,"pushed_at":"2021-01-25T02:50:51.000Z","size":18,"stargazers_count":179,"open_issues_count":1,"forks_count":7,"subscribers_count":4,"default_branch":"master","last_synced_at":"2025-03-21T03:46:43.412Z","etag":null,"topics":["cli","command-line","command-line-interface","nodejs"],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/DiegoZoracKy.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2017-11-05T23:33:49.000Z","updated_at":"2024-06-17T20:02:53.000Z","dependencies_parsed_at":"2022-08-14T05:30:31.757Z","dependency_job_id":null,"html_url":"https://github.com/DiegoZoracKy/magicli","commit_stats":null,"previous_names":[],"tags_count":2,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DiegoZoracKy%2Fmagicli","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DiegoZoracKy%2Fmagicli/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DiegoZoracKy%2Fmagicli/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DiegoZoracKy%2Fmagicli/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/DiegoZoracKy","download_url":"https://codeload.github.com/DiegoZoracKy/magicli/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":244890092,"owners_count":20527033,"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":["cli","command-line","command-line-interface","nodejs"],"created_at":"2024-07-31T05:01:17.955Z","updated_at":"2025-03-22T01:30:59.568Z","avatar_url":"https://github.com/DiegoZoracKy.png","language":"JavaScript","funding_links":[],"categories":["JavaScript","cli"],"sub_categories":[],"readme":"# MagiCLI\n\n[![Build Status](https://api.travis-ci.org/DiegoZoracKy/magicli.svg)](https://travis-ci.org/DiegoZoracKy/magicli) [![npm](https://img.shields.io/npm/v/magicli.svg)]() [![npm](https://img.shields.io/npm/l/magicli.svg)]()\n\nAutomagically generates command-line interfaces (CLI), for any module.\nJust `require('magicli')();` and your module is ready to be executed via CLI.\n\nThe main goal is to have any module prepared to be executed via CLI (installed globally with `-g`, or by using **npx**):\n\nTo see why I believe you should plug it on your module, even if you don't need a CLI (it probably will serve someone on the community), read here: [Introducing MagiCLI: Automagically generates a command-line interface (CLI) for any module\n](https://hackernoon.com/introducing-magicli-automagically-generates-a-command-line-interface-cli-for-any-module-49543e50f86d)\n\n**It can be installed globally, in order to *execute* any module or .js file via CLI.**\n\n## Goals\n\n * Minimal setup (*one line*)\n * Automatic options names based on functions parameters\n * Out of the box support to async functions (`Promises`, or any *thenable* lib)\n * A specific help section for each nested property (*\"subcommands\"*)\n * *Name*, *Description* and *Version* extracted from package.json\n * Simple API to hook into the execution flow (*stdin*, *before*, *after*)\n * Cover all possible cases of module.exports (*Function*, *Object* with nested properties, Destructuring parameters)\n * Provide a CLI to be used to execute any given module or .js file via CLI\n\n## Usage (the most simple and minimal way)\n\n * `npm install magicli`\n * Add the property **bin** to your package.json containing the value **./bin/magicli.js**\n * Create the file **./bin/magicli.js** with the following content:\n\n```javascript\n#!/usr/bin/env node\n\nrequire('magicli')();\n```\n\n**Done!** Install your module with `-g`, or use it via **[npx](http://blog.npmjs.org/post/162869356040/introducing-npx-an-npm-package-runner)**, and run it with `--help` to see the result. The `--version` option will show the same value found at *package.json*. In the same way you can just run `node ./bin/magicli.js --help` to test it quickly, without installing it.\n\nLet's suppose that **your-module** exports the function:\n\n```javascript\nmodule.exports = function(param1, param2) {\n    return param1 + param2;\n}\n```\n\nWhen calling it via CLI, with `--help`, you will get:\n\n```bash\nDescription:\n\n  Same description found at package.json\n\nUsage:\n\n  $ your-module [options]\n\nOptions:\n\n  --param1\n  --param2\n```\n\nThe program will be expecting options with the same name as the parameters declared at the exported function, and it doesn't need to follow the same order. Example:\n\n`$ your-module --param2=\"K\" --param1=\"Z\"` would result in: `ZK`.\n\nImportant: MagiCLI requires the module in order to analyse it, and provide the command-line interface for it. Keep that in mind in case your module does something just by being required.\n\n## Usage via CLI\n\nIn order to **execute** any module or .js file via CLI, install it globally:\n\n```bash\n$ npm install magicli -g\n```\n\nThen just pass in as the first argument, the path to a module or a .js file. Examples:\n * `$ magicli . --help`\n * `$ magicli ./path/to-some-module --help`\n * `$ magicli ./path/to-a-file.js --help`\n\nOr use it via **[npx](http://blog.npmjs.org/post/162869356040/introducing-npx-an-npm-package-runner)** without the need to install it.\n\nLet's suppose that you have a simple .js file as this one:\n\n```javascript\nmodule.exports = {\n\tsum: (n1, n2) =\u003e n1 + n2,\n\tec: {\n\t\tho: str =\u003e `${str} !!!`\n\t}\n}\n```\n\nJust execute **magicli** on it, as `$ magicli ./path/to-the-file-above.js --help` and you will get:\n\n```bash\nCommands:\n  sum\n  ec-ho\n```\n\n`$ magicli ./path/to-the-file-above.js sum --help` will give you:\n```bash\nUsage:\n  $ sum [options]\n\nOptions:\n  --n1\n  --n2\n```\nand `$ magicli ./path/to-the-file-above.js sum --n1=4 --n2=2` will result in `6`\n\n### How it works\n\nMagiCLI is capable of handling many styles of `exports`, like:\n\n * Functions\n * Object Literal\n * Nested properties\n * Class with static methods\n\nAnd also any kind of parameters declaration (*Destructuring Parameters*, *Rest Parameters*).\n\nIf **your-module** were like this:\n```javascript\n// An Arrow function with Destructuring assignment and Default values\nconst mainMethod = ([p1, [p2]] = ['p1Default', ['p2Default']], { p3 = 'p3Default' } = {}) =\u003e `${p1}-${p2}-${p3}`;\n\n// Object Literal containing a nested method\nmodule.exports = {\n\tmainMethod,\n\tnested: {\n\t\tmethod: param =\u003e `nested method param value is: \"${param}`\n\t}\n};\n```\n\n`$ your-module --help` would result in:\n\n```bash\nDescription:\n\n  Same description found at package.json\n\nUsage:\n\n  $ your-module \u003ccommand\u003e\n\nCommands:\n\n  mainMethod\n  nested-method\n```\n\n`$ your-module mainMethod --help` would be:\n\n```bash\nUsage:\n\n  $ your-module mainMethod [options]\n\nOptions:\n\n  --p1\n  --p2\n  --p3\n```\n\n`$ your-module nested-method --help` returns:\n\n```bash\nUsage:\n\n  $ your-module nested-method [options]\n\nOptions:\n\n  --param\n```\n\nCalling *mainMethod* without any parameter:\n`$ your-module mainMethod`\n\nresults in:\n` p1Default-p2Default-p3Default`\n\nWhile defining the parameter for *nested-method*:\n`$ your-module mainMethod nested-method --param=paramValue`\n\nwould return:\n` nested method param value is: \"paramValue\"`\n\nNote: Nested methods/properties will be turned into commands separated by `-`, and it can be configurable via options (`subcommandDelimiter`).\n\n## Usage Options\n`magicli({ commands = {}, validateRequiredParameters = false, help = {}, version = {}, pipe = {}, enumerability = 'enumerable', subcommandDelimiter = '-'})`\n\nOptions are provided to add more information about commands and its options, and also to support a better control of a command execution flow, without the need to change the source code of the module itself (for example, to `JSON.stringify` an `Object Literal` that is returned).\n\n\n\n### enumerability\n\nBy default, only the enumerable nested properties will be considered. The possible values are: `'enumerable'` (default), `'nonenumerable'` or `'all'`.\n\n### validateRequiredParameters\nMagiCLI can validate the required parameters for a command and show the help in case some of them are missing. The default value is `false`.\n\n### help\n\n**help.option**\nTo define a different option name to show the help section. For example, if `'modulehelp'` is chosen, `--modulehelp` must be used instead of `--help` to show the help section.\n\n**help.stripAnsi**\n\tSet to `true` to strip all ansi escape codes (colors, underline, etc.) and output just a raw text.\n\n\n\n### version\n**version.option**\nTo define a different option name to show the version. For example, if `'moduleversion'` is chosen, `--moduleversion` must be used instead of `--version` to show the version number.\n\n### pipe (stdin, before and after)\n\nThe pipeline of a command execution is:\n\n**stdin** (command.pipe.stdin || magicliOptions.pipe.stdin) =\u003e\n\n**magicliOptions.pipe.before** =\u003e\n\n**command.pipe.before** =\u003e\n\n**command.action** (the method in case) =\u003e\n\n**command.pipe.after** =\u003e\n\n**magicliOptions.pipe.after** =\u003e\n\n**stdout**\n\nWhere each of these steps can be handled if needed.\n\nAs it can be defined on *commands* option, for each command, **pipe** can also be defined in *options* to implement a common handler for all commands. The expected properties are:\n\n**pipe.stdin**\n`(stdinValue, args, positionalArgs, argsAfterEndOfOptions)`\n\nUseful to get a value from *stdin* and set it to one of the expected *args*.\n\n**pipe.before**\n`(args, positionalArgs, argsAfterEndOfOptions)`\n\nTo transform the data being input, before it is passed in to the main command action.\n\n**pipe.after**\n`(result, parsedArgs, positionalArgs, argsAfterEndOfOptions)`\n\nNote: **stdin** and **before** must always return *args*, and **after** must always return *result*, as these values will be passed in for the next function in the pipeline.\n\n### commands\nThe options are effortlessly extracted from the parameters names, however it is possible to give more information about a command and its options, and also give instructions to the options parser.\n\n**commands** expects an `Object Literal` where each key is the command name. It would be the module's name for the main function that is exported, and the command's name as it is shown at the *Commands:* section of `--help`. For example:\n```javascript\ncommands: {\n    'mainmodulename': {},\n    'some-nested-method': {}\n}\n```\n\nFor each command the following properties can be configurable:\n\n#### options\nIs an *Array* of *Objects*, where each contains:\n\n**name** (*required*)\nThe name of the parameter that will be described\n\n**required**\nTo tell if the parameter is required.\n\n**description**\nTo give hints or explain what the option is about.\n\n**type**\nTo define how the parser should treat the option (Array, Object, String, Number, etc.).  Check [yargs-parser](https://github.com/yargs/yargs-parser) for instructions about *type*, as it is the engine being used to parse the options.\n\n**alias**\nTo define an alias for the option.\n\n#### pipe (stdin, before and after)\n\nThe pipeline of a command execution is:\n\n**stdin** (command.pipe.stdin || magicliOptions.pipe.stdin) =\u003e\n\n**magicliOptions.pipe.before** =\u003e\n\n**command.pipe.before** =\u003e\n\n**command.action** (the method in case) =\u003e\n\n**command.pipe.after** =\u003e\n\n**magicliOptions.pipe.after** =\u003e\n\n**stdout**\n\nWhere each of these steps can be handled if needed.\n\nAs it can be defined on *options* to implement a common handler for all commands, **pipe** can also be defined for each command.\n\n**pipe.stdin**\n`(stdinValue, args, positionalArgs, argsAfterEndOfOptions)`\n\nUseful to get a value from *stdin* and set it to one of the expected *args*.\n\n**pipe.before**\n`(args, positionalArgs, argsAfterEndOfOptions)`\n\nTo transform the data being input, before it is passed in to the main command action.\n\n**pipe.after**\n`(result, parsedArgs, positionalArgs, argsAfterEndOfOptions)`\n\nNote: **stdin** and **before** must always return *args*, and **after** must always return *result*, as these values will be passed in for the next function in the pipeline.\n\nIf needed, a more thorough guide about this section can be found at [cliss](https://github.com/DiegoZoracKy/cliss) (as this is the module under the hood to handle that)\n\nA full featured use of the module would look like:\n\n```javascript\nmagicli({\n\tcommands,\n\tenumerability,\n\tsubcommandDelimiter,\n\tvalidateRequiredParameters,\n\thelp: {\n\t\toption,\n\t\tstripAnsi\n\t},\n\tversion: {\n\t\toption\n\t},\n\tpipe: {\n\t\tstdin: (stdinValue, args, positionalArgs, argsAfterEndOfOptions) =\u003e {},\n\t\tbefore: (args, positionalArgs, argsAfterEndOfOptions) =\u003e {},\n\t\tafter: (result, parsedArgs, positionalArgs, argsAfterEndOfOptions) =\u003e {}\n\t}\n});\n```\n\n## Example\n\nTo better explain with an example, let's get the following module and configure it with MagiCLI to:\n\n * Define **p1** as `String` (*mainMethod*)\n * Write a description for **p2** (*mainMethod*)\n * Define **p3** as required (*mainMethod*)\n * Get **p2** from stdin (*mainMethod*)\n * Use **before** (command) to upper case **param** (*nested-method*)\n * Use **after** (command) to JSON.stringify the result of (*nested-method*)\n * Use **after** (options) to decorate all outputs (*nested-method*)\n\n**module** (\"main\" property of package.json)\n```javascript\n'use strict';\n\nmodule.exports = {\n\tmainMethod: (p1, p2, { p3 = 'p3Default' } = {}) =\u003e `${p1}-${p2}-${p3}`,\n\tnested: {\n\t\tmethod: param =\u003e {\n\n\t\t\t// Example of a Promise being handled\n\t\t\treturn new Promise((resolve, reject) =\u003e {\n\t\t\t\tsetTimeout(() =\u003e {\n\t\t\t\t\tresolve({ param });\n\t\t\t\t}, 2000);\n\t\t\t});\n\t\t}\n\t}\n};\n```\n\n**magicli.js** (\"bin\" property of package.json)\n```javascript\n#!/usr/bin/env node\n\n\nrequire('../magicli')({\n\tcommands: {\n\t\t'mainMethod': {\n\t\t\toptions: [{\n\t\t\t\tname: 'p1',\n\t\t\t\tdescription: 'Number will be converted to String',\n\t\t\t\ttype: 'String'\n\t\t\t}, {\n\t\t\t\tname: 'p2',\n\t\t\t\tdescription: 'This parameter can be defined via stdin'\n\t\t\t}, {\n\t\t\t\tname: 'p3',\n\t\t\t\trequired: true\n\t\t\t}],\n\t\t\tpipe: {\n\t\t\t\tstdin: (stdinValue, args, positionalArgs, argsAfterEndOfOptions) =\u003e {\n\t\t\t\t\targs.p2 = stdinValue;\n\t\t\t\t\treturn args;\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t'nested-method': {\n\t\t\toptions: [{\n\t\t\t\tname: 'param',\n\t\t\t\tdescription: 'Wait for it...'\n\t\t\t}],\n\t\t\tpipe: {\n\t\t\t\tbefore: (args, positionalArgs, argsAfterEndOfOptions) =\u003e {\n\t\t\t\t\tif (args.param) {\n\t\t\t\t\t\targs.param = args.param.toUpperCase();\n\t\t\t\t\t}\n\t\t\t\t\treturn args;\n\t\t\t\t},\n\n\t\t\t\tafter: JSON.stringify\n\t\t\t}\n\t\t}\n\t},\n\tpipe: {\n\t\tafter: (result, positionalArgs, argsAfterEndOfOptions) =\u003e `======\\n${result}\\n======`\n\t}\n});\n```\n\n## Tests\n\nThere is another repository called [MagiCLI Test Machine](https://github.com/DiegoZoracKy/magicli-test-machine), where many real published modules are being successfully tested. As the idea is to keep increasing the number of real modules tested, it made more sense to maintain a separated repository for that, instead of being constantly increasing the size of MagiCLI itself over time. I ask you to contribute with the growing numbers of those tests by adding your own module there via a pull request.\n\nIf you find some case that isn't being handled properly, please open an *issue* or feel free to create a PR ;)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FDiegoZoracKy%2Fmagicli","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FDiegoZoracKy%2Fmagicli","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FDiegoZoracKy%2Fmagicli/lists"}