diff --git a/src/main/java/org/apache/commons/cli/Options.java b/src/main/java/org/apache/commons/cli/Options.java index 40d8b1103..dcb6b52b4 100644 --- a/src/main/java/org/apache/commons/cli/Options.java +++ b/src/main/java/org/apache/commons/cli/Options.java @@ -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, may be {@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 getMatchingOptions(final String opt) { final String clean = Util.stripLeadingHyphens(opt); final List 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); diff --git a/src/test/java/org/apache/commons/cli/OptionsTest.java b/src/test/java/org/apache/commons/cli/OptionsTest.java index f0ac95258..d6b2f4667 100644 --- a/src/test/java/org/apache/commons/cli/OptionsTest.java +++ b/src/test/java/org/apache/commons/cli/OptionsTest.java @@ -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();