From f42fa6f865bcb3aec681759c6217af36794fcc18 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20G=C3=B3mez-S=C3=A1nchez?= Date: Wed, 11 Oct 2017 11:06:00 +0200 Subject: [PATCH] Throw CommandLineParserInternalException for immutable collections --- .../argparser/CommandLineArgumentParser.java | 16 +++++++++++----- .../argparser/CollectionArgumentUnitTests.java | 11 +++++++++++ 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/broadinstitute/barclay/argparser/CommandLineArgumentParser.java b/src/main/java/org/broadinstitute/barclay/argparser/CommandLineArgumentParser.java index 1c32f2db..c83386b9 100644 --- a/src/main/java/org/broadinstitute/barclay/argparser/CommandLineArgumentParser.java +++ b/src/main/java/org/broadinstitute/barclay/argparser/CommandLineArgumentParser.java @@ -684,11 +684,17 @@ private void setArgument(ArgumentDefinition argumentDefinition, List val 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); + try { + if (value == null) { + //user specified this arg=null which is interpreted as empty list + c.clear(); + } else { + c.add(value); + } + } 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.", + argumentDefinition.getLongName(), + c.getClass().getName())); } argumentDefinition.hasBeenSet = true; } else { diff --git a/src/test/java/org/broadinstitute/barclay/argparser/CollectionArgumentUnitTests.java b/src/test/java/org/broadinstitute/barclay/argparser/CollectionArgumentUnitTests.java index 9b21bae5..16252abd 100644 --- a/src/test/java/org/broadinstitute/barclay/argparser/CollectionArgumentUnitTests.java +++ b/src/test/java/org/broadinstitute/barclay/argparser/CollectionArgumentUnitTests.java @@ -277,6 +277,17 @@ public void testCollectionThatCannotBeAutoInitialized() { new CommandLineArgumentParser(o); } + class ImmutableCollectionArguments { + @Argument + public List LIST = Collections.emptyList(); + } + + @Test(expectedExceptions = CommandLineException.CommandLineParserInternalException.class) + public void testCollectionThatIsImmmutable() { + final ImmutableCollectionArguments o = new ImmutableCollectionArguments(); + new CommandLineArgumentParser(o).parseArguments(System.err, new String[]{"--LIST", "A"}); + } + ////////////////////////////////////////////////////////////////// // Helper methods