Skip to content

Commit 0ece5e4

Browse files
committed
Option.Builder.option("") should throw IllegalArgumentException instead
of ArrayIndexOutOfBoundsException
1 parent 8cb2272 commit 0ece5e4

2 files changed

Lines changed: 17 additions & 7 deletions

File tree

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

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ private static boolean search(final char[] chars, final char c) {
9191
* is valid are:
9292
*
9393
* <ul>
94-
* <li>a single character {@code opt} that is either ' '(special case), '?', '@' or a letter</li>
94+
* <li>a single character {@code opt} that is either Chars.SP(special case), '?', '@' or a letter</li>
9595
* <li>a multi character {@code opt} that only contains valid characters</li>
9696
* </ul>
9797
* </p><p>
@@ -118,17 +118,20 @@ static String validate(final String option) throws IllegalArgumentException {
118118
if (option == null) {
119119
return null;
120120
}
121-
121+
if (option.isEmpty()) {
122+
throw new IllegalArgumentException("Empty option name.");
123+
}
122124
final char[] chars = option.toCharArray();
123-
124-
if (!isValidOpt(chars[0])) {
125-
throw new IllegalArgumentException("Illegal option name '" + chars[0] + "'");
125+
final char ch0 = chars[0];
126+
if (!isValidOpt(ch0)) {
127+
throw new IllegalArgumentException(String.format("Illegal option name '%s'.", ch0));
126128
}
127129
// handle the multi-character opt
128130
if (option.length() > 1) {
129131
for (int i = 1; i < chars.length; i++) {
130-
if (!isValidChar(chars[i])) {
131-
throw new IllegalArgumentException("The option '" + option + "' contains an illegal " + "character : '" + chars[i] + "'");
132+
final char ch = chars[i];
133+
if (!isValidChar(ch)) {
134+
throw new IllegalArgumentException(String.format("The option '%s' contains an illegal " + "character : '%s'.", option, ch));
132135
}
133136
}
134137
}

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,13 @@ public void testBuilderInsufficientParams2() {
121121
assertThrows(IllegalArgumentException.class, () -> Option.builder(null).desc("desc").build());
122122
}
123123

124+
@Test
125+
public void testBuilderInvalidOptionName0() {
126+
assertNull(Option.builder().option(null));
127+
assertThrows(IllegalArgumentException.class, () -> Option.builder().option(""));
128+
assertThrows(IllegalArgumentException.class, () -> Option.builder().option(" "));
129+
}
130+
124131
@Test
125132
public void testBuilderInvalidOptionName1() {
126133
assertThrows(IllegalArgumentException.class, () -> Option.builder().option("invalid?"));

0 commit comments

Comments
 (0)