Page cover image

init

Initialize your CLI after defining its commands.

init(cb?:SaffronInitCallback): void

This function must be called after all commands have been configured. It will then search for and load your application's configuration file and initialize Yargs which will parse process.argv. The parsed arguments and configuration are then passed to the appropriate command's handler.

This function sets the following global parameters:

  • Calls yargs.version() with the version from your application's package.json, ensuring that if the application is invoked with the --version option, Yargs will print the correct version.

  • Calls yargs.wrap() with yargs.terminalWidth() to instruct Yargs to use the full width of the terminal before wrapping lines.

  • Calls yargs.help(), ensuring that if the application is invoked with the --help flag, Yargs will print usage instructions and exit early without calling a handler.

This function accepts an optional callback, SaffronInitCallback that will be passed the global yargs object which can be used to perform any additional global configuration of Yargs.

Handling Yargs Output Manually

This callback may optionally return a yargs.ParseCallback that can can be used to intercept output from Yargs, manipulate it, and write it to an output stream explicitly.

Example:

cli.js
import * as cli from '@darkobits/saffron';

// Configure commands for the application.
cli.command({
  // ...
});

cli.command({
  // ...
});

cli.init(yargs => {
  yargs.wrap(120);

  // Optionally return a ParseCallback.
  return (err, argv, output) => {
    if (err) {
      process.stderr.write(err.message);
      process.exit(err.code ?? 1);
    }

    if (output) {
      process.stdout.write(output);
      process.exit(0);
    }
  };
});

Last updated