Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions src/main/java/org/apache/commons/cli/Options.java
Original file line number Diff line number Diff line change
Expand Up @@ -212,13 +212,17 @@ public Options addRequiredOption(final String opt, final String longOpt, final b
/**
* Gets the options with a long name starting with the name specified.
*
* @param opt The partial name of the option.
* @return The options matching the partial name specified, or an empty list if none matches.
* @param opt The partial name of the option, or {@code null}.
* @return The options matching the partial name specified, or an empty list if none matches or the name is null or empty.
* @since 1.3
*/
public List<String> getMatchingOptions(final String opt) {
final String clean = Util.stripLeadingHyphens(opt);
final List<String> matchingOpts = new ArrayList<>();
// a null or empty name is not a partial name; empty would match every long option
if (Util.isEmpty(clean)) {
return matchingOpts;
}
// for a perfect match return the single option only
if (longOpts.containsKey(clean)) {
return Collections.singletonList(clean);
Expand Down
14 changes: 14 additions & 0 deletions src/test/java/org/apache/commons/cli/OptionsTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,20 @@ void testGetMatchingOpts() {
assertToStrings(options.getOption("verbose"));
}

@Test
void testGetMatchingOptsEmptyName() throws Exception {
final Options options = new Options();
options.addOption(Option.builder("c").longOpt("config-file").hasArg().get());
assertTrue(options.getMatchingOptions(null).isEmpty());
assertTrue(options.getMatchingOptions("").isEmpty());
assertTrue(options.getMatchingOptions("-").isEmpty());
assertTrue(options.getMatchingOptions("--").isEmpty());
// "--=value" names no option, so it must not bind a value to config-file
for (final CommandLineParser parser : new CommandLineParser[] { new DefaultParser(), new PosixParser() }) {
assertThrows(UnrecognizedOptionException.class, () -> parser.parse(options, new String[] { "--=/etc/shadow" }));
}
}

@Test
void testGetOptionsGroups() {
final Options options = new Options();
Expand Down
Loading