commons-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Michael Heuer <heue...@acm.org>
Subject [CLI1.x] help option doesn't work if there is a required option
Date Thu, 12 Mar 2009 18:02:44 GMT
Hello,

My use case is -h,--help text prints to STDOUT and command line errors
print to STDERR.

This works fine in the simple case

Options options = new Options();
HelpFormatter helpFormatter = new HelpFormatter();
Option help = new Option("h", "help", false, "print help text to STDOUT");
help.setRequired(false);
options.addOption(help);

try
{
  CommandLineParser parser = new PosixParser();
  CommandLine commandLine = parser.parse(options, args);
  if (commandLine.hasOption(help.getOpt()))
  {
    helpFormatter.printHelp(...
  }
  ...
}
catch (ParseException e)
{
  System.err.println(e.getMessage() + "\n");
  helpFormatter.printHelp(new PrintWriter(System.err, true),  ...
}


But if there is a missing required option, the help part is unreachable,
since a MissingOptionException is thrown

Options options = new Options();
HelpFormatter helpFormatter = new HelpFormatter();
Option help = new Option("h", "help", false, "print help text to STDOUT");
help.setRequired(false);
Option foo = new Option(...);
foo.setRequired(true);
options.addOption(help);
options.addOption(foo);

try
{
  CommandLineParser parser = new PosixParser();
  CommandLine commandLine = parser.parse(options, args);
  if (commandLine.hasOption(help.getOpt()))
  {
    helpFormatter.printHelp(...
  }
  ...
}
catch (ParseException e)
{
  System.err.println(e.getMessage() + "\n");
  helpFormatter.printHelp(new PrintWriter(System.err, true),  ...
}


I could move the help part to the catch block, but there is no way to
query whether the help option was found.

catch (ParseException e)
{
  if ( help was found )
  {
    helpFormatter.printHelp(...
  }
  else
  {
    System.err.println(e.getMessage() + "\n");
    helpFormatter.printHelp(new PrintWriter(System.err, true),  ...
  }
}

   michael


---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@commons.apache.org
For additional commands, e-mail: user-help@commons.apache.org


Mime
View raw message