Skip to content

Commit dc45fde

Browse files
committed
CLI-269: Introduce CommandLine.Builder
git-svn-id: https://svn.apache.org/repos/asf/commons/proper/cli/trunk@1784363 13f79535-47bb-0310-9956-ffa450edef68
1 parent 0f56df9 commit dc45fde

2 files changed

Lines changed: 52 additions & 0 deletions

File tree

src/main/java/org/apache/commons/cli/CommandLine.java

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -377,4 +377,42 @@ public Option[] getOptions()
377377
// return the array
378378
return processed.toArray(optionsArray);
379379
}
380+
381+
/**
382+
* A nested builder class to create <code>CommandLine</code> instance
383+
* using descriptive methods.
384+
*
385+
* @since 1.4
386+
*/
387+
public static final class Builder
388+
{
389+
private final CommandLine commandLine = new CommandLine();
390+
391+
/**
392+
* Add an option to the command line. The values of the option are stored.
393+
*
394+
* @param opt the processed option
395+
*/
396+
public Builder addOption( Option opt )
397+
{
398+
commandLine.addOption( opt );
399+
return this;
400+
}
401+
402+
/**
403+
* Add left-over unrecognized option/argument.
404+
*
405+
* @param arg the unrecognized option/argument.
406+
*/
407+
public Builder addArg( String arg )
408+
{
409+
commandLine.addArg( arg );
410+
return this;
411+
}
412+
413+
public CommandLine build()
414+
{
415+
return commandLine;
416+
}
417+
}
380418
}

src/test/java/org/apache/commons/cli/CommandLineTest.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,4 +76,18 @@ public void testGetParsedOptionValue() throws Exception {
7676
assertEquals(123, ((Number) cmd.getParsedOptionValue("i")).intValue());
7777
assertEquals("foo", cmd.getParsedOptionValue("f"));
7878
}
79+
80+
@Test
81+
public void testBuilder()
82+
throws Exception
83+
{
84+
CommandLine.Builder builder = new CommandLine.Builder();
85+
builder.addArg( "foo" ).addArg( "bar" );
86+
builder.addOption( Option.builder( "T" ).build() );
87+
CommandLine cmd = builder.build();
88+
89+
assertEquals( "foo", cmd.getArgs()[0] );
90+
assertEquals( "bar", cmd.getArgList().get( 1 ) );
91+
assertEquals( "T", cmd.getOptions()[0].getOpt() );
92+
}
7993
}

0 commit comments

Comments
 (0)