Skip to content

Commit

Permalink
Missing required option doesn't throw
Browse files Browse the repository at this point in the history
This is a proposed fix for: airlift#22

This approach introduces a ParseResult object which allows for the collection of multiple parse errors from the user input
and then provides this back to the caller to decide what to do. E.G. send the user the to the help dialog.

This keeps the existing API and fits with the desire to keep the parsing logic agnostic to the details of the HelpOption.

The existing pattern still fails fast with an exception:

```java
MyCommand command = SingleCommand.singleCommand(MyCommand.class).parse(args);
```

This fix introduces the following pattern from the caller's perspective:

```java
ParseResult parseResult = new ParseResult();
MyCommand command = SingleCommand.singleCommand(MyCommand.class).parse(args, parseResult);
command.helpOption.runOrShowHelp(parseResult, command);
```

The call to runOrShowHelp will:
* Run the command if there are no parse errors and help has not been requsted
* Will display help if it is requested regardless of whether there are parse errors
* Will display parse errors and help when there are parse errors
  • Loading branch information
jontodd committed Jan 26, 2014
1 parent cd9c8d8 commit 66d85bb
Show file tree
Hide file tree
Showing 4 changed files with 110 additions and 10 deletions.
24 changes: 24 additions & 0 deletions src/main/java/io/airlift/airline/HelpOption.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,28 @@ public boolean showHelpIfRequested()
}
return help;
}

/**
* Run the runnable if there are no parse errors and if help was not requested
*/
public void runOrShowHelp(ParseResult parseResult, Runnable runnable) {
if (parseResult.hasErrors()) {
help = true;
System.out.println(parseResult.getErrorMessage());
}

if (help) {
Help.help(commandMetadata);
return;
}

runnable.run();
}

/**
* Run the runnable if help was not requested
*/
public void runOrShowHelp(Runnable runnable) {
runOrShowHelp(new ParseResult(), runnable);
}
}
36 changes: 36 additions & 0 deletions src/main/java/io/airlift/airline/ParseResult.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package io.airlift.airline;

import com.google.common.collect.ImmutableList;

import java.util.LinkedList;
import java.util.List;

public class ParseResult {
private List<ParseException> errors = new LinkedList<ParseException>();

public void addError(ParseException error) {
errors.add(error);
}

public boolean hasErrors() {
return errors.size() != 0;
}

public List<ParseException> getErrors() {
return ImmutableList.copyOf(errors);
}

public String getErrorMessage() {
if (errors.size() >= 1) {
StringBuffer sb = new StringBuffer();
sb.append("ERROR: Encountered problems parsing arguments:\n");
for (ParseException error : errors) {
sb.append(" - ").append(error.getMessage()).append("\n");
}
sb.append("\n");
return sb.toString();
} else {
throw new IllegalStateException("There are no errors to build a message for.");
}
}
}
37 changes: 28 additions & 9 deletions src/main/java/io/airlift/airline/SingleCommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -57,12 +57,31 @@ public C parse(String... args)
}

public C parse(Iterable<String> args)
{
ParseResult parseResult = new ParseResult();
C command = parse(parseResult, args);

// For backward compatibility we fail fast here. Given that exceptions aren't a great way to handle user errors
// since there can be multiple we may consider deprecating this approach.
if (parseResult.hasErrors()) {
throw parseResult.getErrors().get(0);
}

return command;
}

public C parse(ParseResult parseResult, String... args)
{
return parse(parseResult, ImmutableList.copyOf(args));
}

public C parse(ParseResult parseResult, Iterable<String> args)
{
checkNotNull(args, "args is null");

Parser parser = new Parser();
ParseState state = parser.parseCommand(commandMetadata, args);
validate(state);
validate(state, parseResult);

CommandMetadata command = state.getCommand();

Expand All @@ -75,35 +94,35 @@ public C parse(Iterable<String> args)
ImmutableMap.<Class<?>, Object>of(CommandMetadata.class, commandMetadata));
}

private void validate(ParseState state)
private void validate(ParseState state, ParseResult parseResult)
{
CommandMetadata command = state.getCommand();
if (command == null) {
List<String> unparsedInput = state.getUnparsedInput();
if (unparsedInput.isEmpty()) {
throw new ParseCommandMissingException();
parseResult.addError(new ParseCommandMissingException());
}
else {
throw new ParseCommandUnrecognizedException(unparsedInput);
parseResult.addError(new ParseCommandUnrecognizedException(unparsedInput));
}
}

ArgumentsMetadata arguments = command.getArguments();
if (state.getParsedArguments().isEmpty() && arguments != null && arguments.isRequired()) {
throw new ParseArgumentsMissingException(arguments.getTitle());
parseResult.addError(new ParseArgumentsMissingException(arguments.getTitle()));
}

if (!state.getUnparsedInput().isEmpty()) {
throw new ParseArgumentsUnexpectedException(state.getUnparsedInput());
parseResult.addError(new ParseArgumentsUnexpectedException(state.getUnparsedInput()));
}

if (state.getLocation() == Context.OPTION) {
throw new ParseOptionMissingValueException(state.getCurrentOption().getTitle());
parseResult.addError(new ParseOptionMissingValueException(state.getCurrentOption().getTitle()));
}

for (OptionMetadata option : command.getAllOptions()) {
if (option.isRequired() && !state.getParsedOptions().containsKey(option)) {
throw new ParseOptionMissingException(option.getOptions().iterator().next());
parseResult.addError(new ParseOptionMissingException(option.getOptions().iterator().next()));
}
}
}
Expand Down
23 changes: 22 additions & 1 deletion src/test/java/io/airlift/airline/SingleCommandTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,13 @@
import org.testng.annotations.Test;

import javax.inject.Inject;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

import static com.google.common.base.Predicates.compose;
import static com.google.common.base.Predicates.equalTo;
import static com.google.common.base.Predicates.instanceOf;
import static com.google.common.collect.Iterables.find;
import static io.airlift.airline.SingleCommand.singleCommand;
import static org.testng.Assert.assertTrue;
Expand Down Expand Up @@ -244,12 +244,27 @@ public void requiredMainParameters()
singleCommand(ArgsRequired.class).parse();
}

@Test
public void requiredMainParamertersWithParseResult() {
ParseResult result = new ParseResult();
singleCommand(ArgsRequired.class).parse(result);
assertParseResultHasErrorOfType(result, ParseException.class);
}

@Test(expectedExceptions = ParseException.class, expectedExceptionsMessageRegExp = ".*option.*missing.*")
public void requiredOptions()
{
singleCommand(OptionsRequired.class).parse();
}

@Test
public void requiredOptionsWithParseResult()
{
ParseResult result = new ParseResult();
singleCommand(OptionsRequired.class).parse(result);
assertParseResultHasErrorOfType(result, ParseException.class);
}

@Test
public void ignoresOptionalOptions()
{
Expand Down Expand Up @@ -388,4 +403,10 @@ public static class CommandTest
public Boolean interactive = false;

}

private void assertParseResultHasErrorOfType(ParseResult result, Class clazz) {
Assert.assertEquals(result.hasErrors(), true);
String errorMessage = String.format("Expected ParseResult to contain at least one instance of: '%s'", clazz);
Assert.assertNotNull(find(result.getErrors(), instanceOf(clazz)), errorMessage);
}
}

0 comments on commit 66d85bb

Please sign in to comment.