bagofcli

A bag of utility functions for building command-line tools: command and option parsing backed by [commander](https://www.npmjs.com/package/commander), child process execution, process exit handling, file and configuration lookup, and coloured console logging.
Source:
Example
import bag from "bagofcli";

const actions = {
  commands: {
    hello: {
      action: function (command) {
        console.log("Hello %s", command.args[0]);
      },
    },
  },
};
bag.command(import.meta.dirname, actions);

Methods

(static) command(base, actionsopt, optsopt) → {void}

Parse command line arguments and execute actions based on the specified commands. Uses commander to provide `-V` / `--version` flags to display the version number, and `-h` / `--help` flags to display the help info. Commands, their positional arguments, and the global and command options are declared in the command file, while `actions` provides the action handler of each command. A command without declared args accepts any positional arguments by default, a command declared with `allowExcessArguments: false` rejects unexpected ones while parsing, before the action handler is called, and the process exits with status code 1. An option declared with `choices` only accepts one of the listed values, commander rejects any other value while parsing, before the action handler is called, and the process exits with status code 1. Likewise, an option declared with `min`, `max`, or `integer` only accepts a number (or an integer when `integer` is true) within the inclusive range. Arguments and options are validated against the rules declared in the command file before the action handler is called, the process exits with status code 1 without calling the action handler when any of them is invalid.
Source:
Parameters:
Name Type Attributes Description
base string Base directory where the client module is located. Used as the base directory to locate the command file and the package.json file, which is expected to be at `../package.json` relative to `base`. Ideally this is the directory of the client's module, e.g. `lib`.
actions Actions <optional>
Action handlers for commands, see module:bagofcli~Actions.
opts Object <optional>
Optional settings.
Name Type Attributes Default Description
commandFile string <optional>
'../conf/commands.json' Relative path to the command file from `base`.
Returns:
Type:
void
Example
// conf/commands.json
// {
//   "options": [
//     { "arg": "-f, --file <file>", "desc": "A global option" }
//   ],
//   "commands": {
//     "greet": {
//       "desc": "Greet someone",
//       "args": [{ "name": "name", "rules": ["required"] }],
//       "options": [{ "arg": "-s, --shout", "desc": "A command option" }]
//     }
//   }
// }
bag.command(import.meta.dirname, {
  commands: {
    greet: {
      action: function (command) {
        // command.args[0] is the name positional argument
        // command.shout is the command option
        // command.file is the global option
      },
    },
  },
});

(static) exec(command, fallthrough, cb) → {void}

Execute a one-liner command. The output emitted on stderr and stdout of the child process will be written to process.stdout and process.stderr of this process. Fallthrough is handy in situation where there are multiple execs running in sequence/parallel, and they all have to be executed regardless of success/error on either one of them.
Source:
Parameters:
Name Type Description
command string Command to execute.
fallthrough boolean Allow error to be camouflaged as a non-error, in which case the error is passed as the result.
cb ExecCallback Standard `cb(err, result)` callback.
Returns:
Type:
void

(static) execAndCollect(command, fallthrough, cb) → {void}

Execute a one-liner command and collect the output. The output emitted on stderr and stdout of the child process will be collected and passed on to the given callback. Fallthrough is handy in situation where there are multiple execs running in sequence/parallel, and they all have to be executed regardless of success/error on either one of them.
Source:
Parameters:
Name Type Description
command string Command to execute.
fallthrough boolean Allow error to be camouflaged as a non-error, in which case the error is passed as the result.
cb ExecAndCollectCallback `cb(err, stdOutOutput, stdErrOutput, result)` callback.
Returns:
Type:
void

(static) exit(erropt, nullable) → {void}

Handle process exit based on the existence of error. This is handy for command-line tools to use as the final callback. Exit status code 1 indicates an error, exit status code 0 indicates a success. Error message will be logged to the console. This function can be used as a standard `cb(err, result)` callback, the result is not declared in the signature because it is not used, the process simply exits with status code 0 when there is no error.
Source:
Parameters:
Name Type Attributes Description
err ExitError <optional>
<nullable>
Error object, its existence indicates the occurrence of an error, a non-Error object is logged as JSON.
Returns:
Type:
void

(static) exitCb(errorCbopt, successCbopt) → {ExitCallback.<T>}

A higher order function that returns a process exit callback, with error and success callbacks to handle error and result accordingly. Exit status code 1 indicates an error, exit status code 0 indicates a success.
Source:
Parameters:
Name Type Attributes Description
errorCb ExitErrorCallback <optional>
Error callback in the form `errorCb(err)`, defaults to logging the error message to console error.
successCb ExitSuccessCallback.<T> <optional>
Success callback in the form `successCb(result)`, defaults to logging the result to console log.
Returns:
Type:
ExitCallback.<T>
Standard `cb(err, result)` exit callback.

(static) files(items, optsopt) → {Array.<string>}

Get an array of files contained in specified items. When a directory is specified, all files contained within that directory and its sub-directories will be included.
Source:
Parameters:
Name Type Attributes Description
items Array.<string> Array of files and/or directories.
opts Object <optional>
Optional settings.
Name Type Attributes Description
match string <optional>
Regular expression to match against the file path, only the matching files will be included.
Returns:
Type:
Array.<string>
All files.

(static) logStepHeading(message, optsopt) → {void}

Display log step heading message on the console.
Source:
Parameters:
Name Type Attributes Description
message string Heading message to be displayed.
opts Object <optional>
Optional settings.
Name Type Attributes Description
labels Array.<string> <optional>
Labels to be displayed before the message.
Returns:
Type:
void

(static) logStepItemError(message, optsopt) → {void}

Display log step item error message on the console error.
Source:
Parameters:
Name Type Attributes Description
message string Error message to be displayed.
opts Object <optional>
Optional settings.
Name Type Attributes Description
labels Array.<string> <optional>
Labels to be displayed before the message.
Returns:
Type:
void

(static) logStepItemSuccess(message, optsopt) → {void}

Display log step item success message on the console.
Source:
Parameters:
Name Type Attributes Description
message string Success message to be displayed.
opts Object <optional>
Optional settings.
Name Type Attributes Description
labels Array.<string> <optional>
Labels to be displayed before the message.
Returns:
Type:
void

(static) logStepItemWarning(message, optsopt) → {void}

Display log step item warning message on the console.
Source:
Parameters:
Name Type Attributes Description
message string Warning message to be displayed.
opts Object <optional>
Optional settings.
Name Type Attributes Description
labels Array.<string> <optional>
Labels to be displayed before the message.
Returns:
Type:
void

(static) lookupConfig(keys, opts, cb) → {void}

Lookup config values for the specified keys in the following order: - environment variable - if optional file is specified, then check for the value inside the file, the file type is determined by the file extension (.json, .yaml, or .yml) - if optional prompt is set to true, then prompt the user for the config values that are not found in the environment variable and the file the value typed in by the user is masked when the key contains the word password (case insensitive) The file is located using module:bagofcli.lookupFile.
Source:
Parameters:
Name Type Description
keys Array.<string> | string Configuration keys to look up.
opts Object Settings.
Name Type Attributes Default Description
file string <optional>
File name to look up configuration values from.
prompt boolean <optional>
false Prompt the user for missing configuration values.
cb LookupConfigCallback Standard `cb(err, result)` callback, the result is an object of configuration values keyed by configuration key.
Throws:
When the configuration file extension is not supported.
Type
Error
Returns:
Type:
void

(static) lookupFile(file, optsopt) → {Buffer}

Synchronously read file based on these rules: - if path is absolute, then check file at absolute path first - if path is relative, then check file at current working directory - if none of the above exists, check file at user home directory - if none exists, throw an error This allows simple file lookup which allows various locations.
Source:
Parameters:
Name Type Attributes Description
file string File name to read.
opts Object <optional>
Optional settings.
Name Type Attributes Description
platform string <optional>
Platform override, defaults to the current process platform.
Throws:
When the file can not be read from any of the locations.
Type
Error
Returns:
Type:
Buffer
File content.

(static) spawn(command, args, cb) → {void}

Execute a command with an array of arguments. The output emitted on stdout and stderr of the child process will be written to process.stdout and process.stderr of this process, without any additional newline.
Source:
Parameters:
Name Type Description
command string Command to execute.
args Array.<string> Command arguments.
cb SpawnCallback Standard `cb(err, result)` callback, the result is the exit code, and the error exists when the exit code is not 0.
Returns:
Type:
void
Example
// will be executed as: make -f somemakefile target1 target2 target3
bag.spawn("make", ["-f", "somemakefile", "target1", "target2", "target3"], cb);

Type Definitions

Actions

Action handlers for commands in the form `{ commands: { : { action: function (command) {} } } }`. The command name is mapped to the command name specified in the command file. Each action handler is called with a module:bagofcli~CommandArg. The TypeScript type is defined in types.d.ts.
Source:
Type:
  • ActionsType

CommandArg

Object passed to a command action handler, with these properties: - `args` (`Array`): positional arguments, in the order they were passed in - `name` (`Function`): function that returns the name of the invoked command Besides those, every parsed option is available as a direct property keyed by the option's long flag in camel case (e.g. `--some-opt ` is available as `someOpt`). This covers both the command's own options and the global options. When a global option and a command option share the same name, the global option value takes precedence. The TypeScript type is defined in types.d.ts.
Source:
Type:
  • CommandArgType