Skip to content

[Feature Request] postParse hooks #1976

@aweebit

Description

@aweebit

I am currently working on recommander, a library extending Commander's functionality by features that I consider reasonable additions despite there having been little interest shown for them here. It already has async argParser support (#1900), and I would like to add Option.requires() to solve #1802 and something like Option.unrequires() to solve #1855.

Both the checks of the option requirement constraints and the awaiting of options and arguments have to be done after the parsing is finished, so it would be great to have a hook event fired at this point. postParse would be a good name for it.

Currently, the same code has to be run to in three places to simulate such a hook:

  • in a preSubcommand hook
  • for the leaf command in a preAction hook
  • for the leaf command at the end of .parse() / .parseAsync() calls in case it does not have an action handler

To enable the root command on which .parse() / .parseAsync() was called to find the leaf command, the dispatched subcommand needs to be stored in a variable at each level of the command hierarchy. Here are the code lines responsible for this in recommander/lib/command.js:

// in the constructor
const preSubcommandHook = (thisCommand, subcommand) => {
  this.__recommander_dispatchedSubcommand =
    /** @type {Command} */ (subcommand);
  this.__recommander_dispatchedSubcommand
    .__recommander_newParseState(this.__recommander_asyncParsing);
  return this.__recommander_await();
};
this.hook('preSubcommand', preSubcommandHook);
// in a subroutine used by .parse() and .parseAsync()
let leafCommand;
for (
  leafCommand = this;
  leafCommand.__recommander_dispatchedSubcommand;
  leafCommand = leafCommand.__recommander_dispatchedSubcommand
);
leafCommand.__recommander_await(); // in case it has no action handler

Very annoying and unnecessary! This shows postParse hooks are a must-have feature for subclasses.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions