A versatile and customizable CLI creator tool
ArgParser. This class contains your functions to add commands, options, etc. Any call you make returns the ArgParser. Requiring/importing wily-cli provides you with a bunch of functions that will act on an ArgParser. If the ArgParser is not yet made, the function will create a unique ArgParser, and the rest of the chained commands will use that ArgParser. This allows you to easily make components for your CLI in the same or separate files, however you see fit for your application. Unlike other CLI creator tools, this tool's ArgParser class provides more customization and control, as well as handles parsing of the arguments without you explicitly telling it to. All you do is set it up, and it'll handle the rest. See the examples for demonstrations on how to use wily-cli.
npm install wily-cli
event can be a pre determined event, option name, or parameter name. Provided events:
before Execute before all
after Execute after all
exec Execute when the command is run. This is useful when the command only contains options.
command Execute after a sub command is run
help Execute after the help output
version Execute after the version output
quit INTERACTIVE ONLY Execute when the interactive CLI quit command is called
error Execute on an error being thrown. The only parameter in the callback function for this event will be the error.
event (String) Event to execute the action on
action (Function|AsyncFunction|Promise) Action to be executed on the event. For all events except for error, the action function will have options, parameters, and the command passed into it as arguments. The parameters and options arguments will have an _extras property if extra parameters/options are passed in via the command line for the command.
javascript
const cli = require('wily-cli');
cli
.command('example', 'Example command')
.on('command', (options, parameters, command) => {
console.log(Executed ${command});
});
`
---
$3
Set the arguments to be parsed. By default, it will parse process.argv. This function is available just in case you want to override the arguments.
#### Parameters
- args (Array\) Arguments to parse
#### Examples
`javascript
const cli = require('wily-cli');
cli
.command('example', 'Example command')
.args(['example', 'arg2']);
`
---
$3
Set the help output description text. Can be customized with text effects.
#### Parameters
- description (String) Help output description string
#### Examples
`javascript
const cli = require('wily-cli');
cli
.command('example', 'Example command')
.description('Custom description');
`
---
$3
Add a sub command to the command. description can be customized with text effects.
#### Parameters
- command (String) Name of the command
- description (String) Description of the command
- action (String|Function|ArgParser|AsyncFunction|Promise) Action to be taken upon the command being called.
A function action will execute immediately after the command is called. Passing in an ArgParser will set the command to build the ArgParser's additional sub commands and options upon execution of this command.
A string must represent a relative file path pointing to a file that exports an ArgParser. This file can be a JavaScript file or a binary file built from a JavaScript file (can even be a Windows executable). You do not need to specifiy the file extension, just the file name. It will automatically find the file if an extension is not provided, prioritizing JavaScript files over binary files. Binary files can be built with tools, such as nexe or pkg. An advantage of pkg is that it allows for all of your files to be bundled into a single binary. Exporting an ArgParser is only required for JavaScript files, as binary files are executed in different proceses.
Optionally, action can be omitted, resulting it looking for a file named within the same directory as the current ArgParser file. For example, command1.js has a command called test, and test omits the action parameter. It will look for command1-test.js within the same directory as command1.js.
The more efficient options would be using a Function or a path to a file for the action parameters (or omitting the parameter). The ArgParser option is available and can be convenient, but it means that the other ArgParser will be loaded upon being required or imported, padding more time onto building the CLI.
If you add parameters to the command name, for example .command('foo , it will automatically parse those parameters upon executing the command foo. Alternatively, you can use .parameter to add parameters to an ArgParser. If you're adding parameters, it's best to use one technique, not both. Only one parameter can be repeated.
#### Examples
`javascript
const cli = require('wily-cli');
// Function
cli
.command('example', 'Example command', (options, parameters, command) => {
console.log('Command executed');
});
`
`javascript
const cli = require('wily-cli');
// String
cli
.command('example', 'Example command', 'path/to/other/argparser'); // Looks for path/to/other/argparser.js, path/to/other/argparser, or path/to/other/argparser.exe
`
`javascript
const cli = require('wily-cli');
const otherArgParser = require('path/to/other/argparser.js')
// ArgParser
cli
.command('example', 'Example command', otherArgParser);
`
`javascript
const cli = require('wily-cli');
// Omitted action
cli
.command('example', 'Example command'); // Looks for thisfilename-example.js, thisfilename-example, or thisfilename-example.exe
`
---
$3
Sets the default command to be executed if no other command is provided.
#### Parameters
- command (String) Name of the command to be set as default
#### Examples
`javascript
const cli = require('wily-cli');
cli
.command('example', 'Example command')
.command('command2', 'Not default')
.defaultCommand('example');
`
---
$3
Adds an option to the command. The help option is automatically added. By default, the option's short would be lowercase of the first character of the option name, uppercase if lowercase is already taken, or none if both lowercase and uppercase are taken. description can be customized with text effects.
#### Parameters
- option (String) Name of the option. Supports on/off switches. If the option begins with no-, then the opposite option will be set to the opposite value of the no-... option if the value provided is a boolean. For example, if no-cats and cats are both added as options, and no-cats is set to true, then cats will automatically be set to false. You can also omit cats, and any time no-cats is provided with, then cats will be automatically set to the opposite value.
- description (String) Description of the option.
- options (Object) Configuration object for the option.
- default (String) Default value for the option when the option is provided, but no value is given. By default, all options default to true if provided.
- modifier (Function) Function that will modify that provided value of an option.
- parameters (Array) Names of parameters for the option. This will change the option value to be an Object containing the values for those parameters.
- paramSeparator (String) Character to separate the option's parameters within the help output.
- required (Boolean) Flag saying if the option is required or not. Defaults to false.
- passThrough (Boolean) Flag telling the system to also pass the option down to sub commands.
- short (String) Override for the automatic short option.
#### Examples
`javascript
const cli = require('wily-cli');
cli
.command('example', 'Example command')
.option('opt', 'Example option', {
default: { one: 'oneDefault', two: 'twoDefault' },
parameters: ['one', 'two']
})
.option('opt2 ', 'Example option 2');
// Can be called using --opt or -o. The value will default to { one: 'oneDefault', two: 'twoDefault' }
// if no paremeters are provided.
// Parameters can be set by using it like --opt . For example: --opt true 2 would yield { one: true, two: 2}.
// The 'opt2' option is set up with an alternative way of adding parameters directly in
// the option name string.
`
`javascript
const cli = require('wily-cli');
cli
.command('example', 'Example command')
.option('opt', 'Example option');
// Can be called using --opt or -o. The value will be true if not value is provided, or whatever was provided
`
---
$3
Adds a parameter to the command.
#### Parameters
- parameter (String) Name of the parameter
- required (Boolean) True if required (surrounds the parameter with \<> in the help output), false if not required (surrounds the parameter with \[] in hte help output). Defaults to false.
- repeated (Boolean) True if parameter is a repeated parameter. Will be returned as an array in this case. Defaults to false. Only one parameter can be repeated.
#### Examples
`javascript
const cli = require('wily-cli');
cli
.command('example', 'Example command')
.parameter('param1');
// If this command were called foo, the help output would look like foo [param1]
`
`javascript
const cli = require('wily-cli');
cli
.command('example', 'Example command')
.parameter('param1')
.parameter('param2');
// If this command were called foo, the help output would look like foo [param1] [param2]
`
`javascript
const cli = require('wily-cli');
cli
.command('example', 'Example command')
.parameter('param1', true)
.parameter('param2');
// If this command were called foo, the help output would look like foo
`
`javascript
const cli = require('wily-cli');
cli
.command('example', 'Example command')
.parameter('param1', true)
.parameter('param2', false, true);
// If this command were called foo, the help output would look like foo
// param2 would be returned as an array
`
---
$3
Sets a character to separate the command parameters. Alternatively, putting a separator in between the parameters in the .command function command parameter will set the parameter separator for that sub command. Keep in mind, only the first separator will be used as the separator.
#### Parameters
- separator (String) Parameter separator
#### Examples
`javascript
const cli = require('wily-cli');
cli
.parameterSeparator('>');
`
---
$3
Sets the output for the --version/-v version option. If not set, the version option will not be automatically available. Can be customized with text effects.
#### Parameters
- version (String|Number) Version to be outputed with the version option
#### Examples
`javascript
const cli = require('wily-cli');
cli
.version('1.0.2');
`
---
$3
Sets the option name and short for the version output. Default values are version for the option, and v for the short. If short isn't provided, then the previous short will continue to be used.
#### Parameters
- option (String) Option name
- short (String) Option short
#### Examples
`javascript
const cli = require('wily-cli');
cli
.version('1.0.2')
.versionOption('revision', 'r');
`
---
$3
Set the version option description. Default is "Output version". Can be customized with text effects.
#### Parameters
- description (String) Custom version option description
#### Examples
`javascript
const cli = require('wily-cli');
cli
.versionOptionDescription('Display help');
`
---
$3
Overrides the default usage string with a custom usage string. Can be customized with text effects.
#### Parameters
- usageString (String) Custom usage string for the help output
#### Examples
`javascript
const cli = require('wily-cli');
cli
.usage('[magenta]This is how it\'s [red]used');
`
---
$3
Sets the switch character for selecting options. Default character is - for shorts, and -- for longs. Using this will set the character to be for both short and long option names.
#### Parameters
- character (String) Switch character for options
#### Examples
`javascript
const cli = require('wily-cli');
cli
.option('test', 'Test option')
.switchCharacter('/');
// The test option must now be selected by /t or /test
`
---
$3
Enable the automatic help output. Default behavior is enabled.
#### Examples
`javascript
const cli = require('wily-cli');
cli
.enableGeneratedHelp();
`
---
$3
Disable the automatic help output. Useful if you want full control over what gets printed.
#### Examples
`javascript
const cli = require('wily-cli');
cli
.disableGeneratedHelp();
`
---
$3
Outputs a generated help output. Sections of the output can be customized and/or disabled. This will automatically be called when the help option is provided.
---
$3
Sets the option name and short for the help output. Default values are help for the option, and h for the short. If short isn't provided, then the previous short will continue to be used.
#### Parameters
- option (String) Option name
- short (String) Option short
#### Examples
`javascript
const cli = require('wily-cli');
cli
.helpOption('use', '?');
`
---
$3
Set the help option description. Default is "Output usage information". Can be customized with text effects.
#### Parameters
- description (String) Custom help option description
#### Examples
`javascript
const cli = require('wily-cli');
cli
.helpOptionDescription('Display help');
`
---
$3
Sets a string that will be logged out before the help output. Can be customized with text effects.
#### Parameters
- beforeHelpString (String) String to be logged before help output
#### Examples
`javascript
const cli = require('wily-cli');
cli
.option('test', 'Test option')
.beforeHelpLog('Hello there');
// 'Hello there' will printed before the help output
`
---
$3
Sets the padding string for the help output. Default is a tab character. Can be customized with text effects.
#### Parameters
- paddingString (String) Help output padding string
#### Examples
`javascript
const cli = require('wily-cli');
cli
.helpPadding('--- ');
`
---
$3
Sets a string that will be logged out after the help output. Can be customized with text effects.
#### Parameters
- afterHelpString (String) String to be logged after help output
#### Examples
`javascript
const cli = require('wily-cli');
cli
.option('test', 'Test option')
.afterHelpLog('Hello there');
// 'Hello there' will printed after the help output
`
---
$3
Set the process to exit after the help output, or not. Default is false.
#### Parameters
- exit (Boolean) True to make the process exit after the help output, false to keep it alive
#### Examples
`javascript
const cli = require('wily-cli');
cli
.exitOnHelp(true);
`
---
$3
Set the process to exit after the version output, or not. Default is false.
#### Parameters
- exit (Boolean) True to make the process exit after the version output, false to keep it alive
#### Examples
`javascript
const cli = require('wily-cli');
cli
.exitOnVersion(true);
`
---
$3
Sets the usage section in the help output to be visible. This is the default behavior.
#### Examples
`javascript
const cli = require('wily-cli');
cli
.enableHelpUsage();
`
---
$3
Sets the commands section in the help output to be visible. This is the default behavior.
#### Examples
`javascript
const cli = require('wily-cli');
cli
.enableHelpCommands();
`
---
$3
Sets the options section in the help output to be visible. This is the default behavior.
#### Examples
`javascript
const cli = require('wily-cli');
cli
.enableHelpOptions();
`
---
$3
Sets the description section in the help output to be visible. This is the default behavior.
#### Examples
`javascript
const cli = require('wily-cli');
cli
.enableHelpDescription();
`
---
$3
Sets the usage section in the help output to not be visible.
#### Examples
`javascript
const cli = require('wily-cli');
cli
.disableHelpUsage();
`
---
$3
Sets the commands section in the help output to not be visible.
#### Examples
`javascript
const cli = require('wily-cli');
cli
.disableHelpCommands();
`
---
$3
Sets the options section in the help output to not be visible.
#### Examples
`javascript
const cli = require('wily-cli');
cli
.disableHelpOptions();
`
---
$3
Sets the description section in the help output to not be visible.
#### Examples
`javascript
const cli = require('wily-cli');
cli
.disableHelpDescription();
`
---
$3
Enables parsing of options. This is the default behavior.
#### Examples
`javascript
const cli = require('wily-cli');
cli
.enableOptions();
`
---
$3
Enables parsing of commands. This is the default behavior. Parameters will also be parsed.
#### Examples
`javascript
const cli = require('wily-cli');
cli
.enableCommands();
`
---
$3
Disables parsing of options. The options section will also not be visible in the help output.
#### Examples
`javascript
const cli = require('wily-cli');
cli
.disableOptions();
`
---
$3
Disables parsing of commmands. Parameters will also not be parsed. The commands section will also not be visible in the help output.
#### Examples
`javascript
const cli = require('wily-cli');
cli
.disableOptions();
`
---
$3
Sets the CLI to be interactive. Any children ArgParsers will be set as interactive. prompt can be customized with text effects.
#### Parameters
- prompt (String) String prompt to precede the user's input
- quitCommand (String) Name of the quit command to override the default. Default is 'quit'. Only the initial ArgParser will have the quit command, which is automatically added to an interactive CLI.
- quitCommandDescription (String) Description for the quit command. Default is 'Quit the CLI'
#### Examples
`javascript
const cli = require('wily-cli');
cli
.command('example', 'Example command')
.enableInteractivity();
// Sets the CLI to be an interactive CLI, and adds the quit command automatically to exit the CLI
`
`javascript
const cli = require('wily-cli');
cli
.command('example', 'Example command')
.enableInteractivity('cli$');
// Sets the CLI to be an interactive CLI, and sets the prompt to be 'cli$'
`
`javascript
const cli = require('wily-cli');
cli
.command('example', 'Example command')
.enableInteractivity('cli$', 'exit');
// Sets the CLI to be an interactive CLI, sets the prompt to be 'cli$', overrides the quit command name with 'exit', and adds the exit command automatically to exit the CLI
`
`javascript
const cli = require('wily-cli');
cli
.command('example', 'Example command')
.enableInteractivity('cli$', 'exit', 'Exit now!');
// Sets the CLI to be an interactive CLI, sets the prompt to be 'cli$', overrides the quit command name with 'exit', adds the exit command automatically to exit the CLI, and sets the exit command description to be 'Exit now!'
`
---
$3
Disables interactivity of the CLI.
#### Examples
`javascript
const cli = require('wily-cli');
cli
.command('example', 'Example command')
.enableInteractivity()
.disableInteractivity();
`
---
$3
Sets the interactive CLI's prompt. Must be an interactive CLI for this to do anything. Can be customized with text effects.
#### Parameters
- prompt (String) String prompt to precede the user's input
#### Examples
`javascript
const cli = require('wily-cli');
cli
.command('example', 'Example command')
.setInteractivityPrompt('cli$')
.enableInteractivity();
`
---
$3
Sets the interactive CLI's quit command, and optionally quit command description. Must be an interactive CLI for this to do anything.
#### Parameters
- quitCommand (String) Name of the quit command to override the default. Default is 'quit'. Only the initial ArgParser will have the quit command, which is automatically added to an interactive CLI.
- quitCommandDescription (String) Description for the quit command. Default is 'Quit the CLI'
#### Examples
`javascript
const cli = require('wily-cli');
cli
.command('example', 'Example command')
.setQuitInteractivityCommand('exit')
.enableInteractivity();
`
`javascript
const cli = require('wily-cli');
cli
.command('example', 'Example command')
.setQuitInteractivityCommand('exit', 'Exit now!')
.enableInteractivity();
`
---
$3
Enables the quit command for interactive CLIs. Default behavior is enabled.
#### Examples
`javascript
const cli = require('wily-cli');
cli
.enableQuitInteractivityCommand();
`
---
$3
Disables the quit command for interactive CLIs.
#### Examples
`javascript
const cli = require('wily-cli');
cli
.disableQuitInteractivityCommand();
`
---
$3
Enables the output for when missing required parameters or options are found. When this is enabled and missing required arguments are found, it will not attempt to parse any further.
#### Examples
`javascript
const cli = require('wily-cli');
cli
.enableMissingRequiredMessage();
`
---
$3
Disables the output for when missing required parameters or options are found.
#### Examples
`javascript
const cli = require('wily-cli');
cli
.disableMissingRequiredMessage();
`
---
$3
Sets the output for when missing required parameters or options are found. Default message is '[red]error[clear] Missing required argument(s): '
#### Parameters
- prompt (String) String prompt to precede the user's input
#### Examples
`javascript
const cli = require('wily-cli');
cli
.setMissingRequiredMessage('[red]Missing ');
`
---
$3
Creates an ArgParser. This is useful if you would like to create an ArgParser, but not necessarily start setting up the commands right away.
#### Examples
`javascript
const cli = require('wily-cli');
const parser = cli.argParser();
// act on parser later
`
---
$3
Set a callback to retrieve an object representing the most recent parsed results.
#### Paremeters
- cb (Function|AsyncFunction|Promise) Callback function to execute once the parsing is complete. Will be passed a result object that contains properties command, options, parameters, subCommandParameters, missingOptions, and missingParameters. The parameters and options arguments will have an _extras property if extra parameters/options are passed in via the command line for the command. missingOptions and missingParameters are Arrays, while the rest of the arguments are Objects.
#### Examples
`javascript
const cli = require('wily-cli');
cli
.command('example', 'Example command')
.onResult((result) => {
console.log(result);
});
`
---
$3
Force argument parsing instead of letting the tool wait before the process exits. This is useful if you need to continue your program after and outside of the function chaining. This does not return an ArgParser, so it will end the function chain. Typically, you will not need to call this because most logic is likely to be handled within the command callbacks.
#### Paremeters
- args (Array) Overrides the arguments to parse. The default arguments that are passed are within process.argv.
#### Returns
- {Object} An object representing the results of the parse for the command. The object is the same object as the object provided to the callback function of onResult.
#### Examples
`javascript
const cli = require('wily-cli');
let executedCommand = false;
const results = cli
.command('example', 'Example command', () => {
executedCommand = true;
})
.parse(); // chain ends here
// Arguments have been parsed. Continue program below.
console.log(executedCommand); // true
`
$3
An alternative approach to building your CLI. Pass a configuration object representing your CLI with all of the capable features of wily-cli. If you'd rather not call the same function multiple times to build your CLI, such as .command, this function can help eliminate the need to do so, and also streamlines some features, like interactivity.
#### Paremeters
- config (Object) Configuration representing the CLI to build.
#### Examples
`javascript
const cli = require('wily-cli');
const config = {
commands: [
['example', 'Example command'],
['example2', 'Second example command', () => { console.log('second example command'); }],
],
interactive: {
prompt: 'prompt$ ',
quitCommand: 'stop',
quitCommandEnabled: true,
},
switchCharacter: '/',
};
cli.from(config); // If you would like, you may continue chaining other calls off of this
`
---
CLI Configuration
These are the properites that can be added to the object passed to .from. An example configuration object using all of the properties can be found in examples/exampleConfig.js.
- commands (Array) Array of commands to add to the CLI. The commands should be arrays in the format [commandName, commandDescription, commandAction]. The command arrays are structured the same as the properties of .command.
- options (Array) Array of options to add to the CLI. The options should be arrays in the format [optionName, optionDescription, optionConfig]. The option arrays are structured the same as the properties of .option.
- parameters (Array) Array of parameters to add to the CLI. The parameters should be arrays in the format [parameterName, required, repeated]. The parameter arrays are structured the same as the properties of .parameter.
- events (Array) Array of events to add to the CLI. The events should be arrays in the format [eventName, action]. The event arrays are structured the same as the properties of .on.
- args (Array) Optional array of args parse.
- description (String) Help output description text.
- defaultCommand (String) Default command to execute if no other command is parsed.
- parameterSeparator (String) Parameter separator.
- version (String|Number) Output for the version option.
- versionOption (Array) Override the default version option long and short. The array should be in the format [versionOptionLong, versionOptionShort] - the same structure as the properties of .versionOption.
- versionOptionDescription (String) Version option description.
- helpOption (Array) Override the default help option long and short. The array should be in the format [helpOptionLong, helpOptionShort] - the same structure as the properties of .helpOption.
- helpOptionDescription (String) Help option description.
- usage (String) Help output usage text.
- switchCharacter (String) Option switch character.
- generateHelpEnabled (Boolean) Sets the generated help to be enabled or disabled.
- helpPadding (String) Padding text to append to each line of the help output.
- beforeHelpLog (String) Text to print before the generated help output.
- afterHelpLog (String) Text to print after the generated help output.
- exitOnHelp (Boolean) Sets the CLI to exit after the help option is parsed.
- exitOnVersion (Boolean) Sets the CLI to exit after the version option is parsed.
- helpUsageEnabled (Boolean) Sets usage text in the help output to dispaly or not.
- helpCommandsEnabled (Boolean) Sets commands text in the help output to dispaly or not.
- helpOptionsEnabled (Boolean) Sets options text in the help output to dispaly or not.
- helpDescriptionEnabled (Boolean) Sets description text in the help output to dispaly or not.
- optionsEnabled (Boolean) Sets the CLI options to be enabled or disabled.
- commandsEnabled (Boolean) Sets the CLI commands to be enabled or disabled.
- interactive (Object) Configuration for an interactive CLI.
- prompt (String) Interactive CLI prompt text.
- quitCommand (String) Text to override the default quit command name.
- quitCommandDescription (String) text to override the default quit command description.
- quitCommandEnabled (Boolean) Enables or disables the generated quit command.
- onResult (Function|AsyncFunction|Promise) Action to execute after the ArgParser parses. The function is the same as the function in .onResult.
- missingRequiredMessageEnabled (Boolean) Enables or disables the message that outputs if required options or parameters are missing.
- missingRequiredMessage (String) Text to override the default missing required values message.
Text Effects
Listed below are the available effects you can add into a customizable string. For example, if you add a description string like "This is a description", and you wanted to make "This is" blue, "a" green, and leave "description" with no effects, you would pass into .description this string: "[blue]This is [green]a [clear]description"
- Yellow: [yellow]
- White: [white]
- Cyan: [cyan]
- Magenta: [magenta]
- Red: [red]
- Blue: [blue]
- Black: [black]
- Green: [green]
- Gray (grey): [gray] or [grey]
- Bold: [bold]
- Dim: [dim]
- Underline: [underline]
- Strikethrough: [strike]
- Reverse: [reverse]
- Hidden: [hidden]
- Black background: [bgBlack]
- Red background: [bgRed]
- Green background: [bgGreen]
- Yellow background: [bgYellow]
- Blue background: [bgBlue]
- Magenta background: [bgMagenta]
- Cyan background: [bgCyan]
- White background: [bgWhite]
- Clear effects: [clear]
Example Automated Help Output
Provided below is the output for the store CLI example help option. You can customize the help output how you like, such as adding a description, changing the default usage line, hiding sections from being shown, and print messages before and after the help output. Any customs strings you can add can have text effects applied to them.
`
Store CLI example :)
Usage: cli.js [command] [options]
Commands:
open Open the store
close Close the store
isOpened Check if the store is open
items Manage store inventory
purchase -
Purchase an item
Options:
-h, --help Output usage information
-v, --version Output version
``