Skip to content

Commit 834d696

Browse files
committed
CommandLine.addOption(Option) should not allow a null Option
1 parent 0ef219a commit 834d696

3 files changed

Lines changed: 18 additions & 1 deletion

File tree

src/changes/changes.xml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,9 @@
5252
<action dev="ggregory" type="fix" due-to="Dilraj Singh, Gary Gregory" issue="CLI-283">
5353
Fix NPE in CommandLine.resolveOption(String).
5454
</action>
55+
<action dev="ggregory" type="fix" due-to="Dilraj Singh, Gary Gregory" issue="CLI-283">
56+
CommandLine.addOption(Option) should not allow a null Option.
57+
</action>
5558
<!-- ADD -->
5659
<action type="update" dev="ggregory" due-to="Dependabot, Gary Gregory">
5760
Add github/codeql-action.

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

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,9 @@ protected void addArg(final String arg) {
108108
* @param opt the processed option.
109109
*/
110110
protected void addOption(final Option opt) {
111-
options.add(opt);
111+
if (opt != null) {
112+
options.add(opt);
113+
}
112114
}
113115

114116
/**

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

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,18 @@ public void testBuilder() {
4040
assertEquals("T", cmd.getOptions()[0].getOpt());
4141
}
4242

43+
@Test
44+
public void testBuilderNulls() {
45+
final CommandLine.Builder builder = new CommandLine.Builder();
46+
builder.addArg("foo").addArg("bar");
47+
builder.addOption(null);
48+
final CommandLine cmd = builder.build();
49+
50+
assertEquals("foo", cmd.getArgs()[0]);
51+
assertEquals("bar", cmd.getArgList().get(1));
52+
assertEquals(0, cmd.getOptions().length);
53+
}
54+
4355
@Test
4456
public void testGetOptionProperties() throws Exception {
4557
final String[] args = {"-Dparam1=value1", "-Dparam2=value2", "-Dparam3", "-Dparam4=value4", "-D", "--property", "foo=bar"};

0 commit comments

Comments
 (0)