Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Throw CommandLineParserInternalException for immutable collections #102

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;

Expand Down Expand Up @@ -599,7 +600,7 @@ private void setPositionalArgument(final String stringValue) {
c.add(value);
}

@SuppressWarnings("unchecked")
@SuppressWarnings({"unchecked", "rawtypes"})
private void setArgument(ArgumentDefinition argumentDefinition, List<String> values) {
//special treatment for flags
if (argumentDefinition.isFlag() && values.isEmpty()){
Expand All @@ -616,9 +617,8 @@ private void setArgument(ArgumentDefinition argumentDefinition, List<String> val
// if this is a collection then we only want to clear it once at the beginning, before we process
// any of the values, unless we're in APPEND_TO_COLLECTIONS mode, in which case we leave the initial
// and append to it
@SuppressWarnings("rawtypes")
final Collection c = (Collection) argumentDefinition.getFieldValue();
c.clear();
System.err.println("Clear collection");
applyToCollection(argumentDefinition, Collection::clear);
}
values = expandListFile(values);
}
Expand Down Expand Up @@ -680,21 +680,37 @@ private void setArgument(ArgumentDefinition argumentDefinition, List<String> val

// check the argument range
checkArgumentRange(argumentDefinition, value);
// set the already parsed argument
setParsedArgumentValue(argumentDefinition, value);
}
}

if (argumentDefinition.isCollection) {
@SuppressWarnings("rawtypes")
final Collection c = (Collection) argumentDefinition.getFieldValue();
if (value == null) {
//user specified this arg=null which is interpreted as empty list
c.clear();
} else {
c.add(value);
Copy link
Collaborator

@cmnbroad cmnbroad Oct 27, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is at least one other place in this method that calls clear on a collection (line 627). We should scan the code for any places that need to be changed.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. I added a method to catch the exception while applying a consumer (either clear/add, but in the future may be others).

}
argumentDefinition.hasBeenSet = true;
@SuppressWarnings({"unchecked", "rawtypes"})
private void setParsedArgumentValue(final ArgumentDefinition argumentDefinition, final Object value) {
if (argumentDefinition.isCollection) {
if (value == null) {
applyToCollection(argumentDefinition, Collection::clear);
} else {
argumentDefinition.setFieldValue(value);
argumentDefinition.hasBeenSet = true;
applyToCollection(argumentDefinition, c -> c.add(value));
}
argumentDefinition.hasBeenSet = true;
} else {
argumentDefinition.setFieldValue(value);
argumentDefinition.hasBeenSet = true;
}
}

// apply a function to a collection, catching UnsuportedOperationException into a more informative
@SuppressWarnings("rawtypes")
private void applyToCollection(final ArgumentDefinition argumentDefinitionCollection, final Consumer<Collection> function) {

final Collection c = (Collection) argumentDefinitionCollection.getFieldValue();
try {
function.accept(c);
} catch (UnsupportedOperationException e) {
throw new CommandLineException.CommandLineParserInternalException(String.format("Collection arguments seems immutable: \"%s\". Initialized collection should support the clear and add methods, but %s does not.",
argumentDefinitionCollection.getLongName(),
c.getClass().getName()));
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,36 @@ public void testCollectionThatCannotBeAutoInitialized() {
new CommandLineArgumentParser(o);
}

class ImmutableCollectionArguments {
@Argument(optional = true)
public List<String> LIST = Arrays.asList("T");
}

@DataProvider
public Object[][] argsForImmmutableCollectionTest() {
return new Object[][] {
// replace mode
{Collections.EMPTY_SET, // parser options
new String[]{"--LIST", "A"}}, // arguments (real)
// replace mode
{Collections.EMPTY_SET, // parser options
new String[]{"--LIST", "null"}}, // arguments (null)

// append mode
{Collections.singleton(CommandLineParserOptions.APPEND_TO_COLLECTIONS), // parser options
new String[]{"--LIST", "A"}}, // arguments (real)
// append mode
{Collections.singleton(CommandLineParserOptions.APPEND_TO_COLLECTIONS), // parser options
new String[]{"--LIST", "null"}}, // arguments (null)
};
}

@Test(dataProvider = "argsForImmmutableCollectionTest", expectedExceptions = CommandLineException.CommandLineParserInternalException.class)
public void testCollectionThatIsImmmutable(final Set<CommandLineParserOptions> opts, final String[] args) {
final ImmutableCollectionArguments o = new ImmutableCollectionArguments();
new CommandLineArgumentParser(o, Collections.emptyList(), opts).parseArguments(System.err, args);
}

//////////////////////////////////////////////////////////////////
// Helper methods

Expand Down