Applying Jorg Schaible's patch from CLI-177 to fix the OptionBuilder's not resetting when an Exception is thrown
git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/branches/cli-1.x@754830 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/src/java/org/apache/commons/cli/OptionBuilder.java b/src/java/org/apache/commons/cli/OptionBuilder.java
index 83e0299..60b4967 100644
--- a/src/java/org/apache/commons/cli/OptionBuilder.java
+++ b/src/java/org/apache/commons/cli/OptionBuilder.java
@@ -326,6 +326,7 @@
{
if (longopt == null)
{
+ OptionBuilder.reset();
throw new IllegalArgumentException("must specify longopt");
}
@@ -344,21 +345,23 @@
*/
public static Option create(String opt) throws IllegalArgumentException
{
- // create the option
- Option option = new Option(opt, description);
+ Option option = null;
+ try {
+ // create the option
+ option = new Option(opt, description);
- // set the option properties
- option.setLongOpt(longopt);
- option.setRequired(required);
- option.setOptionalArg(optionalArg);
- option.setArgs(numberOfArgs);
- option.setType(type);
- option.setValueSeparator(valuesep);
- option.setArgName(argName);
-
-
- // reset the OptionBuilder properties
- OptionBuilder.reset();
+ // set the option properties
+ option.setLongOpt(longopt);
+ option.setRequired(required);
+ option.setOptionalArg(optionalArg);
+ option.setArgs(numberOfArgs);
+ option.setType(type);
+ option.setValueSeparator(valuesep);
+ option.setArgName(argName);
+ } finally {
+ // reset the OptionBuilder properties
+ OptionBuilder.reset();
+ }
// return the Option instance
return option;
diff --git a/src/test/org/apache/commons/cli/OptionBuilderTest.java b/src/test/org/apache/commons/cli/OptionBuilderTest.java
index 868d263..b445a67 100644
--- a/src/test/org/apache/commons/cli/OptionBuilderTest.java
+++ b/src/test/org/apache/commons/cli/OptionBuilderTest.java
@@ -145,6 +145,33 @@
catch (IllegalArgumentException e)
{
// expected
+
+ // implicitly reset the builder
+ OptionBuilder.create( "opt" );
}
}
+
+ public void testBuilderIsResettedAlways() {
+ try
+ {
+ OptionBuilder.withDescription("JUnit").create('"');
+ fail("IllegalArgumentException expected");
+ }
+ catch (IllegalArgumentException e)
+ {
+ // expected
+ }
+ assertNull("we inherited a description", OptionBuilder.create('x').getDescription());
+
+ try
+ {
+ OptionBuilder.withDescription("JUnit").create();
+ fail("IllegalArgumentException expected");
+ }
+ catch (IllegalArgumentException e)
+ {
+ // expected
+ }
+ assertNull("we inherited a description", OptionBuilder.create('x').getDescription());
+ }
}