@@ -344,36 +344,52 @@ protected Options toOptions() {
344
344
public ExitStatus processCommand () {
345
345
CommandLineParser parser = new DefaultParser ();
346
346
CommandLine cmdLine ;
347
- try {
348
- cmdLine = parser .parse (toOptions (), getExtraArgs ().toArray (new String [0 ]));
349
- } catch (ParseException ex ) {
350
- String msg = ex .getMessage ();
351
- assert msg != null ;
352
- return handleInvalidCommand (msg );
353
- }
354
347
355
- if (cmdLine .hasOption (NO_COLOR_OPTION )) {
356
- handleNoColor ();
357
- }
358
-
359
- if (cmdLine .hasOption (QUIET_OPTION )) {
360
- handleQuiet ();
361
- }
348
+ // this uses a two phase approach where:
349
+ // phase 1: checks if help or version are used
350
+ // phase 2: executes the command
362
351
352
+ // phase 1
363
353
ExitStatus retval = null ;
364
- if (cmdLine .hasOption (VERSION_OPTION )) {
365
- showVersion ();
366
- retval = ExitCode .OK .exit ();
367
- } else if (cmdLine .hasOption (HELP_OPTION )) {
368
- showHelp ();
369
- retval = ExitCode .OK .exit ();
370
- // } else {
371
- // retval = handleInvalidCommand(commandResult, options,
372
- // "Invalid command arguments: " +
373
- // cmdLine.getArgList().stream().collect(Collectors.joining(" ")));
354
+ {
355
+ try {
356
+ Options phase1Options = new Options ();
357
+ phase1Options .addOption (HELP_OPTION );
358
+ phase1Options .addOption (VERSION_OPTION );
359
+
360
+ cmdLine = parser .parse (phase1Options , getExtraArgs ().toArray (new String [0 ]), true );
361
+ } catch (ParseException ex ) {
362
+ String msg = ex .getMessage ();
363
+ assert msg != null ;
364
+ return handleInvalidCommand (msg );
365
+ }
366
+
367
+ if (cmdLine .hasOption (VERSION_OPTION )) {
368
+ showVersion ();
369
+ retval = ExitCode .OK .exit ();
370
+ } else if (cmdLine .hasOption (HELP_OPTION )) {
371
+ showHelp ();
372
+ retval = ExitCode .OK .exit ();
373
+ }
374
374
}
375
375
376
376
if (retval == null ) {
377
+ // phase 2
378
+ try {
379
+ cmdLine = parser .parse (toOptions (), getExtraArgs ().toArray (new String [0 ]));
380
+ } catch (ParseException ex ) {
381
+ String msg = ex .getMessage ();
382
+ assert msg != null ;
383
+ return handleInvalidCommand (msg );
384
+ }
385
+
386
+ if (cmdLine .hasOption (NO_COLOR_OPTION )) {
387
+ handleNoColor ();
388
+ }
389
+
390
+ if (cmdLine .hasOption (QUIET_OPTION )) {
391
+ handleQuiet ();
392
+ }
377
393
retval = invokeCommand (cmdLine );
378
394
}
379
395
0 commit comments