CLI-269: Introduce CommandLine.Builder
git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@1784363 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/src/main/java/org/apache/commons/cli/CommandLine.java b/src/main/java/org/apache/commons/cli/CommandLine.java
index 6890e6f..a6dff13 100644
--- a/src/main/java/org/apache/commons/cli/CommandLine.java
+++ b/src/main/java/org/apache/commons/cli/CommandLine.java
@@ -377,4 +377,42 @@
// return the array
return processed.toArray(optionsArray);
}
+
+ /**
+ * A nested builder class to create <code>CommandLine</code> instance
+ * using descriptive methods.
+ *
+ * @since 1.4
+ */
+ public static final class Builder
+ {
+ private final CommandLine commandLine = new CommandLine();
+
+ /**
+ * Add an option to the command line. The values of the option are stored.
+ *
+ * @param opt the processed option
+ */
+ public Builder addOption( Option opt )
+ {
+ commandLine.addOption( opt );
+ return this;
+ }
+
+ /**
+ * Add left-over unrecognized option/argument.
+ *
+ * @param arg the unrecognized option/argument.
+ */
+ public Builder addArg( String arg )
+ {
+ commandLine.addArg( arg );
+ return this;
+ }
+
+ public CommandLine build()
+ {
+ return commandLine;
+ }
+ }
}
diff --git a/src/test/java/org/apache/commons/cli/CommandLineTest.java b/src/test/java/org/apache/commons/cli/CommandLineTest.java
index 60a0c91..a25fb02 100644
--- a/src/test/java/org/apache/commons/cli/CommandLineTest.java
+++ b/src/test/java/org/apache/commons/cli/CommandLineTest.java
@@ -76,4 +76,18 @@
assertEquals(123, ((Number) cmd.getParsedOptionValue("i")).intValue());
assertEquals("foo", cmd.getParsedOptionValue("f"));
}
+
+ @Test
+ public void testBuilder()
+ throws Exception
+ {
+ CommandLine.Builder builder = new CommandLine.Builder();
+ builder.addArg( "foo" ).addArg( "bar" );
+ builder.addOption( Option.builder( "T" ).build() );
+ CommandLine cmd = builder.build();
+
+ assertEquals( "foo", cmd.getArgs()[0] );
+ assertEquals( "bar", cmd.getArgList().get( 1 ) );
+ assertEquals( "T", cmd.getOptions()[0].getOpt() );
+ }
}