mattallty / Caporal.js

A full-featured framework for building command line applications (cli) with node.js
MIT License
3.44k stars 97 forks source link

Support for multiple actions #209

Open chriscalo opened 3 years ago

chriscalo commented 3 years ago

Is your feature request related to a problem? Please describe. It's at times useful to have multiple action functions run in succession. This makes it easier to keep things DRY when there's reusable logic and can help decompose large functions into smaller composable pieces.

Describe the solution you'd like Much like Express, it seems reasonable to support multiple action functions with some mechanism to continue or not.

#!/usr/bin/env node
const { program } = require("@caporal/core");

program.action(({ args, options, next }) => {
  if (signedIn()) {
    next();
  } else {
    throw new Error("You must sign in first");
  }
});

program.action(({ args, options }) => {
  console.log("Hello, world!");
});

program.run();

Describe alternatives you've considered There's a workaround that looks like the following:

#!/usr/bin/env node
const { program } = require("@caporal/core");

program.action({ args, options } => {
  signinRequired();
  console.log("Hello, world!");
});

program.run();

function signinRequired() {
  if (signedIn()) {
    next();
  } else {
    throw new Error("You must sign in first");
  }
}

This works, but things could be tidier and simpler with separate functions. One problem the workaround requires dealing with is passing along arguments from the action handler ({ args, options }) to the signinRequired() function if they're needed.

Additional context None.

Would you be able to work on it and provide a pull request ?