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

Always add the `command` in a validation error's "meta" section. #204

Open electrotype opened 3 years ago

electrotype commented 3 years ago

I'd like to be able to automatically display the full help of a command when a validation fails.

Let's say a command has a --port option with an associated validator: caporal.NUMBER validator. I call this command using --port notNumber: I would like to be able to catch the generated error (in my catch block) and manually call await caporal.exec(['help', COMMAND_NAME]); in order to display the full help of the command! But the executed command is currently not provided in the meta section, on such error.

Also, it would be appreciated if all errors had a dedicated code. For example: code: INVALID_OPTION_VALUE, so we can know without a doubt what the error is and be able to react to it as we want. Yes, Caporal errors currently have a name, but this value is the name of the error's constructor (if I'm not mistaken), and this name is actually minified in your distributed code... So not very solid, in my opinion.

electrotype commented 3 years ago

In case it helps someone one day, I found an ugly workaround to get the executed command, so I can display its help in case of a validation error:

let mainCommand;
const runOriginal = caporal['_run'].bind(caporal);
caporal['_run'] = async function(result, cmd) {
  mainCommand = cmd;
  return await runOriginal(result, cmd);
};

try {
  await caporal.run();
} catch (err) {
  /* use "mainCommand" if defined */ 
}