adonisjs / ace

Node.js framework for creating command line applications
MIT License
366 stars 35 forks source link

The `--help` prints an argument error after the help message #162

Open webNeat opened 3 days ago

webNeat commented 3 days ago

Package version

13.3.0

Describe the bug

Hello,

I am trying to use ace to build a cli tool outside of Adonis. Inspired by the toolkit command I wrote the following code:

import "reflect-metadata";
import { BaseCommand, args, Kernel, ListLoader, HelpCommand } from "@adonisjs/ace";

class Demo extends BaseCommand {
  public static commandName = "demo";

  @args.string({ description: "first arg" })
  declare first_arg: string;

  @args.string({ description: "second arg" })
  declare second_arg: string;

  public async run() {
    this.logger.info(`Hello from demo command`);
  }
}

const kernel = Kernel.create();
kernel.addLoader(new ListLoader([Demo]));

kernel.defineFlag("help", {
  type: "boolean",
  description: HelpCommand.description,
});
kernel.on("help", async (command, $kernel, parsed) => {
  parsed.args.unshift(command.commandName);
  const help = new HelpCommand($kernel, parsed, kernel.ui, kernel.prompt);
  await help.exec();
  return $kernel.shortcircuit();
});

await kernel.handle(process.argv.splice(2));

My understanding is that this part makes the flag --help available for all commands:

kernel.defineFlag("help", {
  type: "boolean",
  description: HelpCommand.description,
});
kernel.on("help", async (command, $kernel, parsed) => {
  parsed.args.unshift(command.commandName);
  const help = new HelpCommand($kernel, parsed, kernel.ui, kernel.prompt);
  await help.exec();
  return $kernel.shortcircuit();
});

However, when I run node --import tsx main.ts demo --help I get the following error:

Usage:
  demo <first-arg> <second-arg>

Arguments:
  first-arg   first arg
  second-arg  second arg
  ERROR   Missing required argument "second_arg"

Note the error at the end of the output.

This only happens when my Demo command has more than one argument.

Am I doing something wrong here?

Reproduction repo

https://github.com/webNeat/adonis-ace-bug

thetutlage commented 18 hours ago

Yup, it indeed looks like a bug. Ideally this line of code https://github.com/adonisjs/ace/blob/13.x/src/kernel.ts#L335 should be after the shortcircuit conditional but no idea why I have put it before it.

Lemme run some tests and then push a fix