You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@commons.apache.org by gg...@apache.org on 2021/10/02 20:12:18 UTC
[commons-cli] 02/03: Sort members.
This is an automated email from the ASF dual-hosted git repository.
ggregory pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-cli.git
commit 4e8b3a2584ddac7411e20cdaca75b160787d7fa9
Author: Gary Gregory <ga...@gmail.com>
AuthorDate: Sat Oct 2 16:07:45 2021 -0400
Sort members.
---
src/conf/checkstyle.xml | 1 -
.../commons/cli/AlreadySelectedException.java | 28 +-
.../commons/cli/AmbiguousOptionException.java | 46 +-
.../java/org/apache/commons/cli/CommandLine.java | 474 ++++-----
.../java/org/apache/commons/cli/DefaultParser.java | 618 +++++------
.../java/org/apache/commons/cli/HelpFormatter.java | 668 ++++++------
.../commons/cli/MissingArgumentException.java | 16 +-
.../apache/commons/cli/MissingOptionException.java | 58 +-
src/main/java/org/apache/commons/cli/Option.java | 1034 +++++++++----------
.../java/org/apache/commons/cli/OptionBuilder.java | 276 ++---
.../java/org/apache/commons/cli/OptionGroup.java | 46 +-
.../org/apache/commons/cli/OptionValidator.java | 40 +-
src/main/java/org/apache/commons/cli/Options.java | 208 ++--
src/main/java/org/apache/commons/cli/Parser.java | 172 +--
.../java/org/apache/commons/cli/PosixParser.java | 96 +-
.../java/org/apache/commons/cli/TypeHandler.java | 198 ++--
src/main/java/org/apache/commons/cli/Util.java | 32 +-
.../org/apache/commons/cli/ApplicationTest.java | 54 +-
.../apache/commons/cli/ArgumentIsOptionTest.java | 20 +-
.../org/apache/commons/cli/BasicParserTest.java | 52 +-
.../org/apache/commons/cli/CommandLineTest.java | 24 +-
.../java/org/apache/commons/cli/GnuParserTest.java | 46 +-
.../org/apache/commons/cli/HelpFormatterTest.java | 732 ++++++-------
.../org/apache/commons/cli/OptionBuilderTest.java | 192 ++--
.../org/apache/commons/cli/OptionGroupTest.java | 142 +--
.../java/org/apache/commons/cli/OptionTest.java | 176 ++--
.../java/org/apache/commons/cli/OptionsTest.java | 98 +-
.../org/apache/commons/cli/ParserTestCase.java | 1090 ++++++++++----------
.../commons/cli/PatternOptionBuilderTest.java | 154 +--
.../org/apache/commons/cli/PosixParserTest.java | 22 +-
.../org/apache/commons/cli/TypeHandlerTest.java | 100 +-
src/test/java/org/apache/commons/cli/UtilTest.java | 16 +-
.../java/org/apache/commons/cli/ValueTest.java | 204 ++--
.../java/org/apache/commons/cli/ValuesTest.java | 74 +-
.../org/apache/commons/cli/bug/BugCLI252Test.java | 16 +-
.../org/apache/commons/cli/bug/BugCLI265Test.java | 22 +-
.../org/apache/commons/cli/bug/BugCLI266Test.java | 100 +-
.../org/apache/commons/cli/bug/BugCLI71Test.java | 24 +-
.../java/org/apache/commons/cli/bug/BugsTest.java | 50 +-
39 files changed, 3709 insertions(+), 3710 deletions(-)
diff --git a/src/conf/checkstyle.xml b/src/conf/checkstyle.xml
index e2b1b44..eb54177 100644
--- a/src/conf/checkstyle.xml
+++ b/src/conf/checkstyle.xml
@@ -120,7 +120,6 @@ limitations under the License.
<module name="StringLiteralEquality"/>
<module name="SuperClone"/>
<module name="SuperFinalize"/>
- <module name="DeclarationOrder"/>
<module name="ExplicitInitialization"/>
<module name="DefaultComesLast"/>
<module name="FallThrough"/>
diff --git a/src/main/java/org/apache/commons/cli/AlreadySelectedException.java b/src/main/java/org/apache/commons/cli/AlreadySelectedException.java
index 3b1cb01..5a42fb4 100644
--- a/src/main/java/org/apache/commons/cli/AlreadySelectedException.java
+++ b/src/main/java/org/apache/commons/cli/AlreadySelectedException.java
@@ -33,15 +33,6 @@ public class AlreadySelectedException extends ParseException {
private Option option;
/**
- * Construct a new <code>AlreadySelectedException</code> with the specified detail message.
- *
- * @param message the detail message
- */
- public AlreadySelectedException(final String message) {
- super(message);
- }
-
- /**
* Construct a new <code>AlreadySelectedException</code> for the specified option group.
*
* @param group the option group already selected
@@ -55,13 +46,12 @@ public class AlreadySelectedException extends ParseException {
}
/**
- * Returns the option group where another option has been selected.
+ * Construct a new <code>AlreadySelectedException</code> with the specified detail message.
*
- * @return the related option group
- * @since 1.2
+ * @param message the detail message
*/
- public OptionGroup getOptionGroup() {
- return group;
+ public AlreadySelectedException(final String message) {
+ super(message);
}
/**
@@ -73,4 +63,14 @@ public class AlreadySelectedException extends ParseException {
public Option getOption() {
return option;
}
+
+ /**
+ * Returns the option group where another option has been selected.
+ *
+ * @return the related option group
+ * @since 1.2
+ */
+ public OptionGroup getOptionGroup() {
+ return group;
+ }
}
diff --git a/src/main/java/org/apache/commons/cli/AmbiguousOptionException.java b/src/main/java/org/apache/commons/cli/AmbiguousOptionException.java
index 9a523ed..cb679a9 100644
--- a/src/main/java/org/apache/commons/cli/AmbiguousOptionException.java
+++ b/src/main/java/org/apache/commons/cli/AmbiguousOptionException.java
@@ -31,29 +31,6 @@ public class AmbiguousOptionException extends UnrecognizedOptionException {
*/
private static final long serialVersionUID = 5829816121277947229L;
- /** The list of options matching the partial name specified */
- private final Collection<String> matchingOptions;
-
- /**
- * Constructs a new AmbiguousOptionException.
- *
- * @param option the partial option name
- * @param matchingOptions the options matching the name
- */
- public AmbiguousOptionException(final String option, final Collection<String> matchingOptions) {
- super(createMessage(option, matchingOptions), option);
- this.matchingOptions = matchingOptions;
- }
-
- /**
- * Returns the options matching the partial name.
- *
- * @return a collection of options matching the name
- */
- public Collection<String> getMatchingOptions() {
- return matchingOptions;
- }
-
/**
* Build the exception message from the specified list of options.
*
@@ -79,4 +56,27 @@ public class AmbiguousOptionException extends UnrecognizedOptionException {
return buf.toString();
}
+
+ /** The list of options matching the partial name specified */
+ private final Collection<String> matchingOptions;
+
+ /**
+ * Constructs a new AmbiguousOptionException.
+ *
+ * @param option the partial option name
+ * @param matchingOptions the options matching the name
+ */
+ public AmbiguousOptionException(final String option, final Collection<String> matchingOptions) {
+ super(createMessage(option, matchingOptions), option);
+ this.matchingOptions = matchingOptions;
+ }
+
+ /**
+ * Returns the options matching the partial name.
+ *
+ * @return a collection of options matching the name
+ */
+ public Collection<String> getMatchingOptions() {
+ return matchingOptions;
+ }
}
diff --git a/src/main/java/org/apache/commons/cli/CommandLine.java b/src/main/java/org/apache/commons/cli/CommandLine.java
index f0ac8b8..28148b5 100644
--- a/src/main/java/org/apache/commons/cli/CommandLine.java
+++ b/src/main/java/org/apache/commons/cli/CommandLine.java
@@ -34,6 +34,46 @@ import java.util.Properties;
* Additionally, any left-over or unrecognized arguments, are available for further processing.
*/
public class CommandLine implements Serializable {
+ /**
+ * A nested builder class to create <code>CommandLine</code> instance using descriptive methods.
+ *
+ * @since 1.4
+ */
+ public static final class Builder {
+ /**
+ * CommandLine that is being build by this Builder.
+ */
+ private final CommandLine commandLine = new CommandLine();
+
+ /**
+ * Add left-over unrecognized option/argument.
+ *
+ * @param arg the unrecognized option/argument.
+ *
+ * @return this Builder instance for method chaining.
+ */
+ public Builder addArg(final String arg) {
+ commandLine.addArg(arg);
+ return this;
+ }
+
+ /**
+ * Add an option to the command line. The values of the option are stored.
+ *
+ * @param opt the processed option.
+ *
+ * @return this Builder instance for method chaining.
+ */
+ public Builder addOption(final Option opt) {
+ commandLine.addOption(opt);
+ return this;
+ }
+
+ public CommandLine build() {
+ return commandLine;
+ }
+ }
+
/** The serial version UID. */
private static final long serialVersionUID = 1L;
@@ -51,34 +91,55 @@ public class CommandLine implements Serializable {
}
/**
- * Tests to see if an option has been set.
+ * Add left-over unrecognized option/argument.
*
- * @param opt the option to check.
- * @return true if set, false if not.
- * @since 1.5
+ * @param arg the unrecognized option/argument.
*/
- public boolean hasOption(final Option opt) {
- return options.contains(opt);
+ protected void addArg(final String arg) {
+ args.add(arg);
}
/**
- * Tests to see if an option has been set.
+ * Add an option to the command line. The values of the option are stored.
*
- * @param opt Short name of the option.
- * @return true if set, false if not.
+ * @param opt the processed option.
*/
- public boolean hasOption(final String opt) {
- return hasOption(resolveOption(opt));
+ protected void addOption(final Option opt) {
+ options.add(opt);
}
/**
- * Tests to see if an option has been set.
+ * Retrieve any left-over non-recognized options and arguments
*
- * @param opt character name of the option.
- * @return true if set, false if not.
+ * @return remaining items passed in but not parsed as a <code>List</code>.
*/
- public boolean hasOption(final char opt) {
- return hasOption(String.valueOf(opt));
+ public List<String> getArgList() {
+ return args;
+ }
+
+ /**
+ * Retrieve any left-over non-recognized options and arguments
+ *
+ * @return remaining items passed in but not parsed as an array.
+ */
+ public String[] getArgs() {
+ final String[] answer = new String[args.size()];
+
+ args.toArray(answer);
+
+ return answer;
+ }
+
+ /**
+ * Return the <code>Object</code> type of this <code>Option</code>.
+ *
+ * @deprecated due to System.err message. Instead use getParsedOptionValue(char)
+ * @param opt the name of the option.
+ * @return the type of opt.
+ */
+ @Deprecated
+ public Object getOptionObject(final char opt) {
+ return getOptionObject(String.valueOf(opt));
}
/**
@@ -99,61 +160,97 @@ public class CommandLine implements Serializable {
}
/**
- * Return a version of this <code>Option</code> converted to a particular type.
+ * Retrieve the map of values associated to the option. This is convenient for options specifying Java properties like
+ * <code>-Dparam1=value1
+ * -Dparam2=value2</code>. The first argument of the option is the key, and the 2nd argument is the value. If the option
+ * has only one argument (<code>-Dfoo</code>) it is considered as a boolean flag and the value is <code>"true"</code>.
*
- * @param option the name of the option.
- * @return the value parsed into a particular object.
- * @throws ParseException if there are problems turning the option value into the desired type
- * @see PatternOptionBuilder
+ * @param option name of the option.
+ * @return The Properties mapped by the option, never <code>null</code> even if the option doesn't exists.
* @since 1.5
*/
- public Object getParsedOptionValue(final Option option) throws ParseException {
- if (option == null) {
- return null;
- }
- final String res = getOptionValue(option);
- if (res == null) {
- return null;
+ public Properties getOptionProperties(final Option option) {
+ final Properties props = new Properties();
+
+ for (final Option processedOption : options) {
+ if (processedOption.equals(option)) {
+ final List<String> values = processedOption.getValuesList();
+ if (values.size() >= 2) {
+ // use the first 2 arguments as the key/value pair
+ props.put(values.get(0), values.get(1));
+ } else if (values.size() == 1) {
+ // no explicit value, handle it as a boolean
+ props.put(values.get(0), "true");
+ }
+ }
}
- return TypeHandler.createValue(res, option.getType());
+
+ return props;
}
/**
- * Return a version of this <code>Option</code> converted to a particular type.
+ * Retrieve the map of values associated to the option. This is convenient for options specifying Java properties like
+ * <code>-Dparam1=value1
+ * -Dparam2=value2</code>. The first argument of the option is the key, and the 2nd argument is the value. If the option
+ * has only one argument (<code>-Dfoo</code>) it is considered as a boolean flag and the value is <code>"true"</code>.
*
- * @param opt the name of the option.
- * @return the value parsed into a particular object.
- * @throws ParseException if there are problems turning the option value into the desired type
- * @see PatternOptionBuilder
+ * @param opt name of the option.
+ * @return The Properties mapped by the option, never <code>null</code> even if the option doesn't exists.
* @since 1.2
*/
- public Object getParsedOptionValue(final String opt) throws ParseException {
- return getParsedOptionValue(resolveOption(opt));
+ public Properties getOptionProperties(final String opt) {
+ final Properties props = new Properties();
+
+ for (final Option option : options) {
+ if (opt.equals(option.getOpt()) || opt.equals(option.getLongOpt())) {
+ final List<String> values = option.getValuesList();
+ if (values.size() >= 2) {
+ // use the first 2 arguments as the key/value pair
+ props.put(values.get(0), values.get(1));
+ } else if (values.size() == 1) {
+ // no explicit value, handle it as a boolean
+ props.put(values.get(0), "true");
+ }
+ }
+ }
+
+ return props;
}
/**
- * Return a version of this <code>Option</code> converted to a particular type.
+ * Returns an array of the processed {@link Option}s.
*
- * @param opt the name of the option.
- * @return the value parsed into a particular object.
- * @throws ParseException if there are problems turning the option value into the desired type
- * @see PatternOptionBuilder
- * @since 1.5
+ * @return an array of the processed {@link Option}s.
*/
- public Object getParsedOptionValue(final char opt) throws ParseException {
- return getParsedOptionValue(String.valueOf(opt));
+ public Option[] getOptions() {
+ final Collection<Option> processed = options;
+
+ // reinitialize array
+ final Option[] optionsArray = new Option[processed.size()];
+
+ // return the array
+ return processed.toArray(optionsArray);
}
/**
- * Return the <code>Object</code> type of this <code>Option</code>.
+ * Retrieve the first argument, if any, of this option.
*
- * @deprecated due to System.err message. Instead use getParsedOptionValue(char)
- * @param opt the name of the option.
- * @return the type of opt.
+ * @param opt the character name of the option.
+ * @return Value of the argument if option is set, and has an argument, otherwise null.
*/
- @Deprecated
- public Object getOptionObject(final char opt) {
- return getOptionObject(String.valueOf(opt));
+ public String getOptionValue(final char opt) {
+ return getOptionValue(String.valueOf(opt));
+ }
+
+ /**
+ * Retrieve the argument, if any, of an option.
+ *
+ * @param opt character name of the option
+ * @param defaultValue is the default value to be returned if the option is not specified.
+ * @return Value of the argument if option is set, and has an argument, otherwise <code>defaultValue</code>.
+ */
+ public String getOptionValue(final char opt, final String defaultValue) {
+ return getOptionValue(String.valueOf(opt), defaultValue);
}
/**
@@ -172,6 +269,19 @@ public class CommandLine implements Serializable {
}
/**
+ * Retrieve the first argument, if any, of an option.
+ *
+ * @param option name of the option.
+ * @param defaultValue is the default value to be returned if the option is not specified.
+ * @return Value of the argument if option is set, and has an argument, otherwise <code>defaultValue</code>.
+ * @since 1.5
+ */
+ public String getOptionValue(final Option option, final String defaultValue) {
+ final String answer = getOptionValue(option);
+ return (answer != null) ? answer : defaultValue;
+ }
+
+ /**
* Retrieve the first argument, if any, of this option.
*
* @param opt the name of the option.
@@ -182,13 +292,24 @@ public class CommandLine implements Serializable {
}
/**
- * Retrieve the first argument, if any, of this option.
+ * Retrieve the first argument, if any, of an option.
*
- * @param opt the character name of the option.
- * @return Value of the argument if option is set, and has an argument, otherwise null.
+ * @param opt name of the option.
+ * @param defaultValue is the default value to be returned if the option is not specified.
+ * @return Value of the argument if option is set, and has an argument, otherwise <code>defaultValue</code>.
*/
- public String getOptionValue(final char opt) {
- return getOptionValue(String.valueOf(opt));
+ public String getOptionValue(final String opt, final String defaultValue) {
+ return getOptionValue(resolveOption(opt), defaultValue);
+ }
+
+ /**
+ * Retrieves the array of values, if any, of an option.
+ *
+ * @param opt character name of the option.
+ * @return Values of the argument if option is set, and has an argument, otherwise null.
+ */
+ public String[] getOptionValues(final char opt) {
+ return getOptionValues(String.valueOf(opt));
}
/**
@@ -221,149 +342,49 @@ public class CommandLine implements Serializable {
}
/**
- * Retrieves the option object given the long or short option as a String
- *
- * @param opt short or long name of the option.
- * @return Canonicalized option.
- */
- private Option resolveOption(String opt) {
- opt = Util.stripLeadingHyphens(opt);
- for (final Option option : options) {
- if (opt.equals(option.getOpt())) {
- return option;
- }
-
- if (opt.equals(option.getLongOpt())) {
- return option;
- }
-
- }
- return null;
- }
-
- /**
- * Retrieves the array of values, if any, of an option.
- *
- * @param opt character name of the option.
- * @return Values of the argument if option is set, and has an argument, otherwise null.
- */
- public String[] getOptionValues(final char opt) {
- return getOptionValues(String.valueOf(opt));
- }
-
- /**
- * Retrieve the first argument, if any, of an option.
+ * Return a version of this <code>Option</code> converted to a particular type.
*
- * @param option name of the option.
- * @param defaultValue is the default value to be returned if the option is not specified.
- * @return Value of the argument if option is set, and has an argument, otherwise <code>defaultValue</code>.
+ * @param opt the name of the option.
+ * @return the value parsed into a particular object.
+ * @throws ParseException if there are problems turning the option value into the desired type
+ * @see PatternOptionBuilder
* @since 1.5
*/
- public String getOptionValue(final Option option, final String defaultValue) {
- final String answer = getOptionValue(option);
- return (answer != null) ? answer : defaultValue;
- }
-
- /**
- * Retrieve the first argument, if any, of an option.
- *
- * @param opt name of the option.
- * @param defaultValue is the default value to be returned if the option is not specified.
- * @return Value of the argument if option is set, and has an argument, otherwise <code>defaultValue</code>.
- */
- public String getOptionValue(final String opt, final String defaultValue) {
- return getOptionValue(resolveOption(opt), defaultValue);
- }
-
- /**
- * Retrieve the argument, if any, of an option.
- *
- * @param opt character name of the option
- * @param defaultValue is the default value to be returned if the option is not specified.
- * @return Value of the argument if option is set, and has an argument, otherwise <code>defaultValue</code>.
- */
- public String getOptionValue(final char opt, final String defaultValue) {
- return getOptionValue(String.valueOf(opt), defaultValue);
+ public Object getParsedOptionValue(final char opt) throws ParseException {
+ return getParsedOptionValue(String.valueOf(opt));
}
/**
- * Retrieve the map of values associated to the option. This is convenient for options specifying Java properties like
- * <code>-Dparam1=value1
- * -Dparam2=value2</code>. The first argument of the option is the key, and the 2nd argument is the value. If the option
- * has only one argument (<code>-Dfoo</code>) it is considered as a boolean flag and the value is <code>"true"</code>.
+ * Return a version of this <code>Option</code> converted to a particular type.
*
- * @param option name of the option.
- * @return The Properties mapped by the option, never <code>null</code> even if the option doesn't exists.
+ * @param option the name of the option.
+ * @return the value parsed into a particular object.
+ * @throws ParseException if there are problems turning the option value into the desired type
+ * @see PatternOptionBuilder
* @since 1.5
*/
- public Properties getOptionProperties(final Option option) {
- final Properties props = new Properties();
-
- for (final Option processedOption : options) {
- if (processedOption.equals(option)) {
- final List<String> values = processedOption.getValuesList();
- if (values.size() >= 2) {
- // use the first 2 arguments as the key/value pair
- props.put(values.get(0), values.get(1));
- } else if (values.size() == 1) {
- // no explicit value, handle it as a boolean
- props.put(values.get(0), "true");
- }
- }
+ public Object getParsedOptionValue(final Option option) throws ParseException {
+ if (option == null) {
+ return null;
}
-
- return props;
- }
-
- /**
- * Retrieve the map of values associated to the option. This is convenient for options specifying Java properties like
- * <code>-Dparam1=value1
- * -Dparam2=value2</code>. The first argument of the option is the key, and the 2nd argument is the value. If the option
- * has only one argument (<code>-Dfoo</code>) it is considered as a boolean flag and the value is <code>"true"</code>.
- *
- * @param opt name of the option.
- * @return The Properties mapped by the option, never <code>null</code> even if the option doesn't exists.
- * @since 1.2
- */
- public Properties getOptionProperties(final String opt) {
- final Properties props = new Properties();
-
- for (final Option option : options) {
- if (opt.equals(option.getOpt()) || opt.equals(option.getLongOpt())) {
- final List<String> values = option.getValuesList();
- if (values.size() >= 2) {
- // use the first 2 arguments as the key/value pair
- props.put(values.get(0), values.get(1));
- } else if (values.size() == 1) {
- // no explicit value, handle it as a boolean
- props.put(values.get(0), "true");
- }
- }
+ final String res = getOptionValue(option);
+ if (res == null) {
+ return null;
}
-
- return props;
- }
-
- /**
- * Retrieve any left-over non-recognized options and arguments
- *
- * @return remaining items passed in but not parsed as an array.
- */
- public String[] getArgs() {
- final String[] answer = new String[args.size()];
-
- args.toArray(answer);
-
- return answer;
+ return TypeHandler.createValue(res, option.getType());
}
/**
- * Retrieve any left-over non-recognized options and arguments
+ * Return a version of this <code>Option</code> converted to a particular type.
*
- * @return remaining items passed in but not parsed as a <code>List</code>.
+ * @param opt the name of the option.
+ * @return the value parsed into a particular object.
+ * @throws ParseException if there are problems turning the option value into the desired type
+ * @see PatternOptionBuilder
+ * @since 1.2
*/
- public List<String> getArgList() {
- return args;
+ public Object getParsedOptionValue(final String opt) throws ParseException {
+ return getParsedOptionValue(resolveOption(opt));
}
/**
@@ -385,84 +406,63 @@ public class CommandLine implements Serializable {
*/
/**
- * Add left-over unrecognized option/argument.
+ * Tests to see if an option has been set.
*
- * @param arg the unrecognized option/argument.
+ * @param opt character name of the option.
+ * @return true if set, false if not.
*/
- protected void addArg(final String arg) {
- args.add(arg);
+ public boolean hasOption(final char opt) {
+ return hasOption(String.valueOf(opt));
}
/**
- * Add an option to the command line. The values of the option are stored.
+ * Tests to see if an option has been set.
*
- * @param opt the processed option.
+ * @param opt the option to check.
+ * @return true if set, false if not.
+ * @since 1.5
*/
- protected void addOption(final Option opt) {
- options.add(opt);
+ public boolean hasOption(final Option opt) {
+ return options.contains(opt);
}
/**
- * Returns an iterator over the Option members of CommandLine.
+ * Tests to see if an option has been set.
*
- * @return an <code>Iterator</code> over the processed {@link Option} members of this {@link CommandLine}.
+ * @param opt Short name of the option.
+ * @return true if set, false if not.
*/
- public Iterator<Option> iterator() {
- return options.iterator();
+ public boolean hasOption(final String opt) {
+ return hasOption(resolveOption(opt));
}
/**
- * Returns an array of the processed {@link Option}s.
+ * Returns an iterator over the Option members of CommandLine.
*
- * @return an array of the processed {@link Option}s.
+ * @return an <code>Iterator</code> over the processed {@link Option} members of this {@link CommandLine}.
*/
- public Option[] getOptions() {
- final Collection<Option> processed = options;
-
- // reinitialize array
- final Option[] optionsArray = new Option[processed.size()];
-
- // return the array
- return processed.toArray(optionsArray);
+ public Iterator<Option> iterator() {
+ return options.iterator();
}
/**
- * A nested builder class to create <code>CommandLine</code> instance using descriptive methods.
+ * Retrieves the option object given the long or short option as a String
*
- * @since 1.4
+ * @param opt short or long name of the option.
+ * @return Canonicalized option.
*/
- public static final class Builder {
- /**
- * CommandLine that is being build by this Builder.
- */
- private final CommandLine commandLine = new CommandLine();
-
- /**
- * Add an option to the command line. The values of the option are stored.
- *
- * @param opt the processed option.
- *
- * @return this Builder instance for method chaining.
- */
- public Builder addOption(final Option opt) {
- commandLine.addOption(opt);
- return this;
- }
+ private Option resolveOption(String opt) {
+ opt = Util.stripLeadingHyphens(opt);
+ for (final Option option : options) {
+ if (opt.equals(option.getOpt())) {
+ return option;
+ }
- /**
- * Add left-over unrecognized option/argument.
- *
- * @param arg the unrecognized option/argument.
- *
- * @return this Builder instance for method chaining.
- */
- public Builder addArg(final String arg) {
- commandLine.addArg(arg);
- return this;
- }
+ if (opt.equals(option.getLongOpt())) {
+ return option;
+ }
- public CommandLine build() {
- return commandLine;
}
+ return null;
}
}
diff --git a/src/main/java/org/apache/commons/cli/DefaultParser.java b/src/main/java/org/apache/commons/cli/DefaultParser.java
index 0ab58ae..9a1e5bf 100644
--- a/src/main/java/org/apache/commons/cli/DefaultParser.java
+++ b/src/main/java/org/apache/commons/cli/DefaultParser.java
@@ -103,113 +103,12 @@ public class DefaultParser implements CommandLineParser {
this.allowPartialMatching = allowPartialMatching;
}
- @Override
- public CommandLine parse(final Options options, final String[] arguments) throws ParseException {
- return parse(options, arguments, null);
- }
-
- /**
- * Parse the arguments according to the specified options and properties.
- *
- * @param options the specified Options
- * @param arguments the command line arguments
- * @param properties command line option name-value pairs
- * @return the list of atomic option and value tokens
- *
- * @throws ParseException if there are any problems encountered while parsing the command line tokens.
- */
- public CommandLine parse(final Options options, final String[] arguments, final Properties properties) throws ParseException {
- return parse(options, arguments, properties, false);
- }
-
- @Override
- public CommandLine parse(final Options options, final String[] arguments, final boolean stopAtNonOption) throws ParseException {
- return parse(options, arguments, null, stopAtNonOption);
- }
-
/**
- * Parse the arguments according to the specified options and properties.
- *
- * @param options the specified Options
- * @param arguments the command line arguments
- * @param properties command line option name-value pairs
- * @param stopAtNonOption if <code>true</code> an unrecognized argument stops the parsing and the remaining arguments
- * are added to the {@link CommandLine}s args list. If <code>false</code> an unrecognized argument triggers a
- * ParseException.
- *
- * @return the list of atomic option and value tokens
- * @throws ParseException if there are any problems encountered while parsing the command line tokens.
- */
- public CommandLine parse(final Options options, final String[] arguments, final Properties properties, final boolean stopAtNonOption)
- throws ParseException {
- this.options = options;
- this.stopAtNonOption = stopAtNonOption;
- skipParsing = false;
- currentOption = null;
- expectedOpts = new ArrayList(options.getRequiredOptions());
-
- // clear the data from the groups
- for (final OptionGroup group : options.getOptionGroups()) {
- group.setSelected(null);
- }
-
- cmd = new CommandLine();
-
- if (arguments != null) {
- for (final String argument : arguments) {
- handleToken(argument);
- }
- }
-
- // check the arguments of the last option
- checkRequiredArgs();
-
- // add the default options
- handleProperties(properties);
-
- checkRequiredOptions();
-
- return cmd;
- }
-
- /**
- * Sets the values of Options using the values in <code>properties</code>.
- *
- * @param properties The value properties to be processed.
+ * Throw a {@link MissingArgumentException} if the current option didn't receive the number of arguments expected.
*/
- private void handleProperties(final Properties properties) throws ParseException {
- if (properties == null) {
- return;
- }
-
- for (final Enumeration<?> e = properties.propertyNames(); e.hasMoreElements();) {
- final String option = e.nextElement().toString();
-
- final Option opt = options.getOption(option);
- if (opt == null) {
- throw new UnrecognizedOptionException("Default option wasn't defined", option);
- }
-
- // if the option is part of a group, check if another option of the group has been selected
- final OptionGroup group = options.getOptionGroup(opt);
- final boolean selected = group != null && group.getSelected() != null;
-
- if (!cmd.hasOption(option) && !selected) {
- // get the value from the properties
- final String value = properties.getProperty(option);
-
- if (opt.hasArg()) {
- if (opt.getValues() == null || opt.getValues().length == 0) {
- opt.addValueForProcessing(value);
- }
- } else if (!("yes".equalsIgnoreCase(value) || "true".equalsIgnoreCase(value) || "1".equalsIgnoreCase(value))) {
- // if the value is not yes, true or 1 then don't add the option to the CommandLine
- continue;
- }
-
- handleOption(opt);
- currentOption = null;
- }
+ private void checkRequiredArgs() throws ParseException {
+ if (currentOption != null && currentOption.requiresArg()) {
+ throw new MissingArgumentException(currentOption);
}
}
@@ -226,150 +125,128 @@ public class DefaultParser implements CommandLineParser {
}
/**
- * Throw a {@link MissingArgumentException} if the current option didn't receive the number of arguments expected.
- */
- private void checkRequiredArgs() throws ParseException {
- if (currentOption != null && currentOption.requiresArg()) {
- throw new MissingArgumentException(currentOption);
- }
- }
-
- /**
- * Handle any command line token.
- *
- * @param token the command line token to handle
- * @throws ParseException
- */
- private void handleToken(final String token) throws ParseException {
- currentToken = token;
-
- if (skipParsing) {
- cmd.addArg(token);
- } else if ("--".equals(token)) {
- skipParsing = true;
- } else if (currentOption != null && currentOption.acceptsArg() && isArgument(token)) {
- currentOption.addValueForProcessing(Util.stripLeadingAndTrailingQuotes(token));
- } else if (token.startsWith("--")) {
- handleLongOption(token);
- } else if (token.startsWith("-") && !"-".equals(token)) {
- handleShortAndLongOption(token);
- } else {
- handleUnknownToken(token);
- }
-
- if (currentOption != null && !currentOption.acceptsArg()) {
- currentOption = null;
- }
- }
-
- /**
- * Returns true is the token is a valid argument.
+ * Search for a prefix that is the long name of an option (-Xmx512m)
*
* @param token
*/
- private boolean isArgument(final String token) {
- return !isOption(token) || isNegativeNumber(token);
- }
+ private String getLongPrefix(final String token) {
+ final String t = Util.stripLeadingHyphens(token);
- /**
- * Check if the token is a negative number.
- *
- * @param token
- */
- private boolean isNegativeNumber(final String token) {
- try {
- Double.parseDouble(token);
- return true;
- } catch (final NumberFormatException e) {
- return false;
+ int i;
+ String opt = null;
+ for (i = t.length() - 2; i > 1; i--) {
+ final String prefix = t.substring(0, i);
+ if (options.hasLongOption(prefix)) {
+ opt = prefix;
+ break;
+ }
}
- }
- /**
- * Tells if the token looks like an option.
- *
- * @param token
- */
- private boolean isOption(final String token) {
- return isLongOption(token) || isShortOption(token);
+ return opt;
}
/**
- * Tells if the token looks like a short option.
+ * Returns a list of matching option strings for the given token, depending on the selected partial matching policy.
*
- * @param token
+ * @param token the token (may contain leading dashes)
+ * @return the list of matching option strings or an empty list if no matching option could be found
*/
- private boolean isShortOption(final String token) {
- // short options (-S, -SV, -S=V, -SV1=V2, -S1S2)
- if (token == null || !token.startsWith("-") || token.length() == 1) {
- return false;
+ private List<String> getMatchingLongOptions(final String token) {
+ if (allowPartialMatching) {
+ return options.getMatchingOptions(token);
}
-
- // remove leading "-" and "=value"
- final int pos = token.indexOf("=");
- final String optName = pos == -1 ? token.substring(1) : token.substring(1, pos);
- if (options.hasShortOption(optName)) {
- return true;
+ final List<String> matches = new ArrayList<>(1);
+ if (options.hasLongOption(token)) {
+ final Option option = options.getOption(token);
+ matches.add(option.getLongOpt());
}
- // check for several concatenated short options
- return !optName.isEmpty() && options.hasShortOption(String.valueOf(optName.charAt(0)));
+
+ return matches;
}
/**
- * Tells if the token looks like a long option.
+ * Breaks <code>token</code> into its constituent parts using the following algorithm.
*
- * @param token
+ * <ul>
+ * <li>ignore the first character ("<b>-</b>")</li>
+ * <li>for each remaining character check if an {@link Option} exists with that id.</li>
+ * <li>if an {@link Option} does exist then add that character prepended with "<b>-</b>" to the list of processed
+ * tokens.</li>
+ * <li>if the {@link Option} can have an argument value and there are remaining characters in the token then add the
+ * remaining characters as a token to the list of processed tokens.</li>
+ * <li>if an {@link Option} does <b>NOT</b> exist <b>AND</b> <code>stopAtNonOption</code> <b>IS</b> set then add the
+ * special token "<b>--</b>" followed by the remaining characters and also the remaining tokens directly to the
+ * processed tokens list.</li>
+ * <li>if an {@link Option} does <b>NOT</b> exist <b>AND</b> <code>stopAtNonOption</code> <b>IS NOT</b> set then add
+ * that character prepended with "<b>-</b>".</li>
+ * </ul>
+ *
+ * @param token The current token to be <b>burst</b> at the first non-Option encountered.
+ * @throws ParseException if there are any problems encountered while parsing the command line token.
*/
- private boolean isLongOption(final String token) {
- if (token == null || !token.startsWith("-") || token.length() == 1) {
- return false;
- }
+ protected void handleConcatenatedOptions(final String token) throws ParseException {
+ for (int i = 1; i < token.length(); i++) {
+ final String ch = String.valueOf(token.charAt(i));
- final int pos = token.indexOf("=");
- final String t = pos == -1 ? token : token.substring(0, pos);
+ if (!options.hasOption(ch)) {
+ handleUnknownToken(stopAtNonOption && i > 1 ? token.substring(i) : token);
+ break;
+ }
+ handleOption(options.getOption(ch));
- if (!getMatchingLongOptions(t).isEmpty()) {
- // long or partial long options (--L, -L, --L=V, -L=V, --l, --l=V)
- return true;
- }
- if (getLongPrefix(token) != null && !token.startsWith("--")) {
- // -LV
- return true;
+ if (currentOption != null && token.length() != i + 1) {
+ // add the trail as an argument of the option
+ currentOption.addValueForProcessing(token.substring(i + 1));
+ break;
+ }
}
-
- return false;
}
/**
- * Handles an unknown token. If the token starts with a dash an UnrecognizedOptionException is thrown. Otherwise the
- * token is added to the arguments of the command line. If the stopAtNonOption flag is set, this stops the parsing and
- * the remaining tokens are added as-is in the arguments of the command line.
+ * Handles the following tokens:
+ *
+ * --L --L=V --L V --l
*
* @param token the command line token to handle
*/
- private void handleUnknownToken(final String token) throws ParseException {
- if (token.startsWith("-") && token.length() > 1 && !stopAtNonOption) {
- throw new UnrecognizedOptionException("Unrecognized option: " + token, token);
- }
-
- cmd.addArg(token);
- if (stopAtNonOption) {
- skipParsing = true;
+ private void handleLongOption(final String token) throws ParseException {
+ if (token.indexOf('=') == -1) {
+ handleLongOptionWithoutEqual(token);
+ } else {
+ handleLongOptionWithEqual(token);
}
}
/**
* Handles the following tokens:
*
- * --L --L=V --L V --l
+ * --L=V -L=V --l=V -l=V
*
* @param token the command line token to handle
*/
- private void handleLongOption(final String token) throws ParseException {
- if (token.indexOf('=') == -1) {
- handleLongOptionWithoutEqual(token);
+ private void handleLongOptionWithEqual(final String token) throws ParseException {
+ final int pos = token.indexOf('=');
+
+ final String value = token.substring(pos + 1);
+
+ final String opt = token.substring(0, pos);
+
+ final List<String> matchingOpts = getMatchingLongOptions(opt);
+ if (matchingOpts.isEmpty()) {
+ handleUnknownToken(currentToken);
+ } else if (matchingOpts.size() > 1 && !options.hasLongOption(opt)) {
+ throw new AmbiguousOptionException(opt, matchingOpts);
} else {
- handleLongOptionWithEqual(token);
+ final String key = options.hasLongOption(opt) ? opt : matchingOpts.get(0);
+ final Option option = options.getOption(key);
+
+ if (option.acceptsArg()) {
+ handleOption(option);
+ currentOption.addValueForProcessing(value);
+ currentOption = null;
+ } else {
+ handleUnknownToken(currentToken);
+ }
}
}
@@ -392,35 +269,60 @@ public class DefaultParser implements CommandLineParser {
}
}
+ private void handleOption(Option option) throws ParseException {
+ // check the previous option before handling the next one
+ checkRequiredArgs();
+
+ option = (Option) option.clone();
+
+ updateRequiredOptions(option);
+
+ cmd.addOption(option);
+
+ if (option.hasArg()) {
+ currentOption = option;
+ } else {
+ currentOption = null;
+ }
+ }
+
/**
- * Handles the following tokens:
- *
- * --L=V -L=V --l=V -l=V
+ * Sets the values of Options using the values in <code>properties</code>.
*
- * @param token the command line token to handle
+ * @param properties The value properties to be processed.
*/
- private void handleLongOptionWithEqual(final String token) throws ParseException {
- final int pos = token.indexOf('=');
+ private void handleProperties(final Properties properties) throws ParseException {
+ if (properties == null) {
+ return;
+ }
- final String value = token.substring(pos + 1);
+ for (final Enumeration<?> e = properties.propertyNames(); e.hasMoreElements();) {
+ final String option = e.nextElement().toString();
- final String opt = token.substring(0, pos);
+ final Option opt = options.getOption(option);
+ if (opt == null) {
+ throw new UnrecognizedOptionException("Default option wasn't defined", option);
+ }
- final List<String> matchingOpts = getMatchingLongOptions(opt);
- if (matchingOpts.isEmpty()) {
- handleUnknownToken(currentToken);
- } else if (matchingOpts.size() > 1 && !options.hasLongOption(opt)) {
- throw new AmbiguousOptionException(opt, matchingOpts);
- } else {
- final String key = options.hasLongOption(opt) ? opt : matchingOpts.get(0);
- final Option option = options.getOption(key);
+ // if the option is part of a group, check if another option of the group has been selected
+ final OptionGroup group = options.getOptionGroup(opt);
+ final boolean selected = group != null && group.getSelected() != null;
+
+ if (!cmd.hasOption(option) && !selected) {
+ // get the value from the properties
+ final String value = properties.getProperty(option);
+
+ if (opt.hasArg()) {
+ if (opt.getValues() == null || opt.getValues().length == 0) {
+ opt.addValueForProcessing(value);
+ }
+ } else if (!("yes".equalsIgnoreCase(value) || "true".equalsIgnoreCase(value) || "1".equalsIgnoreCase(value))) {
+ // if the value is not yes, true or 1 then don't add the option to the CommandLine
+ continue;
+ }
- if (option.acceptsArg()) {
- handleOption(option);
- currentOption.addValueForProcessing(value);
+ handleOption(opt);
currentOption = null;
- } else {
- handleUnknownToken(currentToken);
}
}
}
@@ -500,24 +402,58 @@ public class DefaultParser implements CommandLineParser {
}
/**
- * Search for a prefix that is the long name of an option (-Xmx512m)
+ * Handle any command line token.
*
- * @param token
+ * @param token the command line token to handle
+ * @throws ParseException
*/
- private String getLongPrefix(final String token) {
- final String t = Util.stripLeadingHyphens(token);
+ private void handleToken(final String token) throws ParseException {
+ currentToken = token;
- int i;
- String opt = null;
- for (i = t.length() - 2; i > 1; i--) {
- final String prefix = t.substring(0, i);
- if (options.hasLongOption(prefix)) {
- opt = prefix;
- break;
- }
+ if (skipParsing) {
+ cmd.addArg(token);
+ } else if ("--".equals(token)) {
+ skipParsing = true;
+ } else if (currentOption != null && currentOption.acceptsArg() && isArgument(token)) {
+ currentOption.addValueForProcessing(Util.stripLeadingAndTrailingQuotes(token));
+ } else if (token.startsWith("--")) {
+ handleLongOption(token);
+ } else if (token.startsWith("-") && !"-".equals(token)) {
+ handleShortAndLongOption(token);
+ } else {
+ handleUnknownToken(token);
}
- return opt;
+ if (currentOption != null && !currentOption.acceptsArg()) {
+ currentOption = null;
+ }
+ }
+
+ /**
+ * Handles an unknown token. If the token starts with a dash an UnrecognizedOptionException is thrown. Otherwise the
+ * token is added to the arguments of the command line. If the stopAtNonOption flag is set, this stops the parsing and
+ * the remaining tokens are added as-is in the arguments of the command line.
+ *
+ * @param token the command line token to handle
+ */
+ private void handleUnknownToken(final String token) throws ParseException {
+ if (token.startsWith("-") && token.length() > 1 && !stopAtNonOption) {
+ throw new UnrecognizedOptionException("Unrecognized option: " + token, token);
+ }
+
+ cmd.addArg(token);
+ if (stopAtNonOption) {
+ skipParsing = true;
+ }
+ }
+
+ /**
+ * Returns true is the token is a valid argument.
+ *
+ * @param token
+ */
+ private boolean isArgument(final String token) {
+ return !isOption(token) || isNegativeNumber(token);
}
/**
@@ -530,99 +466,163 @@ public class DefaultParser implements CommandLineParser {
return option != null && (option.getArgs() >= 2 || option.getArgs() == Option.UNLIMITED_VALUES);
}
- private void handleOption(Option option) throws ParseException {
- // check the previous option before handling the next one
- checkRequiredArgs();
+ /**
+ * Tells if the token looks like a long option.
+ *
+ * @param token
+ */
+ private boolean isLongOption(final String token) {
+ if (token == null || !token.startsWith("-") || token.length() == 1) {
+ return false;
+ }
- option = (Option) option.clone();
+ final int pos = token.indexOf("=");
+ final String t = pos == -1 ? token : token.substring(0, pos);
- updateRequiredOptions(option);
+ if (!getMatchingLongOptions(t).isEmpty()) {
+ // long or partial long options (--L, -L, --L=V, -L=V, --l, --l=V)
+ return true;
+ }
+ if (getLongPrefix(token) != null && !token.startsWith("--")) {
+ // -LV
+ return true;
+ }
- cmd.addOption(option);
+ return false;
+ }
- if (option.hasArg()) {
- currentOption = option;
- } else {
- currentOption = null;
+ /**
+ * Check if the token is a negative number.
+ *
+ * @param token
+ */
+ private boolean isNegativeNumber(final String token) {
+ try {
+ Double.parseDouble(token);
+ return true;
+ } catch (final NumberFormatException e) {
+ return false;
}
}
/**
- * Removes the option or its group from the list of expected elements.
+ * Tells if the token looks like an option.
*
- * @param option
+ * @param token
*/
- private void updateRequiredOptions(final Option option) throws AlreadySelectedException {
- if (option.isRequired()) {
- expectedOpts.remove(option.getKey());
+ private boolean isOption(final String token) {
+ return isLongOption(token) || isShortOption(token);
+ }
+
+ /**
+ * Tells if the token looks like a short option.
+ *
+ * @param token
+ */
+ private boolean isShortOption(final String token) {
+ // short options (-S, -SV, -S=V, -SV1=V2, -S1S2)
+ if (token == null || !token.startsWith("-") || token.length() == 1) {
+ return false;
}
- // if the option is in an OptionGroup make that option the selected option of the group
- if (options.getOptionGroup(option) != null) {
- final OptionGroup group = options.getOptionGroup(option);
+ // remove leading "-" and "=value"
+ final int pos = token.indexOf("=");
+ final String optName = pos == -1 ? token.substring(1) : token.substring(1, pos);
+ if (options.hasShortOption(optName)) {
+ return true;
+ }
+ // check for several concatenated short options
+ return !optName.isEmpty() && options.hasShortOption(String.valueOf(optName.charAt(0)));
+ }
- if (group.isRequired()) {
- expectedOpts.remove(group);
- }
+ @Override
+ public CommandLine parse(final Options options, final String[] arguments) throws ParseException {
+ return parse(options, arguments, null);
+ }
- group.setSelected(option);
- }
+ @Override
+ public CommandLine parse(final Options options, final String[] arguments, final boolean stopAtNonOption) throws ParseException {
+ return parse(options, arguments, null, stopAtNonOption);
}
/**
- * Returns a list of matching option strings for the given token, depending on the selected partial matching policy.
+ * Parse the arguments according to the specified options and properties.
*
- * @param token the token (may contain leading dashes)
- * @return the list of matching option strings or an empty list if no matching option could be found
+ * @param options the specified Options
+ * @param arguments the command line arguments
+ * @param properties command line option name-value pairs
+ * @return the list of atomic option and value tokens
+ *
+ * @throws ParseException if there are any problems encountered while parsing the command line tokens.
*/
- private List<String> getMatchingLongOptions(final String token) {
- if (allowPartialMatching) {
- return options.getMatchingOptions(token);
+ public CommandLine parse(final Options options, final String[] arguments, final Properties properties) throws ParseException {
+ return parse(options, arguments, properties, false);
+ }
+
+ /**
+ * Parse the arguments according to the specified options and properties.
+ *
+ * @param options the specified Options
+ * @param arguments the command line arguments
+ * @param properties command line option name-value pairs
+ * @param stopAtNonOption if <code>true</code> an unrecognized argument stops the parsing and the remaining arguments
+ * are added to the {@link CommandLine}s args list. If <code>false</code> an unrecognized argument triggers a
+ * ParseException.
+ *
+ * @return the list of atomic option and value tokens
+ * @throws ParseException if there are any problems encountered while parsing the command line tokens.
+ */
+ public CommandLine parse(final Options options, final String[] arguments, final Properties properties, final boolean stopAtNonOption)
+ throws ParseException {
+ this.options = options;
+ this.stopAtNonOption = stopAtNonOption;
+ skipParsing = false;
+ currentOption = null;
+ expectedOpts = new ArrayList(options.getRequiredOptions());
+
+ // clear the data from the groups
+ for (final OptionGroup group : options.getOptionGroups()) {
+ group.setSelected(null);
}
- final List<String> matches = new ArrayList<>(1);
- if (options.hasLongOption(token)) {
- final Option option = options.getOption(token);
- matches.add(option.getLongOpt());
+
+ cmd = new CommandLine();
+
+ if (arguments != null) {
+ for (final String argument : arguments) {
+ handleToken(argument);
+ }
}
- return matches;
+ // check the arguments of the last option
+ checkRequiredArgs();
+
+ // add the default options
+ handleProperties(properties);
+
+ checkRequiredOptions();
+
+ return cmd;
}
/**
- * Breaks <code>token</code> into its constituent parts using the following algorithm.
- *
- * <ul>
- * <li>ignore the first character ("<b>-</b>")</li>
- * <li>for each remaining character check if an {@link Option} exists with that id.</li>
- * <li>if an {@link Option} does exist then add that character prepended with "<b>-</b>" to the list of processed
- * tokens.</li>
- * <li>if the {@link Option} can have an argument value and there are remaining characters in the token then add the
- * remaining characters as a token to the list of processed tokens.</li>
- * <li>if an {@link Option} does <b>NOT</b> exist <b>AND</b> <code>stopAtNonOption</code> <b>IS</b> set then add the
- * special token "<b>--</b>" followed by the remaining characters and also the remaining tokens directly to the
- * processed tokens list.</li>
- * <li>if an {@link Option} does <b>NOT</b> exist <b>AND</b> <code>stopAtNonOption</code> <b>IS NOT</b> set then add
- * that character prepended with "<b>-</b>".</li>
- * </ul>
+ * Removes the option or its group from the list of expected elements.
*
- * @param token The current token to be <b>burst</b> at the first non-Option encountered.
- * @throws ParseException if there are any problems encountered while parsing the command line token.
+ * @param option
*/
- protected void handleConcatenatedOptions(final String token) throws ParseException {
- for (int i = 1; i < token.length(); i++) {
- final String ch = String.valueOf(token.charAt(i));
+ private void updateRequiredOptions(final Option option) throws AlreadySelectedException {
+ if (option.isRequired()) {
+ expectedOpts.remove(option.getKey());
+ }
- if (!options.hasOption(ch)) {
- handleUnknownToken(stopAtNonOption && i > 1 ? token.substring(i) : token);
- break;
- }
- handleOption(options.getOption(ch));
+ // if the option is in an OptionGroup make that option the selected option of the group
+ if (options.getOptionGroup(option) != null) {
+ final OptionGroup group = options.getOptionGroup(option);
- if (currentOption != null && token.length() != i + 1) {
- // add the trail as an argument of the option
- currentOption.addValueForProcessing(token.substring(i + 1));
- break;
+ if (group.isRequired()) {
+ expectedOpts.remove(group);
}
+
+ group.setSelected(option);
}
}
}
diff --git a/src/main/java/org/apache/commons/cli/HelpFormatter.java b/src/main/java/org/apache/commons/cli/HelpFormatter.java
index d177860..4deffec 100644
--- a/src/main/java/org/apache/commons/cli/HelpFormatter.java
+++ b/src/main/java/org/apache/commons/cli/HelpFormatter.java
@@ -66,6 +66,28 @@ import java.util.List;
public class HelpFormatter {
// --------------------------------------------------------------- Constants
+ /**
+ * This class implements the <code>Comparator</code> interface for comparing Options.
+ */
+ private static class OptionComparator implements Comparator<Option>, Serializable {
+ /** The serial version UID. */
+ private static final long serialVersionUID = 5305467873966684014L;
+
+ /**
+ * Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument
+ * is less than, equal to, or greater than the second.
+ *
+ * @param opt1 The first Option to be compared.
+ * @param opt2 The second Option to be compared.
+ * @return a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than
+ * the second.
+ */
+ @Override
+ public int compare(final Option opt1, final Option opt2) {
+ return opt1.getKey().compareToIgnoreCase(opt2.getKey());
+ }
+ }
+
/** default number of characters per line */
public static final int DEFAULT_WIDTH = 74;
@@ -169,120 +191,151 @@ public class HelpFormatter {
private String longOptSeparator = DEFAULT_LONG_OPT_SEPARATOR;
/**
- * Sets the 'width'.
+ * Appends the usage clause for an Option to a StringBuffer.
*
- * @param width the new value of 'width'
+ * @param buff the StringBuffer to append to
+ * @param option the Option to append
+ * @param required whether the Option is required or not
*/
- public void setWidth(final int width) {
- this.defaultWidth = width;
- }
+ private void appendOption(final StringBuffer buff, final Option option, final boolean required) {
+ if (!required) {
+ buff.append("[");
+ }
- /**
- * Returns the 'width'.
- *
- * @return the 'width'
- */
- public int getWidth() {
- return defaultWidth;
- }
+ if (option.getOpt() != null) {
+ buff.append("-").append(option.getOpt());
+ } else {
+ buff.append("--").append(option.getLongOpt());
+ }
- /**
- * Sets the 'leftPadding'.
- *
- * @param padding the new value of 'leftPadding'
- */
- public void setLeftPadding(final int padding) {
- this.defaultLeftPad = padding;
- }
+ // if the Option has a value and a non blank argname
+ if (option.hasArg() && (option.getArgName() == null || !option.getArgName().isEmpty())) {
+ buff.append(option.getOpt() == null ? longOptSeparator : " ");
+ buff.append("<").append(option.getArgName() != null ? option.getArgName() : getArgName()).append(">");
+ }
- /**
- * Returns the 'leftPadding'.
- *
- * @return the 'leftPadding'
- */
- public int getLeftPadding() {
- return defaultLeftPad;
+ // if the Option is not a required option
+ if (!required) {
+ buff.append("]");
+ }
}
/**
- * Sets the 'descPadding'.
+ * Appends the usage clause for an OptionGroup to a StringBuffer. The clause is wrapped in square brackets if the group
+ * is required. The display of the options is handled by appendOption
*
- * @param padding the new value of 'descPadding'
+ * @param buff the StringBuffer to append to
+ * @param group the group to append
+ * @see #appendOption(StringBuffer,Option,boolean)
*/
- public void setDescPadding(final int padding) {
- this.defaultDescPad = padding;
- }
+ private void appendOptionGroup(final StringBuffer buff, final OptionGroup group) {
+ if (!group.isRequired()) {
+ buff.append("[");
+ }
- /**
- * Returns the 'descPadding'.
- *
- * @return the 'descPadding'
- */
- public int getDescPadding() {
- return defaultDescPad;
- }
+ final List<Option> optList = new ArrayList<>(group.getOptions());
+ if (getOptionComparator() != null) {
+ Collections.sort(optList, getOptionComparator());
+ }
+ // for each option in the OptionGroup
+ for (final Iterator<Option> it = optList.iterator(); it.hasNext();) {
+ // whether the option is required or not is handled at group level
+ appendOption(buff, it.next(), true);
- /**
- * Sets the 'syntaxPrefix'.
- *
- * @param prefix the new value of 'syntaxPrefix'
- */
- public void setSyntaxPrefix(final String prefix) {
- this.defaultSyntaxPrefix = prefix;
- }
+ if (it.hasNext()) {
+ buff.append(" | ");
+ }
+ }
- /**
- * Returns the 'syntaxPrefix'.
- *
- * @return the 'syntaxPrefix'
- */
- public String getSyntaxPrefix() {
- return defaultSyntaxPrefix;
+ if (!group.isRequired()) {
+ buff.append("]");
+ }
}
/**
- * Sets the 'newLine'.
+ * Return a String of padding of length <code>len</code>.
*
- * @param newline the new value of 'newLine'
+ * @param len The length of the String of padding to create.
+ *
+ * @return The String of padding
*/
- public void setNewLine(final String newline) {
- this.defaultNewLine = newline;
+ protected String createPadding(final int len) {
+ final char[] padding = new char[len];
+ Arrays.fill(padding, ' ');
+
+ return new String(padding);
}
/**
- * Returns the 'newLine'.
+ * Finds the next text wrap position after <code>startPos</code> for the text in <code>text</code> with the column width
+ * <code>width</code>. The wrap point is the last position before startPos+width having a whitespace character (space,
+ * \n, \r). If there is no whitespace character before startPos+width, it will return startPos+width.
*
- * @return the 'newLine'
+ * @param text The text being searched for the wrap position
+ * @param width width of the wrapped text
+ * @param startPos position from which to start the lookup whitespace character
+ * @return position on which the text must be wrapped or -1 if the wrap position is at the end of the text
*/
- public String getNewLine() {
- return defaultNewLine;
+ protected int findWrapPos(final String text, final int width, final int startPos) {
+ // the line ends before the max wrap pos or a new line char found
+ int pos = text.indexOf('\n', startPos);
+ if (pos != -1 && pos <= width) {
+ return pos + 1;
+ }
+
+ pos = text.indexOf('\t', startPos);
+ if (pos != -1 && pos <= width) {
+ return pos + 1;
+ }
+
+ if (startPos + width >= text.length()) {
+ return -1;
+ }
+
+ // look for the last whitespace character before startPos+width
+ for (pos = startPos + width; pos >= startPos; --pos) {
+ final char c = text.charAt(pos);
+ if (c == ' ' || c == '\n' || c == '\r') {
+ break;
+ }
+ }
+
+ // if we found it - just return
+ if (pos > startPos) {
+ return pos;
+ }
+
+ // if we didn't find one, simply chop at startPos+width
+ pos = startPos + width;
+
+ return pos == text.length() ? -1 : pos;
}
/**
- * Sets the 'optPrefix'.
+ * Returns the 'argName'.
*
- * @param prefix the new value of 'optPrefix'
+ * @return the 'argName'
*/
- public void setOptPrefix(final String prefix) {
- this.defaultOptPrefix = prefix;
+ public String getArgName() {
+ return defaultArgName;
}
/**
- * Returns the 'optPrefix'.
+ * Returns the 'descPadding'.
*
- * @return the 'optPrefix'
+ * @return the 'descPadding'
*/
- public String getOptPrefix() {
- return defaultOptPrefix;
+ public int getDescPadding() {
+ return defaultDescPad;
}
/**
- * Sets the 'longOptPrefix'.
+ * Returns the 'leftPadding'.
*
- * @param prefix the new value of 'longOptPrefix'
+ * @return the 'leftPadding'
*/
- public void setLongOptPrefix(final String prefix) {
- this.defaultLongOptPrefix = prefix;
+ public int getLeftPadding() {
+ return defaultLeftPad;
}
/**
@@ -295,17 +348,6 @@ public class HelpFormatter {
}
/**
- * Set the separator displayed between a long option and its value. Ensure that the separator specified is supported by
- * the parser used, typically ' ' or '='.
- *
- * @param longOptSeparator the separator, typically ' ' or '='.
- * @since 1.3
- */
- public void setLongOptSeparator(final String longOptSeparator) {
- this.longOptSeparator = longOptSeparator;
- }
-
- /**
* Returns the separator displayed between a long option and its value.
*
* @return the separator
@@ -316,21 +358,12 @@ public class HelpFormatter {
}
/**
- * Sets the 'argName'.
- *
- * @param name the new value of 'argName'
- */
- public void setArgName(final String name) {
- this.defaultArgName = name;
- }
-
- /**
- * Returns the 'argName'.
+ * Returns the 'newLine'.
*
- * @return the 'argName'
+ * @return the 'newLine'
*/
- public String getArgName() {
- return defaultArgName;
+ public String getNewLine() {
+ return defaultNewLine;
}
/**
@@ -345,64 +378,30 @@ public class HelpFormatter {
}
/**
- * Set the comparator used to sort the options when they output in help text. Passing in a null comparator will keep the
- * options in the order they were declared.
- *
- * @param comparator the {@link Comparator} to use for sorting the options
- * @since 1.2
- */
- public void setOptionComparator(final Comparator<Option> comparator) {
- this.optionComparator = comparator;
- }
-
- /**
- * Print the help for <code>options</code> with the specified command line syntax. This method prints help information
- * to System.out.
- *
- * @param cmdLineSyntax the syntax for this application
- * @param options the Options instance
- */
- public void printHelp(final String cmdLineSyntax, final Options options) {
- printHelp(getWidth(), cmdLineSyntax, null, options, null, false);
- }
-
- /**
- * Print the help for <code>options</code> with the specified command line syntax. This method prints help information
- * to System.out.
+ * Returns the 'optPrefix'.
*
- * @param cmdLineSyntax the syntax for this application
- * @param options the Options instance
- * @param autoUsage whether to print an automatically generated usage statement
+ * @return the 'optPrefix'
*/
- public void printHelp(final String cmdLineSyntax, final Options options, final boolean autoUsage) {
- printHelp(getWidth(), cmdLineSyntax, null, options, null, autoUsage);
+ public String getOptPrefix() {
+ return defaultOptPrefix;
}
/**
- * Print the help for <code>options</code> with the specified command line syntax. This method prints help information
- * to System.out.
+ * Returns the 'syntaxPrefix'.
*
- * @param cmdLineSyntax the syntax for this application
- * @param header the banner to display at the beginning of the help
- * @param options the Options instance
- * @param footer the banner to display at the end of the help
+ * @return the 'syntaxPrefix'
*/
- public void printHelp(final String cmdLineSyntax, final String header, final Options options, final String footer) {
- printHelp(cmdLineSyntax, header, options, footer, false);
+ public String getSyntaxPrefix() {
+ return defaultSyntaxPrefix;
}
/**
- * Print the help for <code>options</code> with the specified command line syntax. This method prints help information
- * to System.out.
+ * Returns the 'width'.
*
- * @param cmdLineSyntax the syntax for this application
- * @param header the banner to display at the beginning of the help
- * @param options the Options instance
- * @param footer the banner to display at the end of the help
- * @param autoUsage whether to print an automatically generated usage statement
+ * @return the 'width'
*/
- public void printHelp(final String cmdLineSyntax, final String header, final Options options, final String footer, final boolean autoUsage) {
- printHelp(getWidth(), cmdLineSyntax, header, options, footer, autoUsage);
+ public int getWidth() {
+ return defaultWidth;
}
/**
@@ -496,134 +495,53 @@ public class HelpFormatter {
}
/**
- * Prints the usage statement for the specified application.
+ * Print the help for <code>options</code> with the specified command line syntax. This method prints help information
+ * to System.out.
*
- * @param pw The PrintWriter to print the usage statement
- * @param width The number of characters to display per line
- * @param app The application name
- * @param options The command line Options
+ * @param cmdLineSyntax the syntax for this application
+ * @param options the Options instance
*/
- public void printUsage(final PrintWriter pw, final int width, final String app, final Options options) {
- // initialize the string buffer
- final StringBuffer buff = new StringBuffer(getSyntaxPrefix()).append(app).append(" ");
-
- // create a list for processed option groups
- final Collection<OptionGroup> processedGroups = new ArrayList<>();
-
- final List<Option> optList = new ArrayList<>(options.getOptions());
- if (getOptionComparator() != null) {
- Collections.sort(optList, getOptionComparator());
- }
- // iterate over the options
- for (final Iterator<Option> it = optList.iterator(); it.hasNext();) {
- // get the next Option
- final Option option = it.next();
-
- // check if the option is part of an OptionGroup
- final OptionGroup group = options.getOptionGroup(option);
-
- // if the option is part of a group
- if (group != null) {
- // and if the group has not already been processed
- if (!processedGroups.contains(group)) {
- // add the group to the processed list
- processedGroups.add(group);
-
- // add the usage clause
- appendOptionGroup(buff, group);
- }
-
- // otherwise the option was displayed in the group
- // previously so ignore it.
- }
-
- // if the Option is not part of an OptionGroup
- else {
- appendOption(buff, option, option.isRequired());
- }
-
- if (it.hasNext()) {
- buff.append(" ");
- }
- }
-
- // call printWrapped
- printWrapped(pw, width, buff.toString().indexOf(' ') + 1, buff.toString());
+ public void printHelp(final String cmdLineSyntax, final Options options) {
+ printHelp(getWidth(), cmdLineSyntax, null, options, null, false);
}
/**
- * Appends the usage clause for an OptionGroup to a StringBuffer. The clause is wrapped in square brackets if the group
- * is required. The display of the options is handled by appendOption
+ * Print the help for <code>options</code> with the specified command line syntax. This method prints help information
+ * to System.out.
*
- * @param buff the StringBuffer to append to
- * @param group the group to append
- * @see #appendOption(StringBuffer,Option,boolean)
+ * @param cmdLineSyntax the syntax for this application
+ * @param options the Options instance
+ * @param autoUsage whether to print an automatically generated usage statement
*/
- private void appendOptionGroup(final StringBuffer buff, final OptionGroup group) {
- if (!group.isRequired()) {
- buff.append("[");
- }
-
- final List<Option> optList = new ArrayList<>(group.getOptions());
- if (getOptionComparator() != null) {
- Collections.sort(optList, getOptionComparator());
- }
- // for each option in the OptionGroup
- for (final Iterator<Option> it = optList.iterator(); it.hasNext();) {
- // whether the option is required or not is handled at group level
- appendOption(buff, it.next(), true);
-
- if (it.hasNext()) {
- buff.append(" | ");
- }
- }
-
- if (!group.isRequired()) {
- buff.append("]");
- }
+ public void printHelp(final String cmdLineSyntax, final Options options, final boolean autoUsage) {
+ printHelp(getWidth(), cmdLineSyntax, null, options, null, autoUsage);
}
/**
- * Appends the usage clause for an Option to a StringBuffer.
+ * Print the help for <code>options</code> with the specified command line syntax. This method prints help information
+ * to System.out.
*
- * @param buff the StringBuffer to append to
- * @param option the Option to append
- * @param required whether the Option is required or not
- */
- private void appendOption(final StringBuffer buff, final Option option, final boolean required) {
- if (!required) {
- buff.append("[");
- }
-
- if (option.getOpt() != null) {
- buff.append("-").append(option.getOpt());
- } else {
- buff.append("--").append(option.getLongOpt());
- }
-
- // if the Option has a value and a non blank argname
- if (option.hasArg() && (option.getArgName() == null || !option.getArgName().isEmpty())) {
- buff.append(option.getOpt() == null ? longOptSeparator : " ");
- buff.append("<").append(option.getArgName() != null ? option.getArgName() : getArgName()).append(">");
- }
-
- // if the Option is not a required option
- if (!required) {
- buff.append("]");
- }
+ * @param cmdLineSyntax the syntax for this application
+ * @param header the banner to display at the beginning of the help
+ * @param options the Options instance
+ * @param footer the banner to display at the end of the help
+ */
+ public void printHelp(final String cmdLineSyntax, final String header, final Options options, final String footer) {
+ printHelp(cmdLineSyntax, header, options, footer, false);
}
/**
- * Print the cmdLineSyntax to the specified writer, using the specified width.
+ * Print the help for <code>options</code> with the specified command line syntax. This method prints help information
+ * to System.out.
*
- * @param pw The printWriter to write the help to
- * @param width The number of characters per line for the usage statement.
- * @param cmdLineSyntax The usage statement.
+ * @param cmdLineSyntax the syntax for this application
+ * @param header the banner to display at the beginning of the help
+ * @param options the Options instance
+ * @param footer the banner to display at the end of the help
+ * @param autoUsage whether to print an automatically generated usage statement
*/
- public void printUsage(final PrintWriter pw, final int width, final String cmdLineSyntax) {
- final int argPos = cmdLineSyntax.indexOf(' ') + 1;
-
- printWrapped(pw, width, getSyntaxPrefix().length() + argPos, getSyntaxPrefix() + cmdLineSyntax);
+ public void printHelp(final String cmdLineSyntax, final String header, final Options options, final String footer, final boolean autoUsage) {
+ printHelp(getWidth(), cmdLineSyntax, header, options, footer, autoUsage);
}
/**
@@ -644,14 +562,72 @@ public class HelpFormatter {
}
/**
- * Print the specified text to the specified PrintWriter.
+ * Print the cmdLineSyntax to the specified writer, using the specified width.
*
* @param pw The printWriter to write the help to
+ * @param width The number of characters per line for the usage statement.
+ * @param cmdLineSyntax The usage statement.
+ */
+ public void printUsage(final PrintWriter pw, final int width, final String cmdLineSyntax) {
+ final int argPos = cmdLineSyntax.indexOf(' ') + 1;
+
+ printWrapped(pw, width, getSyntaxPrefix().length() + argPos, getSyntaxPrefix() + cmdLineSyntax);
+ }
+
+ /**
+ * Prints the usage statement for the specified application.
+ *
+ * @param pw The PrintWriter to print the usage statement
* @param width The number of characters to display per line
- * @param text The text to be written to the PrintWriter
+ * @param app The application name
+ * @param options The command line Options
*/
- public void printWrapped(final PrintWriter pw, final int width, final String text) {
- printWrapped(pw, width, 0, text);
+ public void printUsage(final PrintWriter pw, final int width, final String app, final Options options) {
+ // initialize the string buffer
+ final StringBuffer buff = new StringBuffer(getSyntaxPrefix()).append(app).append(" ");
+
+ // create a list for processed option groups
+ final Collection<OptionGroup> processedGroups = new ArrayList<>();
+
+ final List<Option> optList = new ArrayList<>(options.getOptions());
+ if (getOptionComparator() != null) {
+ Collections.sort(optList, getOptionComparator());
+ }
+ // iterate over the options
+ for (final Iterator<Option> it = optList.iterator(); it.hasNext();) {
+ // get the next Option
+ final Option option = it.next();
+
+ // check if the option is part of an OptionGroup
+ final OptionGroup group = options.getOptionGroup(option);
+
+ // if the option is part of a group
+ if (group != null) {
+ // and if the group has not already been processed
+ if (!processedGroups.contains(group)) {
+ // add the group to the processed list
+ processedGroups.add(group);
+
+ // add the usage clause
+ appendOptionGroup(buff, group);
+ }
+
+ // otherwise the option was displayed in the group
+ // previously so ignore it.
+ }
+
+ // if the Option is not part of an OptionGroup
+ else {
+ appendOption(buff, option, option.isRequired());
+ }
+
+ if (it.hasNext()) {
+ buff.append(" ");
+ }
+ }
+
+ // call printWrapped
+ printWrapped(pw, width, buff.toString().indexOf(' ') + 1, buff.toString());
}
/**
@@ -669,7 +645,16 @@ public class HelpFormatter {
pw.println(sb.toString());
}
- // --------------------------------------------------------------- Protected
+ /**
+ * Print the specified text to the specified PrintWriter.
+ *
+ * @param pw The printWriter to write the help to
+ * @param width The number of characters to display per line
+ * @param text The text to be written to the PrintWriter
+ */
+ public void printWrapped(final PrintWriter pw, final int width, final String text) {
+ printWrapped(pw, width, 0, text);
+ }
/**
* Render the specified Options and return the rendered Options in a StringBuffer.
@@ -832,105 +817,120 @@ public class HelpFormatter {
}
/**
- * Finds the next text wrap position after <code>startPos</code> for the text in <code>text</code> with the column width
- * <code>width</code>. The wrap point is the last position before startPos+width having a whitespace character (space,
- * \n, \r). If there is no whitespace character before startPos+width, it will return startPos+width.
+ * Remove the trailing whitespace from the specified String.
*
- * @param text The text being searched for the wrap position
- * @param width width of the wrapped text
- * @param startPos position from which to start the lookup whitespace character
- * @return position on which the text must be wrapped or -1 if the wrap position is at the end of the text
+ * @param s The String to remove the trailing padding from.
+ *
+ * @return The String of without the trailing padding
*/
- protected int findWrapPos(final String text, final int width, final int startPos) {
- // the line ends before the max wrap pos or a new line char found
- int pos = text.indexOf('\n', startPos);
- if (pos != -1 && pos <= width) {
- return pos + 1;
- }
-
- pos = text.indexOf('\t', startPos);
- if (pos != -1 && pos <= width) {
- return pos + 1;
- }
-
- if (startPos + width >= text.length()) {
- return -1;
+ protected String rtrim(final String s) {
+ if (s == null || s.isEmpty()) {
+ return s;
}
- // look for the last whitespace character before startPos+width
- for (pos = startPos + width; pos >= startPos; --pos) {
- final char c = text.charAt(pos);
- if (c == ' ' || c == '\n' || c == '\r') {
- break;
- }
- }
+ int pos = s.length();
- // if we found it - just return
- if (pos > startPos) {
- return pos;
+ while (pos > 0 && Character.isWhitespace(s.charAt(pos - 1))) {
+ --pos;
}
- // if we didn't find one, simply chop at startPos+width
- pos = startPos + width;
-
- return pos == text.length() ? -1 : pos;
+ return s.substring(0, pos);
}
/**
- * Return a String of padding of length <code>len</code>.
+ * Sets the 'argName'.
*
- * @param len The length of the String of padding to create.
+ * @param name the new value of 'argName'
+ */
+ public void setArgName(final String name) {
+ this.defaultArgName = name;
+ }
+
+ /**
+ * Sets the 'descPadding'.
*
- * @return The String of padding
+ * @param padding the new value of 'descPadding'
*/
- protected String createPadding(final int len) {
- final char[] padding = new char[len];
- Arrays.fill(padding, ' ');
+ public void setDescPadding(final int padding) {
+ this.defaultDescPad = padding;
+ }
- return new String(padding);
+ /**
+ * Sets the 'leftPadding'.
+ *
+ * @param padding the new value of 'leftPadding'
+ */
+ public void setLeftPadding(final int padding) {
+ this.defaultLeftPad = padding;
}
+ // --------------------------------------------------------------- Protected
+
/**
- * Remove the trailing whitespace from the specified String.
+ * Sets the 'longOptPrefix'.
*
- * @param s The String to remove the trailing padding from.
+ * @param prefix the new value of 'longOptPrefix'
+ */
+ public void setLongOptPrefix(final String prefix) {
+ this.defaultLongOptPrefix = prefix;
+ }
+
+ /**
+ * Set the separator displayed between a long option and its value. Ensure that the separator specified is supported by
+ * the parser used, typically ' ' or '='.
*
- * @return The String of without the trailing padding
+ * @param longOptSeparator the separator, typically ' ' or '='.
+ * @since 1.3
*/
- protected String rtrim(final String s) {
- if (s == null || s.isEmpty()) {
- return s;
- }
+ public void setLongOptSeparator(final String longOptSeparator) {
+ this.longOptSeparator = longOptSeparator;
+ }
- int pos = s.length();
+ /**
+ * Sets the 'newLine'.
+ *
+ * @param newline the new value of 'newLine'
+ */
+ public void setNewLine(final String newline) {
+ this.defaultNewLine = newline;
+ }
- while (pos > 0 && Character.isWhitespace(s.charAt(pos - 1))) {
- --pos;
- }
+ /**
+ * Set the comparator used to sort the options when they output in help text. Passing in a null comparator will keep the
+ * options in the order they were declared.
+ *
+ * @param comparator the {@link Comparator} to use for sorting the options
+ * @since 1.2
+ */
+ public void setOptionComparator(final Comparator<Option> comparator) {
+ this.optionComparator = comparator;
+ }
- return s.substring(0, pos);
+ /**
+ * Sets the 'optPrefix'.
+ *
+ * @param prefix the new value of 'optPrefix'
+ */
+ public void setOptPrefix(final String prefix) {
+ this.defaultOptPrefix = prefix;
}
/**
- * This class implements the <code>Comparator</code> interface for comparing Options.
+ * Sets the 'syntaxPrefix'.
+ *
+ * @param prefix the new value of 'syntaxPrefix'
*/
- private static class OptionComparator implements Comparator<Option>, Serializable {
- /** The serial version UID. */
- private static final long serialVersionUID = 5305467873966684014L;
+ public void setSyntaxPrefix(final String prefix) {
+ this.defaultSyntaxPrefix = prefix;
+ }
- /**
- * Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument
- * is less than, equal to, or greater than the second.
- *
- * @param opt1 The first Option to be compared.
- * @param opt2 The second Option to be compared.
- * @return a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than
- * the second.
- */
- @Override
- public int compare(final Option opt1, final Option opt2) {
- return opt1.getKey().compareToIgnoreCase(opt2.getKey());
- }
+ /**
+ * Sets the 'width'.
+ *
+ * @param width the new value of 'width'
+ */
+ public void setWidth(final int width) {
+ this.defaultWidth = width;
}
}
diff --git a/src/main/java/org/apache/commons/cli/MissingArgumentException.java b/src/main/java/org/apache/commons/cli/MissingArgumentException.java
index 8e98e79..a03e3f3 100644
--- a/src/main/java/org/apache/commons/cli/MissingArgumentException.java
+++ b/src/main/java/org/apache/commons/cli/MissingArgumentException.java
@@ -32,21 +32,21 @@ public class MissingArgumentException extends ParseException {
/**
* Construct a new <code>MissingArgumentException</code> with the specified detail message.
*
- * @param message the detail message
+ * @param option the option requiring an argument
+ * @since 1.2
*/
- public MissingArgumentException(final String message) {
- super(message);
+ public MissingArgumentException(final Option option) {
+ this("Missing argument for option: " + option.getKey());
+ this.option = option;
}
/**
* Construct a new <code>MissingArgumentException</code> with the specified detail message.
*
- * @param option the option requiring an argument
- * @since 1.2
+ * @param message the detail message
*/
- public MissingArgumentException(final Option option) {
- this("Missing argument for option: " + option.getKey());
- this.option = option;
+ public MissingArgumentException(final String message) {
+ super(message);
}
/**
diff --git a/src/main/java/org/apache/commons/cli/MissingOptionException.java b/src/main/java/org/apache/commons/cli/MissingOptionException.java
index c18cb2c..fb1c434 100644
--- a/src/main/java/org/apache/commons/cli/MissingOptionException.java
+++ b/src/main/java/org/apache/commons/cli/MissingOptionException.java
@@ -27,18 +27,31 @@ public class MissingOptionException extends ParseException {
/** This exception {@code serialVersionUID}. */
private static final long serialVersionUID = 8161889051578563249L;
- /** The list of missing options and groups */
- private List missingOptions;
-
/**
- * Construct a new <code>MissingSelectedException</code> with the specified detail message.
+ * Build the exception message from the specified list of options.
*
- * @param message the detail message
+ * @param missingOptions the list of missing options and groups
+ * @since 1.2
*/
- public MissingOptionException(final String message) {
- super(message);
+ private static String createMessage(final List<?> missingOptions) {
+ final StringBuilder buf = new StringBuilder("Missing required option");
+ buf.append(missingOptions.size() == 1 ? "" : "s");
+ buf.append(": ");
+
+ final Iterator<?> it = missingOptions.iterator();
+ while (it.hasNext()) {
+ buf.append(it.next());
+ if (it.hasNext()) {
+ buf.append(", ");
+ }
+ }
+
+ return buf.toString();
}
+ /** The list of missing options and groups */
+ private List missingOptions;
+
/**
* Constructs a new <code>MissingSelectedException</code> with the specified list of missing options.
*
@@ -51,35 +64,22 @@ public class MissingOptionException extends ParseException {
}
/**
- * Returns the list of options or option groups missing in the command line parsed.
+ * Construct a new <code>MissingSelectedException</code> with the specified detail message.
*
- * @return the missing options, consisting of String instances for simple options, and OptionGroup instances for
- * required option groups.
- * @since 1.2
+ * @param message the detail message
*/
- public List getMissingOptions() {
- return missingOptions;
+ public MissingOptionException(final String message) {
+ super(message);
}
/**
- * Build the exception message from the specified list of options.
+ * Returns the list of options or option groups missing in the command line parsed.
*
- * @param missingOptions the list of missing options and groups
+ * @return the missing options, consisting of String instances for simple options, and OptionGroup instances for
+ * required option groups.
* @since 1.2
*/
- private static String createMessage(final List<?> missingOptions) {
- final StringBuilder buf = new StringBuilder("Missing required option");
- buf.append(missingOptions.size() == 1 ? "" : "s");
- buf.append(": ");
-
- final Iterator<?> it = missingOptions.iterator();
- while (it.hasNext()) {
- buf.append(it.next());
- if (it.hasNext()) {
- buf.append(", ");
- }
- }
-
- return buf.toString();
+ public List getMissingOptions() {
+ return missingOptions;
}
}
diff --git a/src/main/java/org/apache/commons/cli/Option.java b/src/main/java/org/apache/commons/cli/Option.java
index d61878d..c3b98fc 100644
--- a/src/main/java/org/apache/commons/cli/Option.java
+++ b/src/main/java/org/apache/commons/cli/Option.java
@@ -36,6 +36,220 @@ import java.util.List;
* @see org.apache.commons.cli.CommandLine
*/
public class Option implements Cloneable, Serializable {
+ /**
+ * A nested builder class to create <code>Option</code> instances using descriptive methods.
+ * <p>
+ * Example usage:
+ *
+ * <pre>
+ * Option option = Option.builder("a").required(true).longOpt("arg-name").build();
+ * </pre>
+ *
+ * @since 1.3
+ */
+ public static final class Builder {
+ /** the name of the option */
+ private final String opt;
+
+ /** description of the option */
+ private String description;
+
+ /** the long representation of the option */
+ private String longOpt;
+
+ /** the name of the argument for this option */
+ private String argName;
+
+ /** specifies whether this option is required to be present */
+ private boolean required;
+
+ /** specifies whether the argument value of this Option is optional */
+ private boolean optionalArg;
+
+ /** the number of argument values this option can have */
+ private int numberOfArgs = UNINITIALIZED;
+
+ /** the type of this Option */
+ private Class<?> type = String.class;
+
+ /** the character that is the value separator */
+ private char valuesep;
+
+ /**
+ * Constructs a new <code>Builder</code> with the minimum required parameters for an <code>Option</code> instance.
+ *
+ * @param opt short representation of the option
+ * @throws IllegalArgumentException if there are any non valid Option characters in {@code opt}
+ */
+ private Builder(final String opt) throws IllegalArgumentException {
+ OptionValidator.validateOption(opt);
+ this.opt = opt;
+ }
+
+ /**
+ * Sets the display name for the argument value.
+ *
+ * @param argName the display name for the argument value.
+ * @return this builder, to allow method chaining
+ */
+ public Builder argName(final String argName) {
+ this.argName = argName;
+ return this;
+ }
+
+ /**
+ * Constructs an Option with the values declared by this {@link Builder}.
+ *
+ * @return the new {@link Option}
+ * @throws IllegalArgumentException if neither {@code opt} or {@code longOpt} has been set
+ */
+ public Option build() {
+ if (opt == null && longOpt == null) {
+ throw new IllegalArgumentException("Either opt or longOpt must be specified");
+ }
+ return new Option(this);
+ }
+
+ /**
+ * Sets the description for this option.
+ *
+ * @param description the description of the option.
+ * @return this builder, to allow method chaining
+ */
+ public Builder desc(final String description) {
+ this.description = description;
+ return this;
+ }
+
+ /**
+ * Indicates that the Option will require an argument.
+ *
+ * @return this builder, to allow method chaining
+ */
+ public Builder hasArg() {
+ return hasArg(true);
+ }
+
+ /**
+ * Indicates if the Option has an argument or not.
+ *
+ * @param hasArg specifies whether the Option takes an argument or not
+ * @return this builder, to allow method chaining
+ */
+ public Builder hasArg(final boolean hasArg) {
+ // set to UNINITIALIZED when no arg is specified to be compatible with OptionBuilder
+ numberOfArgs = hasArg ? 1 : Option.UNINITIALIZED;
+ return this;
+ }
+
+ /**
+ * Indicates that the Option can have unlimited argument values.
+ *
+ * @return this builder, to allow method chaining
+ */
+ public Builder hasArgs() {
+ numberOfArgs = Option.UNLIMITED_VALUES;
+ return this;
+ }
+
+ /**
+ * Sets the long name of the Option.
+ *
+ * @param longOpt the long name of the Option
+ * @return this builder, to allow method chaining
+ */
+ public Builder longOpt(final String longOpt) {
+ this.longOpt = longOpt;
+ return this;
+ }
+
+ /**
+ * Sets the number of argument values the Option can take.
+ *
+ * @param numberOfArgs the number of argument values
+ * @return this builder, to allow method chaining
+ */
+ public Builder numberOfArgs(final int numberOfArgs) {
+ this.numberOfArgs = numberOfArgs;
+ return this;
+ }
+
+ /**
+ * Sets whether the Option can have an optional argument.
+ *
+ * @param isOptional specifies whether the Option can have an optional argument.
+ * @return this builder, to allow method chaining
+ */
+ public Builder optionalArg(final boolean isOptional) {
+ this.optionalArg = isOptional;
+ return this;
+ }
+
+ /**
+ * Marks this Option as required.
+ *
+ * @return this builder, to allow method chaining
+ */
+ public Builder required() {
+ return required(true);
+ }
+
+ /**
+ * Sets whether the Option is mandatory.
+ *
+ * @param required specifies whether the Option is mandatory
+ * @return this builder, to allow method chaining
+ */
+ public Builder required(final boolean required) {
+ this.required = required;
+ return this;
+ }
+
+ /**
+ * Sets the type of the Option.
+ *
+ * @param type the type of the Option
+ * @return this builder, to allow method chaining
+ */
+ public Builder type(final Class<?> type) {
+ this.type = type;
+ return this;
+ }
+
+ /**
+ * The Option will use '=' as a means to separate argument value.
+ *
+ * @return this builder, to allow method chaining
+ */
+ public Builder valueSeparator() {
+ return valueSeparator('=');
+ }
+
+ /**
+ * The Option will use <code>sep</code> as a means to separate argument values.
+ * <p>
+ * <b>Example:</b>
+ *
+ * <pre>
+ * Option opt = Option.builder("D").hasArgs().valueSeparator('=').build();
+ * Options options = new Options();
+ * options.addOption(opt);
+ * String[] args = {"-Dkey=value"};
+ * CommandLineParser parser = new DefaultParser();
+ * CommandLine line = parser.parse(options, args);
+ * String propertyName = line.getOptionValues("D")[0]; // will be "key"
+ * String propertyValue = line.getOptionValues("D")[1]; // will be "value"
+ * </pre>
+ *
+ * @param sep The value separator.
+ * @return this builder, to allow method chaining
+ */
+ public Builder valueSeparator(final char sep) {
+ valuesep = sep;
+ return this;
+ }
+ }
+
/** constant that specifies the number of argument values has not been specified */
public static final int UNINITIALIZED = -1;
@@ -45,6 +259,28 @@ public class Option implements Cloneable, Serializable {
/** The serial version UID. */
private static final long serialVersionUID = 1L;
+ /**
+ * Returns a {@link Builder} to create an {@link Option} using descriptive methods.
+ *
+ * @return a new {@link Builder} instance
+ * @since 1.3
+ */
+ public static Builder builder() {
+ return builder(null);
+ }
+
+ /**
+ * Returns a {@link Builder} to create an {@link Option} using descriptive methods.
+ *
+ * @param opt short representation of the option
+ * @return a new {@link Builder} instance
+ * @throws IllegalArgumentException if there are any non valid Option characters in {@code opt}
+ * @since 1.3
+ */
+ public static Builder builder(final String opt) {
+ return new Builder(opt);
+ }
+
/** the name of the option */
private final String opt;
@@ -93,28 +329,28 @@ public class Option implements Cloneable, Serializable {
}
/**
- * Creates an Option using the specified parameters. The option does not take an argument.
+ * Creates an Option using the specified parameters.
*
* @param opt short representation of the option
+ * @param hasArg specifies whether the Option takes an argument or not
* @param description describes the function of the option
*
* @throws IllegalArgumentException if there are any non valid Option characters in <code>opt</code>.
*/
- public Option(final String opt, final String description) throws IllegalArgumentException {
- this(opt, null, false, description);
+ public Option(final String opt, final boolean hasArg, final String description) throws IllegalArgumentException {
+ this(opt, null, hasArg, description);
}
/**
- * Creates an Option using the specified parameters.
+ * Creates an Option using the specified parameters. The option does not take an argument.
*
* @param opt short representation of the option
- * @param hasArg specifies whether the Option takes an argument or not
* @param description describes the function of the option
*
* @throws IllegalArgumentException if there are any non valid Option characters in <code>opt</code>.
*/
- public Option(final String opt, final boolean hasArg, final String description) throws IllegalArgumentException {
- this(opt, null, hasArg, description);
+ public Option(final String opt, final String description) throws IllegalArgumentException {
+ this(opt, null, false, description);
}
/**
@@ -143,120 +379,134 @@ public class Option implements Cloneable, Serializable {
}
/**
- * Returns the id of this Option. This is only set when the Option shortOpt is a single character. This is used for
- * switch statements.
+ * Tells if the option can accept more arguments.
*
- * @return the id of this Option
+ * @return false if the maximum number of arguments is reached
+ * @since 1.3
*/
- public int getId() {
- return getKey().charAt(0);
- }
-
- /**
- * Returns the 'unique' Option identifier.
- *
- * @return the 'unique' Option identifier
- */
- String getKey() {
- // if 'opt' is null, then it is a 'long' option
- return (opt == null) ? longOpt : opt;
+ boolean acceptsArg() {
+ return (hasArg() || hasArgs() || hasOptionalArg()) && (numberOfArgs <= 0 || values.size() < numberOfArgs);
}
/**
- * Retrieve the name of this Option.
+ * Add the value to this Option. If the number of arguments is greater than zero and there is enough space in the list
+ * then add the value. Otherwise, throw a runtime exception.
*
- * It is this String which can be used with {@link CommandLine#hasOption(String opt)} and
- * {@link CommandLine#getOptionValue(String opt)} to check for existence and argument.
+ * @param value The value to be added to this Option
*
- * @return The name of this option
+ * @since 1.0.1
*/
- public String getOpt() {
- return opt;
- }
+ private void add(final String value) {
+ if (!acceptsArg()) {
+ throw new RuntimeException("Cannot add value, list full.");
+ }
- /**
- * Retrieve the type of this Option.
- *
- * @return The type of this option
- */
- public Object getType() {
- return type;
+ // store value
+ values.add(value);
}
/**
- * Sets the type of this Option.
- * <p>
- * <b>Note:</b> this method is kept for binary compatibility and the input type is supposed to be a {@link Class}
- * object.
+ * This method is not intended to be used. It was a piece of internal API that was made public in 1.0. It currently
+ * throws an UnsupportedOperationException.
*
- * @param type the type of this Option
- * @deprecated since 1.3, use {@link #setType(Class)} instead
+ * @param value the value to add
+ * @return always throws an {@link UnsupportedOperationException}
+ * @throws UnsupportedOperationException always
+ * @deprecated
*/
@Deprecated
- public void setType(final Object type) {
- setType((Class<?>) type);
+ public boolean addValue(final String value) {
+ throw new UnsupportedOperationException(
+ "The addValue method is not intended for client use. " + "Subclasses should use the addValueForProcessing method instead. ");
}
/**
- * Sets the type of this Option.
+ * Adds the specified value to this Option.
*
- * @param type the type of this Option
- * @since 1.3
+ * @param value is a/the value of this Option
*/
- public void setType(final Class<?> type) {
- this.type = type;
+ void addValueForProcessing(final String value) {
+ if (numberOfArgs == UNINITIALIZED) {
+ throw new RuntimeException("NO_ARGS_ALLOWED");
+ }
+ processValue(value);
}
/**
- * Retrieve the long name of this Option.
+ * Clear the Option values. After a parse is complete, these are left with data in them and they need clearing if
+ * another parse is done.
*
- * @return Long name of this option, or null, if there is no long name
+ * See: <a href="https://issues.apache.org/jira/browse/CLI-71">CLI-71</a>
*/
- public String getLongOpt() {
- return longOpt;
+ void clearValues() {
+ values.clear();
}
/**
- * Sets the long name of this Option.
+ * A rather odd clone method - due to incorrect code in 1.0 it is public and in 1.1 rather than throwing a
+ * CloneNotSupportedException it throws a RuntimeException so as to maintain backwards compat at the API level.
*
- * @param longOpt the long name of this Option
- */
- public void setLongOpt(final String longOpt) {
- this.longOpt = longOpt;
- }
-
- /**
- * Sets whether this Option can have an optional argument.
+ * After calling this method, it is very likely you will want to call clearValues().
*
- * @param optionalArg specifies whether the Option can have an optional argument.
+ * @return a clone of this Option instance
+ * @throws RuntimeException if a {@link CloneNotSupportedException} has been thrown by {@code super.clone()}
*/
- public void setOptionalArg(final boolean optionalArg) {
- this.optionalArg = optionalArg;
+ @Override
+ public Object clone() {
+ try {
+ final Option option = (Option) super.clone();
+ option.values = new ArrayList<>(values);
+ return option;
+ } catch (final CloneNotSupportedException cnse) {
+ throw new RuntimeException("A CloneNotSupportedException was thrown: " + cnse.getMessage());
+ }
}
- /**
- * @return whether this Option can have an optional argument
- */
- public boolean hasOptionalArg() {
- return optionalArg;
+ @Override
+ public boolean equals(final Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+
+ final Option option = (Option) o;
+
+ if (opt != null ? !opt.equals(option.opt) : option.opt != null) {
+ return false;
+ }
+ if (longOpt != null ? !longOpt.equals(option.longOpt) : option.longOpt != null) {
+ return false;
+ }
+
+ return true;
}
/**
- * Query to see if this Option has a long name
+ * Gets the display name for the argument value.
*
- * @return boolean flag indicating existence of a long name
+ * @return the display name for the argument value.
*/
- public boolean hasLongOpt() {
- return longOpt != null;
+ public String getArgName() {
+ return argName;
}
/**
- * Query to see if this Option requires an argument
+ * Returns the number of argument values this Option can take.
*
- * @return boolean flag indicating if an argument is required
+ * <p>
+ * A value equal to the constant {@link #UNINITIALIZED} (= -1) indicates the number of arguments has not been specified.
+ * A value equal to the constant {@link #UNLIMITED_VALUES} (= -2) indicates that this options takes an unlimited amount
+ * of values.
+ * </p>
+ *
+ * @return num the number of argument values
+ * @see #UNINITIALIZED
+ * @see #UNLIMITED_VALUES
*/
- public boolean hasArg() {
- return numberOfArgs > 0 || numberOfArgs == UNLIMITED_VALUES;
+ public int getArgs() {
+ return numberOfArgs;
}
/**
@@ -269,85 +519,97 @@ public class Option implements Cloneable, Serializable {
}
/**
- * Sets the self-documenting description of this Option
+ * Returns the id of this Option. This is only set when the Option shortOpt is a single character. This is used for
+ * switch statements.
*
- * @param description The description of this option
- * @since 1.1
+ * @return the id of this Option
*/
- public void setDescription(final String description) {
- this.description = description;
+ public int getId() {
+ return getKey().charAt(0);
}
/**
- * Query to see if this Option is mandatory
+ * Returns the 'unique' Option identifier.
*
- * @return boolean flag indicating whether this Option is mandatory
+ * @return the 'unique' Option identifier
*/
- public boolean isRequired() {
- return required;
+ String getKey() {
+ // if 'opt' is null, then it is a 'long' option
+ return (opt == null) ? longOpt : opt;
}
/**
- * Sets whether this Option is mandatory.
+ * Retrieve the long name of this Option.
*
- * @param required specifies whether this Option is mandatory
+ * @return Long name of this option, or null, if there is no long name
*/
- public void setRequired(final boolean required) {
- this.required = required;
+ public String getLongOpt() {
+ return longOpt;
}
/**
- * Sets the display name for the argument value.
+ * Retrieve the name of this Option.
*
- * @param argName the display name for the argument value.
+ * It is this String which can be used with {@link CommandLine#hasOption(String opt)} and
+ * {@link CommandLine#getOptionValue(String opt)} to check for existence and argument.
+ *
+ * @return The name of this option
*/
- public void setArgName(final String argName) {
- this.argName = argName;
+ public String getOpt() {
+ return opt;
}
/**
- * Gets the display name for the argument value.
+ * Retrieve the type of this Option.
*
- * @return the display name for the argument value.
+ * @return The type of this option
*/
- public String getArgName() {
- return argName;
+ public Object getType() {
+ return type;
}
/**
- * Returns whether the display name for the argument value has been set.
+ * Returns the specified value of this Option or <code>null</code> if there is no value.
*
- * @return if the display name for the argument value has been set.
+ * @return the value/first value of this Option or <code>null</code> if there is no value.
*/
- public boolean hasArgName() {
- return argName != null && !argName.isEmpty();
+ public String getValue() {
+ return hasNoValues() ? null : values.get(0);
}
/**
- * Query to see if this Option can take many values.
+ * Returns the specified value of this Option or <code>null</code> if there is no value.
*
- * @return boolean flag indicating if multiple values are allowed
+ * @param index The index of the value to be returned.
+ *
+ * @return the specified value of this Option or <code>null</code> if there is no value.
+ *
+ * @throws IndexOutOfBoundsException if index is less than 1 or greater than the number of the values for this Option.
*/
- public boolean hasArgs() {
- return numberOfArgs > 1 || numberOfArgs == UNLIMITED_VALUES;
+ public String getValue(final int index) throws IndexOutOfBoundsException {
+ return hasNoValues() ? null : values.get(index);
}
/**
- * Sets the number of argument values this Option can take.
+ * Returns the value/first value of this Option or the <code>defaultValue</code> if there is no value.
*
- * @param num the number of argument values
+ * @param defaultValue The value to be returned if there is no value.
+ *
+ * @return the value/first value of this Option or the <code>defaultValue</code> if there are no values.
*/
- public void setArgs(final int num) {
- this.numberOfArgs = num;
+ public String getValue(final String defaultValue) {
+ final String value = getValue();
+
+ return (value != null) ? value : defaultValue;
}
/**
- * Sets the value separator. For example if the argument value was a Java property, the value separator would be '='.
+ * Return the values of this Option as a String array or null if there are no values
*
- * @param sep The value separator.
+ * @return the values of this Option as a String array or null if there are no values
*/
- public void setValueSeparator(final char sep) {
- this.valuesep = sep;
+ public String[] getValues() {
+ return hasNoValues() ? null : values.toArray(new String[values.size()]);
}
/**
@@ -360,42 +622,89 @@ public class Option implements Cloneable, Serializable {
}
/**
- * Return whether this Option has specified a value separator.
+ * @return the values of this Option as a List or null if there are no values
+ */
+ public List<String> getValuesList() {
+ return values;
+ }
+
+ /**
+ * Query to see if this Option requires an argument
*
- * @return whether this Option has specified a value separator.
- * @since 1.1
+ * @return boolean flag indicating if an argument is required
*/
- public boolean hasValueSeparator() {
- return valuesep > 0;
+ public boolean hasArg() {
+ return numberOfArgs > 0 || numberOfArgs == UNLIMITED_VALUES;
}
/**
- * Returns the number of argument values this Option can take.
+ * Returns whether the display name for the argument value has been set.
*
- * <p>
- * A value equal to the constant {@link #UNINITIALIZED} (= -1) indicates the number of arguments has not been specified.
- * A value equal to the constant {@link #UNLIMITED_VALUES} (= -2) indicates that this options takes an unlimited amount
- * of values.
- * </p>
+ * @return if the display name for the argument value has been set.
+ */
+ public boolean hasArgName() {
+ return argName != null && !argName.isEmpty();
+ }
+
+ /**
+ * Query to see if this Option can take many values.
*
- * @return num the number of argument values
- * @see #UNINITIALIZED
- * @see #UNLIMITED_VALUES
+ * @return boolean flag indicating if multiple values are allowed
*/
- public int getArgs() {
- return numberOfArgs;
+ public boolean hasArgs() {
+ return numberOfArgs > 1 || numberOfArgs == UNLIMITED_VALUES;
+ }
+
+ @Override
+ public int hashCode() {
+ int result;
+ result = opt != null ? opt.hashCode() : 0;
+ result = 31 * result + (longOpt != null ? longOpt.hashCode() : 0);
+ return result;
}
/**
- * Adds the specified value to this Option.
+ * Query to see if this Option has a long name
*
- * @param value is a/the value of this Option
+ * @return boolean flag indicating existence of a long name
*/
- void addValueForProcessing(final String value) {
- if (numberOfArgs == UNINITIALIZED) {
- throw new RuntimeException("NO_ARGS_ALLOWED");
- }
- processValue(value);
+ public boolean hasLongOpt() {
+ return longOpt != null;
+ }
+
+ /**
+ * Returns whether this Option has any values.
+ *
+ * @return whether this Option has any values.
+ */
+ private boolean hasNoValues() {
+ return values.isEmpty();
+ }
+
+ /**
+ * @return whether this Option can have an optional argument
+ */
+ public boolean hasOptionalArg() {
+ return optionalArg;
+ }
+
+ /**
+ * Return whether this Option has specified a value separator.
+ *
+ * @return whether this Option has specified a value separator.
+ * @since 1.1
+ */
+ public boolean hasValueSeparator() {
+ return valuesep > 0;
+ }
+
+ /**
+ * Query to see if this Option is mandatory
+ *
+ * @return boolean flag indicating whether this Option is mandatory
+ */
+ public boolean isRequired() {
+ return required;
}
/**
@@ -439,71 +748,107 @@ public class Option implements Cloneable, Serializable {
}
/**
- * Add the value to this Option. If the number of arguments is greater than zero and there is enough space in the list
- * then add the value. Otherwise, throw a runtime exception.
- *
- * @param value The value to be added to this Option
+ * Tells if the option requires more arguments to be valid.
*
- * @since 1.0.1
+ * @return false if the option doesn't require more arguments
+ * @since 1.3
*/
- private void add(final String value) {
- if (!acceptsArg()) {
- throw new RuntimeException("Cannot add value, list full.");
+ boolean requiresArg() {
+ if (optionalArg) {
+ return false;
}
-
- // store value
- values.add(value);
+ if (numberOfArgs == UNLIMITED_VALUES) {
+ return values.isEmpty();
+ }
+ return acceptsArg();
}
/**
- * Returns the specified value of this Option or <code>null</code> if there is no value.
+ * Sets the display name for the argument value.
*
- * @return the value/first value of this Option or <code>null</code> if there is no value.
+ * @param argName the display name for the argument value.
*/
- public String getValue() {
- return hasNoValues() ? null : values.get(0);
+ public void setArgName(final String argName) {
+ this.argName = argName;
}
/**
- * Returns the specified value of this Option or <code>null</code> if there is no value.
+ * Sets the number of argument values this Option can take.
*
- * @param index The index of the value to be returned.
+ * @param num the number of argument values
+ */
+ public void setArgs(final int num) {
+ this.numberOfArgs = num;
+ }
+
+ /**
+ * Sets the self-documenting description of this Option
*
- * @return the specified value of this Option or <code>null</code> if there is no value.
+ * @param description The description of this option
+ * @since 1.1
+ */
+ public void setDescription(final String description) {
+ this.description = description;
+ }
+
+ /**
+ * Sets the long name of this Option.
*
- * @throws IndexOutOfBoundsException if index is less than 1 or greater than the number of the values for this Option.
+ * @param longOpt the long name of this Option
*/
- public String getValue(final int index) throws IndexOutOfBoundsException {
- return hasNoValues() ? null : values.get(index);
+ public void setLongOpt(final String longOpt) {
+ this.longOpt = longOpt;
}
/**
- * Returns the value/first value of this Option or the <code>defaultValue</code> if there is no value.
+ * Sets whether this Option can have an optional argument.
*
- * @param defaultValue The value to be returned if there is no value.
+ * @param optionalArg specifies whether the Option can have an optional argument.
+ */
+ public void setOptionalArg(final boolean optionalArg) {
+ this.optionalArg = optionalArg;
+ }
+
+ /**
+ * Sets whether this Option is mandatory.
*
- * @return the value/first value of this Option or the <code>defaultValue</code> if there are no values.
+ * @param required specifies whether this Option is mandatory
*/
- public String getValue(final String defaultValue) {
- final String value = getValue();
+ public void setRequired(final boolean required) {
+ this.required = required;
+ }
- return (value != null) ? value : defaultValue;
+ /**
+ * Sets the type of this Option.
+ *
+ * @param type the type of this Option
+ * @since 1.3
+ */
+ public void setType(final Class<?> type) {
+ this.type = type;
}
/**
- * Return the values of this Option as a String array or null if there are no values
+ * Sets the type of this Option.
+ * <p>
+ * <b>Note:</b> this method is kept for binary compatibility and the input type is supposed to be a {@link Class}
+ * object.
*
- * @return the values of this Option as a String array or null if there are no values
+ * @param type the type of this Option
+ * @deprecated since 1.3, use {@link #setType(Class)} instead
*/
- public String[] getValues() {
- return hasNoValues() ? null : values.toArray(new String[values.size()]);
+ @Deprecated
+ public void setType(final Object type) {
+ setType((Class<?>) type);
}
/**
- * @return the values of this Option as a List or null if there are no values
+ * Sets the value separator. For example if the argument value was a Java property, the value separator would be '='.
+ *
+ * @param sep The value separator.
*/
- public List<String> getValuesList() {
- return values;
+ public void setValueSeparator(final char sep) {
+ this.valuesep = sep;
}
/**
@@ -539,349 +884,4 @@ public class Option implements Cloneable, Serializable {
return buf.toString();
}
-
- /**
- * Returns whether this Option has any values.
- *
- * @return whether this Option has any values.
- */
- private boolean hasNoValues() {
- return values.isEmpty();
- }
-
- @Override
- public boolean equals(final Object o) {
- if (this == o) {
- return true;
- }
- if (o == null || getClass() != o.getClass()) {
- return false;
- }
-
- final Option option = (Option) o;
-
- if (opt != null ? !opt.equals(option.opt) : option.opt != null) {
- return false;
- }
- if (longOpt != null ? !longOpt.equals(option.longOpt) : option.longOpt != null) {
- return false;
- }
-
- return true;
- }
-
- @Override
- public int hashCode() {
- int result;
- result = opt != null ? opt.hashCode() : 0;
- result = 31 * result + (longOpt != null ? longOpt.hashCode() : 0);
- return result;
- }
-
- /**
- * A rather odd clone method - due to incorrect code in 1.0 it is public and in 1.1 rather than throwing a
- * CloneNotSupportedException it throws a RuntimeException so as to maintain backwards compat at the API level.
- *
- * After calling this method, it is very likely you will want to call clearValues().
- *
- * @return a clone of this Option instance
- * @throws RuntimeException if a {@link CloneNotSupportedException} has been thrown by {@code super.clone()}
- */
- @Override
- public Object clone() {
- try {
- final Option option = (Option) super.clone();
- option.values = new ArrayList<>(values);
- return option;
- } catch (final CloneNotSupportedException cnse) {
- throw new RuntimeException("A CloneNotSupportedException was thrown: " + cnse.getMessage());
- }
- }
-
- /**
- * Clear the Option values. After a parse is complete, these are left with data in them and they need clearing if
- * another parse is done.
- *
- * See: <a href="https://issues.apache.org/jira/browse/CLI-71">CLI-71</a>
- */
- void clearValues() {
- values.clear();
- }
-
- /**
- * This method is not intended to be used. It was a piece of internal API that was made public in 1.0. It currently
- * throws an UnsupportedOperationException.
- *
- * @param value the value to add
- * @return always throws an {@link UnsupportedOperationException}
- * @throws UnsupportedOperationException always
- * @deprecated
- */
- @Deprecated
- public boolean addValue(final String value) {
- throw new UnsupportedOperationException(
- "The addValue method is not intended for client use. " + "Subclasses should use the addValueForProcessing method instead. ");
- }
-
- /**
- * Tells if the option can accept more arguments.
- *
- * @return false if the maximum number of arguments is reached
- * @since 1.3
- */
- boolean acceptsArg() {
- return (hasArg() || hasArgs() || hasOptionalArg()) && (numberOfArgs <= 0 || values.size() < numberOfArgs);
- }
-
- /**
- * Tells if the option requires more arguments to be valid.
- *
- * @return false if the option doesn't require more arguments
- * @since 1.3
- */
- boolean requiresArg() {
- if (optionalArg) {
- return false;
- }
- if (numberOfArgs == UNLIMITED_VALUES) {
- return values.isEmpty();
- }
- return acceptsArg();
- }
-
- /**
- * Returns a {@link Builder} to create an {@link Option} using descriptive methods.
- *
- * @return a new {@link Builder} instance
- * @since 1.3
- */
- public static Builder builder() {
- return builder(null);
- }
-
- /**
- * Returns a {@link Builder} to create an {@link Option} using descriptive methods.
- *
- * @param opt short representation of the option
- * @return a new {@link Builder} instance
- * @throws IllegalArgumentException if there are any non valid Option characters in {@code opt}
- * @since 1.3
- */
- public static Builder builder(final String opt) {
- return new Builder(opt);
- }
-
- /**
- * A nested builder class to create <code>Option</code> instances using descriptive methods.
- * <p>
- * Example usage:
- *
- * <pre>
- * Option option = Option.builder("a").required(true).longOpt("arg-name").build();
- * </pre>
- *
- * @since 1.3
- */
- public static final class Builder {
- /** the name of the option */
- private final String opt;
-
- /** description of the option */
- private String description;
-
- /** the long representation of the option */
- private String longOpt;
-
- /** the name of the argument for this option */
- private String argName;
-
- /** specifies whether this option is required to be present */
- private boolean required;
-
- /** specifies whether the argument value of this Option is optional */
- private boolean optionalArg;
-
- /** the number of argument values this option can have */
- private int numberOfArgs = UNINITIALIZED;
-
- /** the type of this Option */
- private Class<?> type = String.class;
-
- /** the character that is the value separator */
- private char valuesep;
-
- /**
- * Constructs a new <code>Builder</code> with the minimum required parameters for an <code>Option</code> instance.
- *
- * @param opt short representation of the option
- * @throws IllegalArgumentException if there are any non valid Option characters in {@code opt}
- */
- private Builder(final String opt) throws IllegalArgumentException {
- OptionValidator.validateOption(opt);
- this.opt = opt;
- }
-
- /**
- * Sets the display name for the argument value.
- *
- * @param argName the display name for the argument value.
- * @return this builder, to allow method chaining
- */
- public Builder argName(final String argName) {
- this.argName = argName;
- return this;
- }
-
- /**
- * Sets the description for this option.
- *
- * @param description the description of the option.
- * @return this builder, to allow method chaining
- */
- public Builder desc(final String description) {
- this.description = description;
- return this;
- }
-
- /**
- * Sets the long name of the Option.
- *
- * @param longOpt the long name of the Option
- * @return this builder, to allow method chaining
- */
- public Builder longOpt(final String longOpt) {
- this.longOpt = longOpt;
- return this;
- }
-
- /**
- * Sets the number of argument values the Option can take.
- *
- * @param numberOfArgs the number of argument values
- * @return this builder, to allow method chaining
- */
- public Builder numberOfArgs(final int numberOfArgs) {
- this.numberOfArgs = numberOfArgs;
- return this;
- }
-
- /**
- * Sets whether the Option can have an optional argument.
- *
- * @param isOptional specifies whether the Option can have an optional argument.
- * @return this builder, to allow method chaining
- */
- public Builder optionalArg(final boolean isOptional) {
- this.optionalArg = isOptional;
- return this;
- }
-
- /**
- * Marks this Option as required.
- *
- * @return this builder, to allow method chaining
- */
- public Builder required() {
- return required(true);
- }
-
- /**
- * Sets whether the Option is mandatory.
- *
- * @param required specifies whether the Option is mandatory
- * @return this builder, to allow method chaining
- */
- public Builder required(final boolean required) {
- this.required = required;
- return this;
- }
-
- /**
- * Sets the type of the Option.
- *
- * @param type the type of the Option
- * @return this builder, to allow method chaining
- */
- public Builder type(final Class<?> type) {
- this.type = type;
- return this;
- }
-
- /**
- * The Option will use '=' as a means to separate argument value.
- *
- * @return this builder, to allow method chaining
- */
- public Builder valueSeparator() {
- return valueSeparator('=');
- }
-
- /**
- * The Option will use <code>sep</code> as a means to separate argument values.
- * <p>
- * <b>Example:</b>
- *
- * <pre>
- * Option opt = Option.builder("D").hasArgs().valueSeparator('=').build();
- * Options options = new Options();
- * options.addOption(opt);
- * String[] args = {"-Dkey=value"};
- * CommandLineParser parser = new DefaultParser();
- * CommandLine line = parser.parse(options, args);
- * String propertyName = line.getOptionValues("D")[0]; // will be "key"
- * String propertyValue = line.getOptionValues("D")[1]; // will be "value"
- * </pre>
- *
- * @param sep The value separator.
- * @return this builder, to allow method chaining
- */
- public Builder valueSeparator(final char sep) {
- valuesep = sep;
- return this;
- }
-
- /**
- * Indicates that the Option will require an argument.
- *
- * @return this builder, to allow method chaining
- */
- public Builder hasArg() {
- return hasArg(true);
- }
-
- /**
- * Indicates if the Option has an argument or not.
- *
- * @param hasArg specifies whether the Option takes an argument or not
- * @return this builder, to allow method chaining
- */
- public Builder hasArg(final boolean hasArg) {
- // set to UNINITIALIZED when no arg is specified to be compatible with OptionBuilder
- numberOfArgs = hasArg ? 1 : Option.UNINITIALIZED;
- return this;
- }
-
- /**
- * Indicates that the Option can have unlimited argument values.
- *
- * @return this builder, to allow method chaining
- */
- public Builder hasArgs() {
- numberOfArgs = Option.UNLIMITED_VALUES;
- return this;
- }
-
- /**
- * Constructs an Option with the values declared by this {@link Builder}.
- *
- * @return the new {@link Option}
- * @throws IllegalArgumentException if neither {@code opt} or {@code longOpt} has been set
- */
- public Option build() {
- if (opt == null && longOpt == null) {
- throw new IllegalArgumentException("Either opt or longOpt must be specified");
- }
- return new Option(this);
- }
- }
}
diff --git a/src/main/java/org/apache/commons/cli/OptionBuilder.java b/src/main/java/org/apache/commons/cli/OptionBuilder.java
index 7bcab4f..b6ee9df 100644
--- a/src/main/java/org/apache/commons/cli/OptionBuilder.java
+++ b/src/main/java/org/apache/commons/cli/OptionBuilder.java
@@ -63,36 +63,59 @@ public final class OptionBuilder {
}
/**
- * private constructor to prevent instances being created
+ * Create an Option using the current settings
+ *
+ * @return the Option instance
+ * @throws IllegalArgumentException if <code>longOpt</code> has not been set.
*/
- private OptionBuilder() {
- // hide the constructor
+ public static Option create() throws IllegalArgumentException {
+ if (longopt == null) {
+ OptionBuilder.reset();
+ throw new IllegalArgumentException("must specify longopt");
+ }
+
+ return create(null);
}
/**
- * Resets the member variables to their default values.
+ * Create an Option using the current settings and with the specified Option <code>char</code>.
+ *
+ * @param opt the character representation of the Option
+ * @return the Option instance
+ * @throws IllegalArgumentException if <code>opt</code> is not a valid character. See Option.
*/
- private static void reset() {
- description = null;
- argName = null;
- longopt = null;
- type = String.class;
- required = false;
- numberOfArgs = Option.UNINITIALIZED;
- optionalArg = false;
- valuesep = (char) 0;
+ public static Option create(final char opt) throws IllegalArgumentException {
+ return create(String.valueOf(opt));
}
/**
- * The next Option created will have the following long option value.
+ * Create an Option using the current settings and with the specified Option <code>char</code>.
*
- * @param newLongopt the long option value
- * @return the OptionBuilder instance
+ * @param opt the <code>java.lang.String</code> representation of the Option
+ * @return the Option instance
+ * @throws IllegalArgumentException if <code>opt</code> is not a valid character. See Option.
*/
- public static OptionBuilder withLongOpt(final String newLongopt) {
- OptionBuilder.longopt = newLongopt;
+ public static Option create(final String opt) throws IllegalArgumentException {
+ Option option = null;
+ try {
+ // create the option
+ option = new Option(opt, description);
- return INSTANCE;
+ // set the option properties
+ option.setLongOpt(longopt);
+ option.setRequired(required);
+ option.setOptionalArg(optionalArg);
+ option.setArgs(numberOfArgs);
+ option.setType(type);
+ option.setValueSeparator(valuesep);
+ option.setArgName(argName);
+ } finally {
+ // reset the OptionBuilder properties
+ OptionBuilder.reset();
+ }
+
+ // return the Option instance
+ return option;
}
/**
@@ -119,69 +142,72 @@ public final class OptionBuilder {
}
/**
- * The next Option created will have the specified argument value name.
+ * The next Option created can have unlimited argument values.
*
- * @param name the name for the argument value
* @return the OptionBuilder instance
*/
- public static OptionBuilder withArgName(final String name) {
- OptionBuilder.argName = name;
+ public static OptionBuilder hasArgs() {
+ OptionBuilder.numberOfArgs = Option.UNLIMITED_VALUES;
return INSTANCE;
}
/**
- * The next Option created will be required.
+ * The next Option created can have <code>num</code> argument values.
*
+ * @param num the number of args that the option can have
* @return the OptionBuilder instance
*/
- public static OptionBuilder isRequired() {
- OptionBuilder.required = true;
+ public static OptionBuilder hasArgs(final int num) {
+ OptionBuilder.numberOfArgs = num;
return INSTANCE;
}
/**
- * The next Option created uses <code>sep</code> as a means to separate argument values.
- * <p>
- * <b>Example:</b>
- *
- * <pre>
- * Option opt = OptionBuilder.withValueSeparator('=').create('D');
- *
- * String args = "-Dkey=value";
- * CommandLine line = parser.parse(args);
- * String propertyName = opt.getValue(0); // will be "key"
- * String propertyValue = opt.getValue(1); // will be "value"
- * </pre>
- *
- * @param sep The value separator to be used for the argument values.
+ * The next Option can have an optional argument.
*
* @return the OptionBuilder instance
*/
- public static OptionBuilder withValueSeparator(final char sep) {
- OptionBuilder.valuesep = sep;
+ public static OptionBuilder hasOptionalArg() {
+ OptionBuilder.numberOfArgs = 1;
+ OptionBuilder.optionalArg = true;
return INSTANCE;
}
/**
- * The next Option created uses '<code>=</code>' as a means to separate argument values.
- *
- * <b>Example:</b>
+ * The next Option can have an unlimited number of optional arguments.
*
- * <pre>
- * Option opt = OptionBuilder.withValueSeparator().create('D');
+ * @return the OptionBuilder instance
+ */
+ public static OptionBuilder hasOptionalArgs() {
+ OptionBuilder.numberOfArgs = Option.UNLIMITED_VALUES;
+ OptionBuilder.optionalArg = true;
+
+ return INSTANCE;
+ }
+
+ /**
+ * The next Option can have the specified number of optional arguments.
*
- * CommandLine line = parser.parse(args);
- * String propertyName = opt.getValue(0);
- * String propertyValue = opt.getValue(1);
- * </pre>
+ * @param numArgs - the maximum number of optional arguments the next Option created can have.
+ * @return the OptionBuilder instance
+ */
+ public static OptionBuilder hasOptionalArgs(final int numArgs) {
+ OptionBuilder.numberOfArgs = numArgs;
+ OptionBuilder.optionalArg = true;
+
+ return INSTANCE;
+ }
+
+ /**
+ * The next Option created will be required.
*
* @return the OptionBuilder instance
*/
- public static OptionBuilder withValueSeparator() {
- OptionBuilder.valuesep = '=';
+ public static OptionBuilder isRequired() {
+ OptionBuilder.required = true;
return INSTANCE;
}
@@ -199,61 +225,64 @@ public final class OptionBuilder {
}
/**
- * The next Option created can have unlimited argument values.
- *
- * @return the OptionBuilder instance
+ * Resets the member variables to their default values.
*/
- public static OptionBuilder hasArgs() {
- OptionBuilder.numberOfArgs = Option.UNLIMITED_VALUES;
-
- return INSTANCE;
+ private static void reset() {
+ description = null;
+ argName = null;
+ longopt = null;
+ type = String.class;
+ required = false;
+ numberOfArgs = Option.UNINITIALIZED;
+ optionalArg = false;
+ valuesep = (char) 0;
}
/**
- * The next Option created can have <code>num</code> argument values.
+ * The next Option created will have the specified argument value name.
*
- * @param num the number of args that the option can have
+ * @param name the name for the argument value
* @return the OptionBuilder instance
*/
- public static OptionBuilder hasArgs(final int num) {
- OptionBuilder.numberOfArgs = num;
+ public static OptionBuilder withArgName(final String name) {
+ OptionBuilder.argName = name;
return INSTANCE;
}
/**
- * The next Option can have an optional argument.
+ * The next Option created will have the specified description
*
+ * @param newDescription a description of the Option's purpose
* @return the OptionBuilder instance
*/
- public static OptionBuilder hasOptionalArg() {
- OptionBuilder.numberOfArgs = 1;
- OptionBuilder.optionalArg = true;
+ public static OptionBuilder withDescription(final String newDescription) {
+ OptionBuilder.description = newDescription;
return INSTANCE;
}
/**
- * The next Option can have an unlimited number of optional arguments.
+ * The next Option created will have the following long option value.
*
+ * @param newLongopt the long option value
* @return the OptionBuilder instance
*/
- public static OptionBuilder hasOptionalArgs() {
- OptionBuilder.numberOfArgs = Option.UNLIMITED_VALUES;
- OptionBuilder.optionalArg = true;
+ public static OptionBuilder withLongOpt(final String newLongopt) {
+ OptionBuilder.longopt = newLongopt;
return INSTANCE;
}
/**
- * The next Option can have the specified number of optional arguments.
+ * The next Option created will have a value that will be an instance of <code>type</code>.
*
- * @param numArgs - the maximum number of optional arguments the next Option created can have.
+ * @param newType the type of the Options argument value
* @return the OptionBuilder instance
+ * @since 1.3
*/
- public static OptionBuilder hasOptionalArgs(final int numArgs) {
- OptionBuilder.numberOfArgs = numArgs;
- OptionBuilder.optionalArg = true;
+ public static OptionBuilder withType(final Class<?> newType) {
+ OptionBuilder.type = newType;
return INSTANCE;
}
@@ -274,83 +303,54 @@ public final class OptionBuilder {
}
/**
- * The next Option created will have a value that will be an instance of <code>type</code>.
+ * The next Option created uses '<code>=</code>' as a means to separate argument values.
*
- * @param newType the type of the Options argument value
- * @return the OptionBuilder instance
- * @since 1.3
- */
- public static OptionBuilder withType(final Class<?> newType) {
- OptionBuilder.type = newType;
-
- return INSTANCE;
- }
-
- /**
- * The next Option created will have the specified description
+ * <b>Example:</b>
+ *
+ * <pre>
+ * Option opt = OptionBuilder.withValueSeparator().create('D');
+ *
+ * CommandLine line = parser.parse(args);
+ * String propertyName = opt.getValue(0);
+ * String propertyValue = opt.getValue(1);
+ * </pre>
*
- * @param newDescription a description of the Option's purpose
* @return the OptionBuilder instance
*/
- public static OptionBuilder withDescription(final String newDescription) {
- OptionBuilder.description = newDescription;
+ public static OptionBuilder withValueSeparator() {
+ OptionBuilder.valuesep = '=';
return INSTANCE;
}
/**
- * Create an Option using the current settings and with the specified Option <code>char</code>.
+ * The next Option created uses <code>sep</code> as a means to separate argument values.
+ * <p>
+ * <b>Example:</b>
*
- * @param opt the character representation of the Option
- * @return the Option instance
- * @throws IllegalArgumentException if <code>opt</code> is not a valid character. See Option.
- */
- public static Option create(final char opt) throws IllegalArgumentException {
- return create(String.valueOf(opt));
- }
-
- /**
- * Create an Option using the current settings
+ * <pre>
+ * Option opt = OptionBuilder.withValueSeparator('=').create('D');
*
- * @return the Option instance
- * @throws IllegalArgumentException if <code>longOpt</code> has not been set.
+ * String args = "-Dkey=value";
+ * CommandLine line = parser.parse(args);
+ * String propertyName = opt.getValue(0); // will be "key"
+ * String propertyValue = opt.getValue(1); // will be "value"
+ * </pre>
+ *
+ * @param sep The value separator to be used for the argument values.
+ *
+ * @return the OptionBuilder instance
*/
- public static Option create() throws IllegalArgumentException {
- if (longopt == null) {
- OptionBuilder.reset();
- throw new IllegalArgumentException("must specify longopt");
- }
+ public static OptionBuilder withValueSeparator(final char sep) {
+ OptionBuilder.valuesep = sep;
- return create(null);
+ return INSTANCE;
}
/**
- * Create an Option using the current settings and with the specified Option <code>char</code>.
- *
- * @param opt the <code>java.lang.String</code> representation of the Option
- * @return the Option instance
- * @throws IllegalArgumentException if <code>opt</code> is not a valid character. See Option.
+ * private constructor to prevent instances being created
*/
- public static Option create(final String opt) throws IllegalArgumentException {
- Option option = null;
- try {
- // create the option
- option = new Option(opt, description);
-
- // set the option properties
- option.setLongOpt(longopt);
- option.setRequired(required);
- option.setOptionalArg(optionalArg);
- option.setArgs(numberOfArgs);
- option.setType(type);
- option.setValueSeparator(valuesep);
- option.setArgName(argName);
- } finally {
- // reset the OptionBuilder properties
- OptionBuilder.reset();
- }
-
- // return the Option instance
- return option;
+ private OptionBuilder() {
+ // hide the constructor
}
}
diff --git a/src/main/java/org/apache/commons/cli/OptionGroup.java b/src/main/java/org/apache/commons/cli/OptionGroup.java
index 5bf5c8f..93ca192 100644
--- a/src/main/java/org/apache/commons/cli/OptionGroup.java
+++ b/src/main/java/org/apache/commons/cli/OptionGroup.java
@@ -70,6 +70,29 @@ public class OptionGroup implements Serializable {
}
/**
+ * @return the selected option name
+ */
+ public String getSelected() {
+ return selected;
+ }
+
+ /**
+ * Returns whether this option group is required.
+ *
+ * @return whether this option group is required
+ */
+ public boolean isRequired() {
+ return required;
+ }
+
+ /**
+ * @param required specifies if this group is required
+ */
+ public void setRequired(final boolean required) {
+ this.required = required;
+ }
+
+ /**
* Set the selected option of this group to <code>name</code>.
*
* @param option the option that is selected
@@ -92,29 +115,6 @@ public class OptionGroup implements Serializable {
}
/**
- * @return the selected option name
- */
- public String getSelected() {
- return selected;
- }
-
- /**
- * @param required specifies if this group is required
- */
- public void setRequired(final boolean required) {
- this.required = required;
- }
-
- /**
- * Returns whether this option group is required.
- *
- * @return whether this option group is required
- */
- public boolean isRequired() {
- return required;
- }
-
- /**
* Returns the stringified version of this OptionGroup.
*
* @return the stringified representation of this group
diff --git a/src/main/java/org/apache/commons/cli/OptionValidator.java b/src/main/java/org/apache/commons/cli/OptionValidator.java
index 3525378..35f9f44 100644
--- a/src/main/java/org/apache/commons/cli/OptionValidator.java
+++ b/src/main/java/org/apache/commons/cli/OptionValidator.java
@@ -24,6 +24,26 @@ package org.apache.commons.cli;
*/
final class OptionValidator {
/**
+ * Returns whether the specified character is a valid character.
+ *
+ * @param c the character to validate
+ * @return true if <code>c</code> is a letter.
+ */
+ private static boolean isValidChar(final char c) {
+ return Character.isJavaIdentifierPart(c);
+ }
+
+ /**
+ * Returns whether the specified character is a valid Option.
+ *
+ * @param c the option to validate
+ * @return true if <code>c</code> is a letter, '?' or '@', otherwise false.
+ */
+ private static boolean isValidOpt(final char c) {
+ return isValidChar(c) || c == '?' || c == '@';
+ }
+
+ /**
* Validates whether <code>opt</code> is a permissible Option shortOpt. The rules that specify if the <code>opt</code>
* is valid are:
*
@@ -61,24 +81,4 @@ final class OptionValidator {
}
}
}
-
- /**
- * Returns whether the specified character is a valid Option.
- *
- * @param c the option to validate
- * @return true if <code>c</code> is a letter, '?' or '@', otherwise false.
- */
- private static boolean isValidOpt(final char c) {
- return isValidChar(c) || c == '?' || c == '@';
- }
-
- /**
- * Returns whether the specified character is a valid character.
- *
- * @param c the character to validate
- * @return true if <code>c</code> is a letter.
- */
- private static boolean isValidChar(final char c) {
- return Character.isJavaIdentifierPart(c);
- }
}
diff --git a/src/main/java/org/apache/commons/cli/Options.java b/src/main/java/org/apache/commons/cli/Options.java
index 5b86571..e4ccb70 100644
--- a/src/main/java/org/apache/commons/cli/Options.java
+++ b/src/main/java/org/apache/commons/cli/Options.java
@@ -55,36 +55,47 @@ public class Options implements Serializable {
private final Map<String, OptionGroup> optionGroups = new LinkedHashMap<>();
/**
- * Add the specified option group.
+ * Adds an option instance
*
- * @param group the OptionGroup that is to be added
+ * @param opt the option that is to be added
* @return the resulting Options instance
*/
- public Options addOptionGroup(final OptionGroup group) {
- if (group.isRequired()) {
- requiredOpts.add(group);
- }
+ public Options addOption(final Option opt) {
+ final String key = opt.getKey();
- for (final Option option : group.getOptions()) {
- // an Option cannot be required if it is in an
- // OptionGroup, either the group is required or
- // nothing is required
- option.setRequired(false);
- addOption(option);
+ // add it to the long option list
+ if (opt.hasLongOpt()) {
+ longOpts.put(opt.getLongOpt(), opt);
+ }
- optionGroups.put(option.getKey(), group);
+ // if the option is required add it to the required list
+ if (opt.isRequired()) {
+ if (requiredOpts.contains(key)) {
+ requiredOpts.remove(requiredOpts.indexOf(key));
+ }
+ requiredOpts.add(key);
}
+ shortOpts.put(key, opt);
+
return this;
}
/**
- * Lists the OptionGroups that are members of this Options instance.
+ * Add an option that only contains a short-name.
*
- * @return a Collection of OptionGroup instances.
+ * <p>
+ * It may be specified as requiring an argument.
+ * </p>
+ *
+ * @param opt Short single-character name of the option.
+ * @param hasArg flag signalling if an argument is required after this option
+ * @param description Self-documenting description
+ * @return the resulting Options instance
*/
- Collection<OptionGroup> getOptionGroups() {
- return new HashSet<>(optionGroups.values());
+ public Options addOption(final String opt, final boolean hasArg, final String description) {
+ addOption(opt, null, hasArg, description);
+ return this;
}
/**
@@ -105,37 +116,44 @@ public class Options implements Serializable {
}
/**
- * Add an option that only contains a short-name.
+ * Add an option that contains a short-name and a long-name.
*
* <p>
* It may be specified as requiring an argument.
* </p>
*
* @param opt Short single-character name of the option.
+ * @param longOpt Long multi-character name of the option.
* @param hasArg flag signalling if an argument is required after this option
* @param description Self-documenting description
* @return the resulting Options instance
*/
- public Options addOption(final String opt, final boolean hasArg, final String description) {
- addOption(opt, null, hasArg, description);
+ public Options addOption(final String opt, final String longOpt, final boolean hasArg, final String description) {
+ addOption(new Option(opt, longOpt, hasArg, description));
return this;
}
/**
- * Add an option that contains a short-name and a long-name.
- *
- * <p>
- * It may be specified as requiring an argument.
- * </p>
+ * Add the specified option group.
*
- * @param opt Short single-character name of the option.
- * @param longOpt Long multi-character name of the option.
- * @param hasArg flag signalling if an argument is required after this option
- * @param description Self-documenting description
+ * @param group the OptionGroup that is to be added
* @return the resulting Options instance
*/
- public Options addOption(final String opt, final String longOpt, final boolean hasArg, final String description) {
- addOption(new Option(opt, longOpt, hasArg, description));
+ public Options addOptionGroup(final OptionGroup group) {
+ if (group.isRequired()) {
+ requiredOpts.add(group);
+ }
+
+ for (final Option option : group.getOptions()) {
+ // an Option cannot be required if it is in an
+ // OptionGroup, either the group is required or
+ // nothing is required
+ option.setRequired(false);
+ addOption(option);
+
+ optionGroups.put(option.getKey(), group);
+ }
+
return this;
}
@@ -169,57 +187,29 @@ public class Options implements Serializable {
}
/**
- * Adds an option instance
+ * Returns the options with a long name starting with the name specified.
*
- * @param opt the option that is to be added
- * @return the resulting Options instance
+ * @param opt the partial name of the option
+ * @return the options matching the partial name specified, or an empty list if none matches
+ * @since 1.3
*/
- public Options addOption(final Option opt) {
- final String key = opt.getKey();
+ public List<String> getMatchingOptions(String opt) {
+ opt = Util.stripLeadingHyphens(opt);
- // add it to the long option list
- if (opt.hasLongOpt()) {
- longOpts.put(opt.getLongOpt(), opt);
+ final List<String> matchingOpts = new ArrayList<>();
+
+ // for a perfect match return the single option only
+ if (longOpts.containsKey(opt)) {
+ return Collections.singletonList(opt);
}
- // if the option is required add it to the required list
- if (opt.isRequired()) {
- if (requiredOpts.contains(key)) {
- requiredOpts.remove(requiredOpts.indexOf(key));
+ for (final String longOpt : longOpts.keySet()) {
+ if (longOpt.startsWith(opt)) {
+ matchingOpts.add(longOpt);
}
- requiredOpts.add(key);
}
- shortOpts.put(key, opt);
-
- return this;
- }
-
- /**
- * Retrieve a read-only list of options in this set
- *
- * @return read-only Collection of {@link Option} objects in this descriptor
- */
- public Collection<Option> getOptions() {
- return Collections.unmodifiableCollection(helpOptions());
- }
-
- /**
- * Returns the Options for use by the HelpFormatter.
- *
- * @return the List of Options
- */
- List<Option> helpOptions() {
- return new ArrayList<>(shortOpts.values());
- }
-
- /**
- * Returns the required options.
- *
- * @return read-only List of required options
- */
- public List getRequiredOptions() {
- return Collections.unmodifiableList(requiredOpts);
+ return matchingOpts;
}
/**
@@ -243,54 +233,65 @@ public class Options implements Serializable {
}
/**
- * Returns the options with a long name starting with the name specified.
+ * Returns the OptionGroup the <code>opt</code> belongs to.
*
- * @param opt the partial name of the option
- * @return the options matching the partial name specified, or an empty list if none matches
- * @since 1.3
+ * @param opt the option whose OptionGroup is being queried.
+ * @return the OptionGroup if <code>opt</code> is part of an OptionGroup, otherwise return null
*/
- public List<String> getMatchingOptions(String opt) {
- opt = Util.stripLeadingHyphens(opt);
-
- final List<String> matchingOpts = new ArrayList<>();
+ public OptionGroup getOptionGroup(final Option opt) {
+ return optionGroups.get(opt.getKey());
+ }
- // for a perfect match return the single option only
- if (longOpts.containsKey(opt)) {
- return Collections.singletonList(opt);
- }
+ /**
+ * Lists the OptionGroups that are members of this Options instance.
+ *
+ * @return a Collection of OptionGroup instances.
+ */
+ Collection<OptionGroup> getOptionGroups() {
+ return new HashSet<>(optionGroups.values());
+ }
- for (final String longOpt : longOpts.keySet()) {
- if (longOpt.startsWith(opt)) {
- matchingOpts.add(longOpt);
- }
- }
+ /**
+ * Retrieve a read-only list of options in this set
+ *
+ * @return read-only Collection of {@link Option} objects in this descriptor
+ */
+ public Collection<Option> getOptions() {
+ return Collections.unmodifiableCollection(helpOptions());
+ }
- return matchingOpts;
+ /**
+ * Returns the required options.
+ *
+ * @return read-only List of required options
+ */
+ public List getRequiredOptions() {
+ return Collections.unmodifiableList(requiredOpts);
}
/**
* Returns whether the named {@link Option} is a member of this {@link Options}.
*
- * @param opt short or long name of the {@link Option}
+ * @param opt long name of the {@link Option}
* @return true if the named {@link Option} is a member of this {@link Options}
+ * @since 1.3
*/
- public boolean hasOption(String opt) {
+ public boolean hasLongOption(String opt) {
opt = Util.stripLeadingHyphens(opt);
- return shortOpts.containsKey(opt) || longOpts.containsKey(opt);
+ return longOpts.containsKey(opt);
}
/**
* Returns whether the named {@link Option} is a member of this {@link Options}.
*
- * @param opt long name of the {@link Option}
+ * @param opt short or long name of the {@link Option}
* @return true if the named {@link Option} is a member of this {@link Options}
- * @since 1.3
*/
- public boolean hasLongOption(String opt) {
+ public boolean hasOption(String opt) {
opt = Util.stripLeadingHyphens(opt);
- return longOpts.containsKey(opt);
+ return shortOpts.containsKey(opt) || longOpts.containsKey(opt);
}
/**
@@ -307,13 +308,12 @@ public class Options implements Serializable {
}
/**
- * Returns the OptionGroup the <code>opt</code> belongs to.
+ * Returns the Options for use by the HelpFormatter.
*
- * @param opt the option whose OptionGroup is being queried.
- * @return the OptionGroup if <code>opt</code> is part of an OptionGroup, otherwise return null
+ * @return the List of Options
*/
- public OptionGroup getOptionGroup(final Option opt) {
- return optionGroups.get(opt.getKey());
+ List<Option> helpOptions() {
+ return new ArrayList<>(shortOpts.values());
}
/**
diff --git a/src/main/java/org/apache/commons/cli/Parser.java b/src/main/java/org/apache/commons/cli/Parser.java
index cf16848..4c1664e 100644
--- a/src/main/java/org/apache/commons/cli/Parser.java
+++ b/src/main/java/org/apache/commons/cli/Parser.java
@@ -40,17 +40,16 @@ public abstract class Parser implements CommandLineParser {
/** list of required options strings */
private List requiredOptions;
- protected void setOptions(final Options options) {
- this.options = options;
- this.requiredOptions = new ArrayList(options.getRequiredOptions());
- }
-
- protected Options getOptions() {
- return options;
- }
-
- protected List getRequiredOptions() {
- return requiredOptions;
+ /**
+ * Throws a {@link MissingOptionException} if all of the required options are not present.
+ *
+ * @throws MissingOptionException if any of the required Options are not present.
+ */
+ protected void checkRequiredOptions() throws MissingOptionException {
+ // if there are required options that have not been processed
+ if (!getRequiredOptions().isEmpty()) {
+ throw new MissingOptionException(getRequiredOptions());
+ }
}
/**
@@ -64,6 +63,14 @@ public abstract class Parser implements CommandLineParser {
*/
protected abstract String[] flatten(Options opts, String[] arguments, boolean stopAtNonOption) throws ParseException;
+ protected Options getOptions() {
+ return options;
+ }
+
+ protected List getRequiredOptions() {
+ return requiredOptions;
+ }
+
/**
* Parses the specified <code>arguments</code> based on the specified {@link Options}.
*
@@ -78,21 +85,6 @@ public abstract class Parser implements CommandLineParser {
}
/**
- * Parse the arguments according to the specified options and properties.
- *
- * @param options the specified Options
- * @param arguments the command line arguments
- * @param properties command line option name-value pairs
- * @return the list of atomic option and value tokens
- * @throws ParseException if there are any problems encountered while parsing the command line tokens.
- *
- * @since 1.1
- */
- public CommandLine parse(final Options options, final String[] arguments, final Properties properties) throws ParseException {
- return parse(options, arguments, properties, false);
- }
-
- /**
* Parses the specified <code>arguments</code> based on the specified {@link Options}.
*
* @param options the <code>Options</code>
@@ -114,6 +106,21 @@ public abstract class Parser implements CommandLineParser {
* @param options the specified Options
* @param arguments the command line arguments
* @param properties command line option name-value pairs
+ * @return the list of atomic option and value tokens
+ * @throws ParseException if there are any problems encountered while parsing the command line tokens.
+ *
+ * @since 1.1
+ */
+ public CommandLine parse(final Options options, final String[] arguments, final Properties properties) throws ParseException {
+ return parse(options, arguments, properties, false);
+ }
+
+ /**
+ * Parse the arguments according to the specified options and properties.
+ *
+ * @param options the specified Options
+ * @param arguments the command line arguments
+ * @param properties command line option name-value pairs
* @param stopAtNonOption if <code>true</code> an unrecognized argument stops the parsing and the remaining arguments
* are added to the {@link CommandLine}s args list. If <code>false</code> an unrecognized argument triggers a
* ParseException.
@@ -207,66 +214,6 @@ public abstract class Parser implements CommandLineParser {
}
/**
- * Sets the values of Options using the values in <code>properties</code>.
- *
- * @param properties The value properties to be processed.
- * @throws ParseException if there are any problems encountered while processing the properties.
- */
- protected void processProperties(final Properties properties) throws ParseException {
- if (properties == null) {
- return;
- }
-
- for (final Enumeration<?> e = properties.propertyNames(); e.hasMoreElements();) {
- final String option = e.nextElement().toString();
-
- final Option opt = options.getOption(option);
- if (opt == null) {
- throw new UnrecognizedOptionException("Default option wasn't defined", option);
- }
-
- // if the option is part of a group, check if another option of the group has been selected
- final OptionGroup group = options.getOptionGroup(opt);
- final boolean selected = group != null && group.getSelected() != null;
-
- if (!cmd.hasOption(option) && !selected) {
- // get the value from the properties instance
- final String value = properties.getProperty(option);
-
- if (opt.hasArg()) {
- if (opt.getValues() == null || opt.getValues().length == 0) {
- try {
- opt.addValueForProcessing(value);
- } catch (final RuntimeException exp) // NOPMD
- {
- // if we cannot add the value don't worry about it
- }
- }
- } else if (!("yes".equalsIgnoreCase(value) || "true".equalsIgnoreCase(value) || "1".equalsIgnoreCase(value))) {
- // if the value is not yes, true or 1 then don't add the
- // option to the CommandLine
- continue;
- }
-
- cmd.addOption(opt);
- updateRequiredOptions(opt);
- }
- }
- }
-
- /**
- * Throws a {@link MissingOptionException} if all of the required options are not present.
- *
- * @throws MissingOptionException if any of the required Options are not present.
- */
- protected void checkRequiredOptions() throws MissingOptionException {
- // if there are required options that have not been processed
- if (!getRequiredOptions().isEmpty()) {
- throw new MissingOptionException(getRequiredOptions());
- }
- }
-
- /**
* Process the argument values for the specified Option <code>opt</code> using the values retrieved from the specified
* iterator <code>iter</code>.
*
@@ -333,6 +280,59 @@ public abstract class Parser implements CommandLineParser {
}
/**
+ * Sets the values of Options using the values in <code>properties</code>.
+ *
+ * @param properties The value properties to be processed.
+ * @throws ParseException if there are any problems encountered while processing the properties.
+ */
+ protected void processProperties(final Properties properties) throws ParseException {
+ if (properties == null) {
+ return;
+ }
+
+ for (final Enumeration<?> e = properties.propertyNames(); e.hasMoreElements();) {
+ final String option = e.nextElement().toString();
+
+ final Option opt = options.getOption(option);
+ if (opt == null) {
+ throw new UnrecognizedOptionException("Default option wasn't defined", option);
+ }
+
+ // if the option is part of a group, check if another option of the group has been selected
+ final OptionGroup group = options.getOptionGroup(opt);
+ final boolean selected = group != null && group.getSelected() != null;
+
+ if (!cmd.hasOption(option) && !selected) {
+ // get the value from the properties instance
+ final String value = properties.getProperty(option);
+
+ if (opt.hasArg()) {
+ if (opt.getValues() == null || opt.getValues().length == 0) {
+ try {
+ opt.addValueForProcessing(value);
+ } catch (final RuntimeException exp) // NOPMD
+ {
+ // if we cannot add the value don't worry about it
+ }
+ }
+ } else if (!("yes".equalsIgnoreCase(value) || "true".equalsIgnoreCase(value) || "1".equalsIgnoreCase(value))) {
+ // if the value is not yes, true or 1 then don't add the
+ // option to the CommandLine
+ continue;
+ }
+
+ cmd.addOption(opt);
+ updateRequiredOptions(opt);
+ }
+ }
+ }
+
+ protected void setOptions(final Options options) {
+ this.options = options;
+ this.requiredOptions = new ArrayList(options.getRequiredOptions());
+ }
+
+ /**
* Removes the option or its group from the list of expected elements.
*
* @param opt
diff --git a/src/main/java/org/apache/commons/cli/PosixParser.java b/src/main/java/org/apache/commons/cli/PosixParser.java
index a1bcb43..8dd736f 100644
--- a/src/main/java/org/apache/commons/cli/PosixParser.java
+++ b/src/main/java/org/apache/commons/cli/PosixParser.java
@@ -43,12 +43,46 @@ public class PosixParser extends Parser {
private Options options;
/**
- * Resets the members to their original state i.e. remove all of <code>tokens</code> entries and set
- * <code>eatTheRest</code> to false.
+ * Breaks <code>token</code> into its constituent parts using the following algorithm.
+ *
+ * <ul>
+ * <li>ignore the first character ("<b>-</b>")</li>
+ * <li>for each remaining character check if an {@link Option} exists with that id.</li>
+ * <li>if an {@link Option} does exist then add that character prepended with "<b>-</b>" to the list of processed
+ * tokens.</li>
+ * <li>if the {@link Option} can have an argument value and there are remaining characters in the token then add the
+ * remaining characters as a token to the list of processed tokens.</li>
+ * <li>if an {@link Option} does <b>NOT</b> exist <b>AND</b> <code>stopAtNonOption</code> <b>IS</b> set then add the
+ * special token "<b>--</b>" followed by the remaining characters and also the remaining tokens directly to the
+ * processed tokens list.</li>
+ * <li>if an {@link Option} does <b>NOT</b> exist <b>AND</b> <code>stopAtNonOption</code> <b>IS NOT</b> set then add
+ * that character prepended with "<b>-</b>".</li>
+ * </ul>
+ *
+ * @param token The current token to be <b>burst</b>
+ * @param stopAtNonOption Specifies whether to stop processing at the first non-Option encountered.
*/
- private void init() {
- eatTheRest = false;
- tokens.clear();
+ protected void burstToken(final String token, final boolean stopAtNonOption) {
+ for (int i = 1; i < token.length(); i++) {
+ final String ch = String.valueOf(token.charAt(i));
+
+ if (options.hasOption(ch)) {
+ tokens.add("-" + ch);
+ currentOption = options.getOption(ch);
+
+ if (currentOption.hasArg() && token.length() != i + 1) {
+ tokens.add(token.substring(i + 1));
+
+ break;
+ }
+ } else if (stopAtNonOption) {
+ processNonOptionToken(token.substring(i), true);
+ break;
+ } else {
+ tokens.add(token);
+ break;
+ }
+ }
}
/**
@@ -159,6 +193,15 @@ public class PosixParser extends Parser {
}
/**
+ * Resets the members to their original state i.e. remove all of <code>tokens</code> entries and set
+ * <code>eatTheRest</code> to false.
+ */
+ private void init() {
+ eatTheRest = false;
+ tokens.clear();
+ }
+
+ /**
* Add the special token "<b>--</b>" and the current <code>value</code> to the processed tokens list. Then add all the
* remaining <code>argument</code> values to the processed tokens list.
*
@@ -197,47 +240,4 @@ public class PosixParser extends Parser {
tokens.add(token);
}
-
- /**
- * Breaks <code>token</code> into its constituent parts using the following algorithm.
- *
- * <ul>
- * <li>ignore the first character ("<b>-</b>")</li>
- * <li>for each remaining character check if an {@link Option} exists with that id.</li>
- * <li>if an {@link Option} does exist then add that character prepended with "<b>-</b>" to the list of processed
- * tokens.</li>
- * <li>if the {@link Option} can have an argument value and there are remaining characters in the token then add the
- * remaining characters as a token to the list of processed tokens.</li>
- * <li>if an {@link Option} does <b>NOT</b> exist <b>AND</b> <code>stopAtNonOption</code> <b>IS</b> set then add the
- * special token "<b>--</b>" followed by the remaining characters and also the remaining tokens directly to the
- * processed tokens list.</li>
- * <li>if an {@link Option} does <b>NOT</b> exist <b>AND</b> <code>stopAtNonOption</code> <b>IS NOT</b> set then add
- * that character prepended with "<b>-</b>".</li>
- * </ul>
- *
- * @param token The current token to be <b>burst</b>
- * @param stopAtNonOption Specifies whether to stop processing at the first non-Option encountered.
- */
- protected void burstToken(final String token, final boolean stopAtNonOption) {
- for (int i = 1; i < token.length(); i++) {
- final String ch = String.valueOf(token.charAt(i));
-
- if (options.hasOption(ch)) {
- tokens.add("-" + ch);
- currentOption = options.getOption(ch);
-
- if (currentOption.hasArg() && token.length() != i + 1) {
- tokens.add(token.substring(i + 1));
-
- break;
- }
- } else if (stopAtNonOption) {
- processNonOptionToken(token.substring(i), true);
- break;
- } else {
- tokens.add(token);
- break;
- }
- }
- }
}
diff --git a/src/main/java/org/apache/commons/cli/TypeHandler.java b/src/main/java/org/apache/commons/cli/TypeHandler.java
index c306594..9865d9b 100644
--- a/src/main/java/org/apache/commons/cli/TypeHandler.java
+++ b/src/main/java/org/apache/commons/cli/TypeHandler.java
@@ -30,79 +30,56 @@ import java.util.Date;
*/
public class TypeHandler {
/**
- * Returns the <code>Object</code> of type <code>obj</code> with the value of <code>str</code>.
+ * Returns the class whose name is <code>classname</code>.
*
- * @param str the command line value
- * @param obj the type of argument
- * @return The instance of <code>obj</code> initialized with the value of <code>str</code>.
- * @throws ParseException if the value creation for the given object type failed
+ * @param classname the class name
+ * @return The class if it is found
+ * @throws ParseException if the class could not be found
*/
- public static Object createValue(final String str, final Object obj) throws ParseException {
- return createValue(str, (Class<?>) obj);
+ public static Class<?> createClass(final String classname) throws ParseException {
+ try {
+ return Class.forName(classname);
+ } catch (final ClassNotFoundException e) {
+ throw new ParseException("Unable to find the class: " + classname);
+ }
}
/**
- * Returns the <code>Object</code> of type <code>clazz</code> with the value of <code>str</code>.
+ * Returns the date represented by <code>str</code>.
+ * <p>
+ * This method is not yet implemented and always throws an {@link UnsupportedOperationException}.
*
- * @param str the command line value
- * @param clazz the class representing the type of argument
- * @param <T> type of argument
- * @return The instance of <code>clazz</code> initialized with the value of <code>str</code>.
- * @throws ParseException if the value creation for the given class failed
+ * @param str the date string
+ * @return The date if <code>str</code> is a valid date string, otherwise return null.
+ * @throws UnsupportedOperationException always
*/
- @SuppressWarnings("unchecked") // returned value will have type T because it is fixed by clazz
- public static <T> T createValue(final String str, final Class<T> clazz) throws ParseException {
- if (PatternOptionBuilder.STRING_VALUE == clazz) {
- return (T) str;
- }
- if (PatternOptionBuilder.OBJECT_VALUE == clazz) {
- return (T) createObject(str);
- }
- if (PatternOptionBuilder.NUMBER_VALUE == clazz) {
- return (T) createNumber(str);
- }
- if (PatternOptionBuilder.DATE_VALUE == clazz) {
- return (T) createDate(str);
- }
- if (PatternOptionBuilder.CLASS_VALUE == clazz) {
- return (T) createClass(str);
- }
- if (PatternOptionBuilder.FILE_VALUE == clazz) {
- return (T) createFile(str);
- }
- if (PatternOptionBuilder.EXISTING_FILE_VALUE == clazz) {
- return (T) openFile(str);
- }
- if (PatternOptionBuilder.FILES_VALUE == clazz) {
- return (T) createFiles(str);
- }
- if (PatternOptionBuilder.URL_VALUE == clazz) {
- return (T) createURL(str);
- }
- throw new ParseException("Unable to handle the class: " + clazz);
+ public static Date createDate(final String str) {
+ throw new UnsupportedOperationException("Not yet implemented");
}
/**
- * Create an Object from the classname and empty constructor.
+ * Returns the File represented by <code>str</code>.
*
- * @param classname the argument value
- * @return the initialized object
- * @throws ParseException if the class could not be found or the object could not be created
+ * @param str the File location
+ * @return The file represented by <code>str</code>.
*/
- public static Object createObject(final String classname) throws ParseException {
- final Class<?> cl;
-
- try {
- cl = Class.forName(classname);
- } catch (final ClassNotFoundException cnfe) {
- throw new ParseException("Unable to find the class: " + classname);
- }
+ public static File createFile(final String str) {
+ return new File(str);
+ }
- try {
- return cl.newInstance();
- } catch (final Exception e) {
- throw new ParseException(e.getClass().getName() + "; Unable to create an instance of: " + classname);
- }
+ /**
+ * Returns the File[] represented by <code>str</code>.
+ * <p>
+ * This method is not yet implemented and always throws an {@link UnsupportedOperationException}.
+ *
+ * @param str the paths to the files
+ * @return The File[] represented by <code>str</code>.
+ * @throws UnsupportedOperationException always
+ */
+ public static File[] createFiles(final String str) {
+ // to implement/port:
+ // return FileW.findFiles(str);
+ throw new UnsupportedOperationException("Not yet implemented");
}
/**
@@ -124,31 +101,26 @@ public class TypeHandler {
}
/**
- * Returns the class whose name is <code>classname</code>.
+ * Create an Object from the classname and empty constructor.
*
- * @param classname the class name
- * @return The class if it is found
- * @throws ParseException if the class could not be found
+ * @param classname the argument value
+ * @return the initialized object
+ * @throws ParseException if the class could not be found or the object could not be created
*/
- public static Class<?> createClass(final String classname) throws ParseException {
+ public static Object createObject(final String classname) throws ParseException {
+ final Class<?> cl;
+
try {
- return Class.forName(classname);
- } catch (final ClassNotFoundException e) {
+ cl = Class.forName(classname);
+ } catch (final ClassNotFoundException cnfe) {
throw new ParseException("Unable to find the class: " + classname);
}
- }
- /**
- * Returns the date represented by <code>str</code>.
- * <p>
- * This method is not yet implemented and always throws an {@link UnsupportedOperationException}.
- *
- * @param str the date string
- * @return The date if <code>str</code> is a valid date string, otherwise return null.
- * @throws UnsupportedOperationException always
- */
- public static Date createDate(final String str) {
- throw new UnsupportedOperationException("Not yet implemented");
+ try {
+ return cl.newInstance();
+ } catch (final Exception e) {
+ throw new ParseException(e.getClass().getName() + "; Unable to create an instance of: " + classname);
+ }
}
/**
@@ -167,13 +139,56 @@ public class TypeHandler {
}
/**
- * Returns the File represented by <code>str</code>.
+ * Returns the <code>Object</code> of type <code>clazz</code> with the value of <code>str</code>.
*
- * @param str the File location
- * @return The file represented by <code>str</code>.
+ * @param str the command line value
+ * @param clazz the class representing the type of argument
+ * @param <T> type of argument
+ * @return The instance of <code>clazz</code> initialized with the value of <code>str</code>.
+ * @throws ParseException if the value creation for the given class failed
*/
- public static File createFile(final String str) {
- return new File(str);
+ @SuppressWarnings("unchecked") // returned value will have type T because it is fixed by clazz
+ public static <T> T createValue(final String str, final Class<T> clazz) throws ParseException {
+ if (PatternOptionBuilder.STRING_VALUE == clazz) {
+ return (T) str;
+ }
+ if (PatternOptionBuilder.OBJECT_VALUE == clazz) {
+ return (T) createObject(str);
+ }
+ if (PatternOptionBuilder.NUMBER_VALUE == clazz) {
+ return (T) createNumber(str);
+ }
+ if (PatternOptionBuilder.DATE_VALUE == clazz) {
+ return (T) createDate(str);
+ }
+ if (PatternOptionBuilder.CLASS_VALUE == clazz) {
+ return (T) createClass(str);
+ }
+ if (PatternOptionBuilder.FILE_VALUE == clazz) {
+ return (T) createFile(str);
+ }
+ if (PatternOptionBuilder.EXISTING_FILE_VALUE == clazz) {
+ return (T) openFile(str);
+ }
+ if (PatternOptionBuilder.FILES_VALUE == clazz) {
+ return (T) createFiles(str);
+ }
+ if (PatternOptionBuilder.URL_VALUE == clazz) {
+ return (T) createURL(str);
+ }
+ throw new ParseException("Unable to handle the class: " + clazz);
+ }
+
+ /**
+ * Returns the <code>Object</code> of type <code>obj</code> with the value of <code>str</code>.
+ *
+ * @param str the command line value
+ * @param obj the type of argument
+ * @return The instance of <code>obj</code> initialized with the value of <code>str</code>.
+ * @throws ParseException if the value creation for the given object type failed
+ */
+ public static Object createValue(final String str, final Object obj) throws ParseException {
+ return createValue(str, (Class<?>) obj);
}
/**
@@ -190,19 +205,4 @@ public class TypeHandler {
throw new ParseException("Unable to find file: " + str);
}
}
-
- /**
- * Returns the File[] represented by <code>str</code>.
- * <p>
- * This method is not yet implemented and always throws an {@link UnsupportedOperationException}.
- *
- * @param str the paths to the files
- * @return The File[] represented by <code>str</code>.
- * @throws UnsupportedOperationException always
- */
- public static File[] createFiles(final String str) {
- // to implement/port:
- // return FileW.findFiles(str);
- throw new UnsupportedOperationException("Not yet implemented");
- }
}
diff --git a/src/main/java/org/apache/commons/cli/Util.java b/src/main/java/org/apache/commons/cli/Util.java
index 47257c0..2d53e4f 100644
--- a/src/main/java/org/apache/commons/cli/Util.java
+++ b/src/main/java/org/apache/commons/cli/Util.java
@@ -22,6 +22,22 @@ package org.apache.commons.cli;
*/
final class Util {
/**
+ * Remove the leading and trailing quotes from <code>str</code>. E.g. if str is '"one two"', then 'one two' is returned.
+ *
+ * @param str The string from which the leading and trailing quotes should be removed.
+ *
+ * @return The string without the leading and trailing quotes.
+ */
+ static String stripLeadingAndTrailingQuotes(String str) {
+ final int length = str.length();
+ if (length > 1 && str.startsWith("\"") && str.endsWith("\"") && str.substring(1, length - 1).indexOf('"') == -1) {
+ str = str.substring(1, length - 1);
+ }
+
+ return str;
+ }
+
+ /**
* Remove the hyphens from the beginning of <code>str</code> and return the new String.
*
* @param str The string from which the hyphens should be removed.
@@ -41,20 +57,4 @@ final class Util {
return str;
}
-
- /**
- * Remove the leading and trailing quotes from <code>str</code>. E.g. if str is '"one two"', then 'one two' is returned.
- *
- * @param str The string from which the leading and trailing quotes should be removed.
- *
- * @return The string without the leading and trailing quotes.
- */
- static String stripLeadingAndTrailingQuotes(String str) {
- final int length = str.length();
- if (length > 1 && str.startsWith("\"") && str.endsWith("\"") && str.substring(1, length - 1).indexOf('"') == -1) {
- str = str.substring(1, length - 1);
- }
-
- return str;
- }
}
diff --git a/src/test/java/org/apache/commons/cli/ApplicationTest.java b/src/test/java/org/apache/commons/cli/ApplicationTest.java
index 8abdfbe..9ea0ee8 100644
--- a/src/test/java/org/apache/commons/cli/ApplicationTest.java
+++ b/src/test/java/org/apache/commons/cli/ApplicationTest.java
@@ -40,33 +40,6 @@ import org.junit.Test;
*/
@SuppressWarnings("deprecation") // tests some deprecated classes
public class ApplicationTest {
- @Test
- public void testLs() throws Exception {
- // create the command line parser
- final CommandLineParser parser = new PosixParser();
- final Options options = new Options();
- options.addOption("a", "all", false, "do not hide entries starting with .");
- options.addOption("A", "almost-all", false, "do not list implied . and ..");
- options.addOption("b", "escape", false, "print octal escapes for nongraphic characters");
- //@formatter:off
- options.addOption(OptionBuilder.withLongOpt("block-size")
- .withDescription("use SIZE-byte blocks")
- .hasArg()
- .withArgName("SIZE")
- .create());
- //@formatter:on
- options.addOption("B", "ignore-backups", false, "do not list implied entried ending with ~");
- options.addOption("c", false, "with -lt: sort by, and show, ctime (time of last modification of file status information) with "
- + "-l:show ctime and sort by name otherwise: sort by ctime");
- options.addOption("C", false, "list entries by columns");
-
- final String[] args = {"--block-size=10"};
-
- final CommandLine line = parser.parse(options, args);
- assertTrue(line.hasOption("block-size"));
- assertEquals(line.getOptionValue("block-size"), "10");
- }
-
/**
* Ant test
*/
@@ -182,6 +155,33 @@ public class ApplicationTest {
assertEquals("println 'hello'", line.getOptionValue('e'));
}
+ @Test
+ public void testLs() throws Exception {
+ // create the command line parser
+ final CommandLineParser parser = new PosixParser();
+ final Options options = new Options();
+ options.addOption("a", "all", false, "do not hide entries starting with .");
+ options.addOption("A", "almost-all", false, "do not list implied . and ..");
+ options.addOption("b", "escape", false, "print octal escapes for nongraphic characters");
+ //@formatter:off
+ options.addOption(OptionBuilder.withLongOpt("block-size")
+ .withDescription("use SIZE-byte blocks")
+ .hasArg()
+ .withArgName("SIZE")
+ .create());
+ //@formatter:on
+ options.addOption("B", "ignore-backups", false, "do not list implied entried ending with ~");
+ options.addOption("c", false, "with -lt: sort by, and show, ctime (time of last modification of file status information) with "
+ + "-l:show ctime and sort by name otherwise: sort by ctime");
+ options.addOption("C", false, "list entries by columns");
+
+ final String[] args = {"--block-size=10"};
+
+ final CommandLine line = parser.parse(options, args);
+ assertTrue(line.hasOption("block-size"));
+ assertEquals(line.getOptionValue("block-size"), "10");
+ }
+
/**
* author Slawek Zachcial
*/
diff --git a/src/test/java/org/apache/commons/cli/ArgumentIsOptionTest.java b/src/test/java/org/apache/commons/cli/ArgumentIsOptionTest.java
index 4da03f5..d613f0b 100644
--- a/src/test/java/org/apache/commons/cli/ArgumentIsOptionTest.java
+++ b/src/test/java/org/apache/commons/cli/ArgumentIsOptionTest.java
@@ -36,6 +36,16 @@ public class ArgumentIsOptionTest {
}
@Test
+ public void testOption() throws Exception {
+ final String[] args = {"-p"};
+
+ final CommandLine cl = parser.parse(options, args);
+ assertTrue("Confirm -p is set", cl.hasOption("p"));
+ assertFalse("Confirm -attr is not set", cl.hasOption("attr"));
+ assertTrue("Confirm all arguments recognized", cl.getArgs().length == 0);
+ }
+
+ @Test
public void testOptionAndOptionWithArgument() throws Exception {
final String[] args = {"-p", "-attr", "p"};
@@ -56,14 +66,4 @@ public class ArgumentIsOptionTest {
assertTrue("Confirm arg of -attr", cl.getOptionValue("attr").equals("p"));
assertTrue("Confirm all arguments recognized", cl.getArgs().length == 0);
}
-
- @Test
- public void testOption() throws Exception {
- final String[] args = {"-p"};
-
- final CommandLine cl = parser.parse(options, args);
- assertTrue("Confirm -p is set", cl.hasOption("p"));
- assertFalse("Confirm -attr is not set", cl.hasOption("attr"));
- assertTrue("Confirm all arguments recognized", cl.getArgs().length == 0);
- }
}
diff --git a/src/test/java/org/apache/commons/cli/BasicParserTest.java b/src/test/java/org/apache/commons/cli/BasicParserTest.java
index c6d06f0..5d5fcd8 100644
--- a/src/test/java/org/apache/commons/cli/BasicParserTest.java
+++ b/src/test/java/org/apache/commons/cli/BasicParserTest.java
@@ -33,144 +33,144 @@ public class BasicParserTest extends ParserTestCase {
@Override
@Test
@Ignore("not supported by the BasicParser")
- public void testDoubleDash2() throws Exception {
+ public void testAmbiguousLongWithoutEqualSingleDash() throws Exception {
}
@Override
@Test
@Ignore("not supported by the BasicParser")
- public void testLongWithoutEqualSingleDash() throws Exception {
+ public void testAmbiguousPartialLongOption1() throws Exception {
}
@Override
@Test
@Ignore("not supported by the BasicParser")
- public void testAmbiguousLongWithoutEqualSingleDash() throws Exception {
+ public void testAmbiguousPartialLongOption2() throws Exception {
}
@Override
@Test
- @Ignore("not supported by the BasicParser (CLI-184)")
- public void testNegativeOption() throws Exception {
+ @Ignore("not supported by the BasicParser")
+ public void testAmbiguousPartialLongOption3() throws Exception {
}
@Override
@Test
@Ignore("not supported by the BasicParser")
- public void testPropertiesOption1() throws Exception {
+ public void testAmbiguousPartialLongOption4() throws Exception {
}
@Override
@Test
@Ignore("not supported by the BasicParser")
- public void testPropertiesOption2() throws Exception {
+ public void testBursting() throws Exception {
}
@Override
@Test
@Ignore("not supported by the BasicParser")
- public void testShortWithEqual() throws Exception {
+ public void testDoubleDash2() throws Exception {
}
@Override
@Test
@Ignore("not supported by the BasicParser")
- public void testShortWithoutEqual() throws Exception {
+ public void testLongWithEqualDoubleDash() throws Exception {
}
@Override
@Test
@Ignore("not supported by the BasicParser")
- public void testLongWithEqualDoubleDash() throws Exception {
+ public void testLongWithEqualSingleDash() throws Exception {
}
@Override
@Test
@Ignore("not supported by the BasicParser")
- public void testLongWithEqualSingleDash() throws Exception {
+ public void testLongWithoutEqualSingleDash() throws Exception {
}
@Override
@Test
@Ignore("not supported by the BasicParser")
- public void testUnambiguousPartialLongOption1() throws Exception {
+ public void testMissingArgWithBursting() throws Exception {
}
@Override
@Test
- @Ignore("not supported by the BasicParser")
- public void testUnambiguousPartialLongOption2() throws Exception {
+ @Ignore("not supported by the BasicParser (CLI-184)")
+ public void testNegativeOption() throws Exception {
}
@Override
@Test
@Ignore("not supported by the BasicParser")
- public void testUnambiguousPartialLongOption3() throws Exception {
+ public void testPartialLongOptionSingleDash() throws Exception {
}
@Override
@Test
@Ignore("not supported by the BasicParser")
- public void testUnambiguousPartialLongOption4() throws Exception {
+ public void testPropertiesOption1() throws Exception {
}
@Override
@Test
@Ignore("not supported by the BasicParser")
- public void testAmbiguousPartialLongOption1() throws Exception {
+ public void testPropertiesOption2() throws Exception {
}
@Override
@Test
@Ignore("not supported by the BasicParser")
- public void testAmbiguousPartialLongOption2() throws Exception {
+ public void testShortWithEqual() throws Exception {
}
@Override
@Test
@Ignore("not supported by the BasicParser")
- public void testAmbiguousPartialLongOption3() throws Exception {
+ public void testShortWithoutEqual() throws Exception {
}
@Override
@Test
@Ignore("not supported by the BasicParser")
- public void testAmbiguousPartialLongOption4() throws Exception {
+ public void testStopBursting() throws Exception {
}
@Override
@Test
@Ignore("not supported by the BasicParser")
- public void testPartialLongOptionSingleDash() throws Exception {
+ public void testStopBursting2() throws Exception {
}
@Override
@Test
@Ignore("not supported by the BasicParser")
- public void testBursting() throws Exception {
+ public void testUnambiguousPartialLongOption1() throws Exception {
}
@Override
@Test
@Ignore("not supported by the BasicParser")
- public void testUnrecognizedOptionWithBursting() throws Exception {
+ public void testUnambiguousPartialLongOption2() throws Exception {
}
@Override
@Test
@Ignore("not supported by the BasicParser")
- public void testMissingArgWithBursting() throws Exception {
+ public void testUnambiguousPartialLongOption3() throws Exception {
}
@Override
@Test
@Ignore("not supported by the BasicParser")
- public void testStopBursting() throws Exception {
+ public void testUnambiguousPartialLongOption4() throws Exception {
}
@Override
@Test
@Ignore("not supported by the BasicParser")
- public void testStopBursting2() throws Exception {
+ public void testUnrecognizedOptionWithBursting() throws Exception {
}
}
diff --git a/src/test/java/org/apache/commons/cli/CommandLineTest.java b/src/test/java/org/apache/commons/cli/CommandLineTest.java
index 7056cd2..d9fc548 100644
--- a/src/test/java/org/apache/commons/cli/CommandLineTest.java
+++ b/src/test/java/org/apache/commons/cli/CommandLineTest.java
@@ -29,6 +29,18 @@ import org.junit.Test;
public class CommandLineTest {
@Test
+ public void testBuilder() throws Exception {
+ final CommandLine.Builder builder = new CommandLine.Builder();
+ builder.addArg("foo").addArg("bar");
+ builder.addOption(Option.builder("T").build());
+ final CommandLine cmd = builder.build();
+
+ assertEquals("foo", cmd.getArgs()[0]);
+ assertEquals("bar", cmd.getArgList().get(1));
+ assertEquals("T", cmd.getOptions()[0].getOpt());
+ }
+
+ @Test
public void testGetOptionProperties() throws Exception {
final String[] args = {"-Dparam1=value1", "-Dparam2=value2", "-Dparam3", "-Dparam4=value4", "-D", "--property", "foo=bar"};
@@ -140,16 +152,4 @@ public class CommandLineTest {
assertNull(cmd.getOptionValue((Option) null));
assertNull(cmd.getParsedOptionValue((Option) null));
}
-
- @Test
- public void testBuilder() throws Exception {
- final CommandLine.Builder builder = new CommandLine.Builder();
- builder.addArg("foo").addArg("bar");
- builder.addOption(Option.builder("T").build());
- final CommandLine cmd = builder.build();
-
- assertEquals("foo", cmd.getArgs()[0]);
- assertEquals("bar", cmd.getArgList().get(1));
- assertEquals("T", cmd.getOptions()[0].getOpt());
- }
}
diff --git a/src/test/java/org/apache/commons/cli/GnuParserTest.java b/src/test/java/org/apache/commons/cli/GnuParserTest.java
index af289a4..a08ca8b 100644
--- a/src/test/java/org/apache/commons/cli/GnuParserTest.java
+++ b/src/test/java/org/apache/commons/cli/GnuParserTest.java
@@ -33,126 +33,126 @@ public class GnuParserTest extends ParserTestCase {
@Override
@Test
@Ignore("not supported by the GnuParser")
- public void testDoubleDash2() throws Exception {
+ public void testAmbiguousLongWithoutEqualSingleDash() throws Exception {
}
@Override
@Test
@Ignore("not supported by the GnuParser")
- public void testLongWithoutEqualSingleDash() throws Exception {
+ public void testAmbiguousPartialLongOption1() throws Exception {
}
@Override
@Test
@Ignore("not supported by the GnuParser")
- public void testAmbiguousLongWithoutEqualSingleDash() throws Exception {
+ public void testAmbiguousPartialLongOption2() throws Exception {
}
@Override
@Test
- @Ignore("not supported by the GnuParser (CLI-184)")
- public void testNegativeOption() throws Exception {
+ @Ignore("not supported by the GnuParser")
+ public void testAmbiguousPartialLongOption3() throws Exception {
}
@Override
@Test
@Ignore("not supported by the GnuParser")
- public void testLongWithUnexpectedArgument1() throws Exception {
+ public void testAmbiguousPartialLongOption4() throws Exception {
}
@Override
@Test
@Ignore("not supported by the GnuParser")
- public void testLongWithUnexpectedArgument2() throws Exception {
+ public void testBursting() throws Exception {
}
@Override
@Test
@Ignore("not supported by the GnuParser")
- public void testShortWithUnexpectedArgument() throws Exception {
+ public void testDoubleDash2() throws Exception {
}
@Override
@Test
@Ignore("not supported by the GnuParser")
- public void testUnambiguousPartialLongOption1() throws Exception {
+ public void testLongWithoutEqualSingleDash() throws Exception {
}
@Override
@Test
@Ignore("not supported by the GnuParser")
- public void testUnambiguousPartialLongOption2() throws Exception {
+ public void testLongWithUnexpectedArgument1() throws Exception {
}
@Override
@Test
@Ignore("not supported by the GnuParser")
- public void testUnambiguousPartialLongOption3() throws Exception {
+ public void testLongWithUnexpectedArgument2() throws Exception {
}
@Override
@Test
@Ignore("not supported by the GnuParser")
- public void testUnambiguousPartialLongOption4() throws Exception {
+ public void testMissingArgWithBursting() throws Exception {
}
@Override
@Test
- @Ignore("not supported by the GnuParser")
- public void testAmbiguousPartialLongOption1() throws Exception {
+ @Ignore("not supported by the GnuParser (CLI-184)")
+ public void testNegativeOption() throws Exception {
}
@Override
@Test
@Ignore("not supported by the GnuParser")
- public void testAmbiguousPartialLongOption2() throws Exception {
+ public void testPartialLongOptionSingleDash() throws Exception {
}
@Override
@Test
@Ignore("not supported by the GnuParser")
- public void testAmbiguousPartialLongOption3() throws Exception {
+ public void testShortWithUnexpectedArgument() throws Exception {
}
@Override
@Test
@Ignore("not supported by the GnuParser")
- public void testAmbiguousPartialLongOption4() throws Exception {
+ public void testStopBursting() throws Exception {
}
@Override
@Test
@Ignore("not supported by the GnuParser")
- public void testPartialLongOptionSingleDash() throws Exception {
+ public void testStopBursting2() throws Exception {
}
@Override
@Test
@Ignore("not supported by the GnuParser")
- public void testBursting() throws Exception {
+ public void testUnambiguousPartialLongOption1() throws Exception {
}
@Override
@Test
@Ignore("not supported by the GnuParser")
- public void testUnrecognizedOptionWithBursting() throws Exception {
+ public void testUnambiguousPartialLongOption2() throws Exception {
}
@Override
@Test
@Ignore("not supported by the GnuParser")
- public void testMissingArgWithBursting() throws Exception {
+ public void testUnambiguousPartialLongOption3() throws Exception {
}
@Override
@Test
@Ignore("not supported by the GnuParser")
- public void testStopBursting() throws Exception {
+ public void testUnambiguousPartialLongOption4() throws Exception {
}
@Override
@Test
@Ignore("not supported by the GnuParser")
- public void testStopBursting2() throws Exception {
+ public void testUnrecognizedOptionWithBursting() throws Exception {
}
}
diff --git a/src/test/java/org/apache/commons/cli/HelpFormatterTest.java b/src/test/java/org/apache/commons/cli/HelpFormatterTest.java
index e3c83cc..052f6b0 100644
--- a/src/test/java/org/apache/commons/cli/HelpFormatterTest.java
+++ b/src/test/java/org/apache/commons/cli/HelpFormatterTest.java
@@ -34,6 +34,73 @@ public class HelpFormatterTest {
private static final String EOL = System.getProperty("line.separator");
@Test
+ public void testAccessors() {
+ final HelpFormatter formatter = new HelpFormatter();
+
+ formatter.setArgName("argname");
+ assertEquals("arg name", "argname", formatter.getArgName());
+
+ formatter.setDescPadding(3);
+ assertEquals("desc padding", 3, formatter.getDescPadding());
+
+ formatter.setLeftPadding(7);
+ assertEquals("left padding", 7, formatter.getLeftPadding());
+
+ formatter.setLongOptPrefix("~~");
+ assertEquals("long opt prefix", "~~", formatter.getLongOptPrefix());
+
+ formatter.setNewLine("\n");
+ assertEquals("new line", "\n", formatter.getNewLine());
+
+ formatter.setOptPrefix("~");
+ assertEquals("opt prefix", "~", formatter.getOptPrefix());
+
+ formatter.setSyntaxPrefix("-> ");
+ assertEquals("syntax prefix", "-> ", formatter.getSyntaxPrefix());
+
+ formatter.setWidth(80);
+ assertEquals("width", 80, formatter.getWidth());
+ }
+
+ @Test
+ public void testAutomaticUsage() throws Exception {
+ final HelpFormatter hf = new HelpFormatter();
+ Options options;
+ String expected = "usage: app [-a]";
+ final ByteArrayOutputStream out = new ByteArrayOutputStream();
+ final PrintWriter pw = new PrintWriter(out);
+
+ options = new Options().addOption("a", false, "aaaa aaaa aaaa aaaa aaaa");
+ hf.printUsage(pw, 60, "app", options);
+ pw.flush();
+ assertEquals("simple auto usage", expected, out.toString().trim());
+ out.reset();
+
+ expected = "usage: app [-a] [-b]";
+ options = new Options().addOption("a", false, "aaaa aaaa aaaa aaaa aaaa").addOption("b", false, "bbb");
+ hf.printUsage(pw, 60, "app", options);
+ pw.flush();
+ assertEquals("simple auto usage", expected, out.toString().trim());
+ out.reset();
+ }
+
+ @Test
+ public void testDefaultArgName() {
+ final Option option = Option.builder("f").hasArg().required(true).build();
+
+ final Options options = new Options();
+ options.addOption(option);
+
+ final StringWriter out = new StringWriter();
+
+ final HelpFormatter formatter = new HelpFormatter();
+ formatter.setArgName("argument");
+ formatter.printUsage(new PrintWriter(out), 80, "app", options);
+
+ assertEquals("usage: app -f <argument>" + EOL, out.toString());
+ }
+
+ @Test
public void testFindWrapPos() throws Exception {
final HelpFormatter hf = new HelpFormatter();
@@ -61,136 +128,168 @@ public class HelpFormatterTest {
}
@Test
- public void testRenderWrappedTextWordCut() {
- final int width = 7;
- final int padding = 0;
- final String text = "Thisisatest.";
- final String expected = "Thisisa" + EOL + "test.";
-
- final StringBuffer sb = new StringBuffer();
- new HelpFormatter().renderWrappedText(sb, width, padding, text);
- assertEquals("cut and wrap", expected, sb.toString());
+ public void testHeaderStartingWithLineSeparator() {
+ // related to Bugzilla #21215
+ final Options options = new Options();
+ final HelpFormatter formatter = new HelpFormatter();
+ final String header = EOL + "Header";
+ final String footer = "Footer";
+ final StringWriter out = new StringWriter();
+ formatter.printHelp(new PrintWriter(out), 80, "foobar", header, options, 2, 2, footer, true);
+ //@formatter:off
+ assertEquals(
+ "usage: foobar" + EOL +
+ "" + EOL +
+ "Header" + EOL +
+ "" + EOL +
+ "Footer" + EOL,
+ out.toString());
+ //@formatter:on
}
@Test
- public void testRenderWrappedTextSingleLine() {
- // single line text
- final int width = 12;
- final int padding = 0;
- final String text = "This is a test.";
- final String expected = "This is a" + EOL + "test.";
+ public void testHelpWithLongOptSeparator() throws Exception {
+ final Options options = new Options();
+ options.addOption("f", true, "the file");
+ options.addOption(Option.builder("s").longOpt("size").desc("the size").hasArg().argName("SIZE").build());
+ options.addOption(Option.builder().longOpt("age").desc("the age").hasArg().build());
- final StringBuffer sb = new StringBuffer();
- new HelpFormatter().renderWrappedText(sb, width, padding, text);
- assertEquals("single line text", expected, sb.toString());
- }
+ final HelpFormatter formatter = new HelpFormatter();
+ assertEquals(HelpFormatter.DEFAULT_LONG_OPT_SEPARATOR, formatter.getLongOptSeparator());
+ formatter.setLongOptSeparator("=");
+ assertEquals("=", formatter.getLongOptSeparator());
- @Test
- public void testRenderWrappedTextSingleLinePadded() {
- // single line padded text
- final int width = 12;
- final int padding = 4;
- final String text = "This is a test.";
- final String expected = "This is a" + EOL + " test.";
+ final StringWriter out = new StringWriter();
- final StringBuffer sb = new StringBuffer();
- new HelpFormatter().renderWrappedText(sb, width, padding, text);
- assertEquals("single line padded text", expected, sb.toString());
- }
+ formatter.printHelp(new PrintWriter(out), 80, "create", "header", options, 2, 2, "footer");
- @Test
- public void testRenderWrappedTextSingleLinePadded2() {
- // single line padded text 2
- final int width = 53;
- final int padding = 24;
//@formatter:off
- final String text = " -p,--period <PERIOD> PERIOD is time duration of form " +
- "DATE[-DATE] where DATE has form YYYY[MM[DD]]";
- final String expected = " -p,--period <PERIOD> PERIOD is time duration of" + EOL +
- " form DATE[-DATE] where DATE" + EOL +
- " has form YYYY[MM[DD]]";
+ assertEquals(
+ "usage: create" + EOL +
+ "header" + EOL +
+ " --age=<arg> the age" + EOL +
+ " -f <arg> the file" + EOL +
+ " -s,--size=<SIZE> the size" + EOL +
+ "footer" + EOL,
+ out.toString());
//@formatter:on
-
- final StringBuffer sb = new StringBuffer();
- new HelpFormatter().renderWrappedText(sb, width, padding, text);
- assertEquals("single line padded text 2", expected, sb.toString());
}
@Test
- public void testRenderWrappedTextMultiLine() {
- // multi line text
- final int width = 16;
- final int padding = 0;
+ public void testIndentedHeaderAndFooter() {
+ // related to CLI-207
+ final Options options = new Options();
+ final HelpFormatter formatter = new HelpFormatter();
+ final String header = " Header1\n Header2";
+ final String footer = " Footer1\n Footer2";
+ final StringWriter out = new StringWriter();
+ formatter.printHelp(new PrintWriter(out), 80, "foobar", header, options, 2, 2, footer, true);
//@formatter:off
- final String expected = "aaaa aaaa aaaa" + EOL +
- "aaaaaa" + EOL +
- "aaaaa";
+ assertEquals(
+ "usage: foobar" + EOL +
+ " Header1" + EOL +
+ " Header2" + EOL +
+ "" + EOL +
+ " Footer1" + EOL +
+ " Footer2" + EOL,
+ out.toString());
//@formatter:on
-
- final StringBuffer sb = new StringBuffer();
- new HelpFormatter().renderWrappedText(sb, width, padding, expected);
- assertEquals("multi line text", expected, sb.toString());
}
@Test
- public void testRenderWrappedTextMultiLinePadded() {
- // multi-line padded text
- final int width = 16;
- final int padding = 4;
+ public void testOptionWithoutShortFormat() {
+ // related to Bugzilla #19383 (CLI-67)
+ final Options options = new Options();
+ options.addOption(new Option("a", "aaa", false, "aaaaaaa"));
+ options.addOption(new Option(null, "bbb", false, "bbbbbbb"));
+ options.addOption(new Option("c", null, false, "ccccccc"));
+
+ final HelpFormatter formatter = new HelpFormatter();
+ final StringWriter out = new StringWriter();
+ formatter.printHelp(new PrintWriter(out), 80, "foobar", "", options, 2, 2, "", true);
//@formatter:off
- final String text = "aaaa aaaa aaaa" + EOL +
- "aaaaaa" + EOL +
- "aaaaa";
- final String expected = "aaaa aaaa aaaa" + EOL +
- " aaaaaa" + EOL +
- " aaaaa";
+ assertEquals(
+ "usage: foobar [-a] [--bbb] [-c]" + EOL +
+ " -a,--aaa aaaaaaa" + EOL +
+ " --bbb bbbbbbb" + EOL +
+ " -c ccccccc" + EOL,
+ out.toString());
//@formatter:on
-
- final StringBuffer sb = new StringBuffer();
- new HelpFormatter().renderWrappedText(sb, width, padding, text);
- assertEquals("multi-line padded text", expected, sb.toString());
}
@Test
- public void testPrintOptions() throws Exception {
- final StringBuffer sb = new StringBuffer();
- final HelpFormatter hf = new HelpFormatter();
- final int leftPad = 1;
- final int descPad = 3;
- final String lpad = hf.createPadding(leftPad);
- final String dpad = hf.createPadding(descPad);
- Options options;
- String expected;
-
- options = new Options().addOption("a", false, "aaaa aaaa aaaa aaaa aaaa");
- expected = lpad + "-a" + dpad + "aaaa aaaa aaaa aaaa aaaa";
- hf.renderOptions(sb, 60, options, leftPad, descPad);
- assertEquals("simple non-wrapped option", expected, sb.toString());
+ public void testOptionWithoutShortFormat2() {
+ // related to Bugzilla #27635 (CLI-26)
+ final Option help = new Option("h", "help", false, "print this message");
+ final Option version = new Option("v", "version", false, "print version information");
+ final Option newRun = new Option("n", "new", false, "Create NLT cache entries only for new items");
+ final Option trackerRun = new Option("t", "tracker", false, "Create NLT cache entries only for tracker items");
- int nextLineTabStop = leftPad + descPad + "-a".length();
- expected = lpad + "-a" + dpad + "aaaa aaaa aaaa" + EOL + hf.createPadding(nextLineTabStop) + "aaaa aaaa";
- sb.setLength(0);
- hf.renderOptions(sb, nextLineTabStop + 17, options, leftPad, descPad);
- assertEquals("simple wrapped option", expected, sb.toString());
+ //@formatter:off
+ final Option timeLimit = Option.builder("l")
+ .longOpt("limit")
+ .hasArg()
+ .valueSeparator()
+ .desc("Set time limit for execution, in mintues")
+ .build();
- options = new Options().addOption("a", "aaa", false, "dddd dddd dddd dddd");
- expected = lpad + "-a,--aaa" + dpad + "dddd dddd dddd dddd";
- sb.setLength(0);
- hf.renderOptions(sb, 60, options, leftPad, descPad);
- assertEquals("long non-wrapped option", expected, sb.toString());
+ final Option age = Option.builder("a").longOpt("age")
+ .hasArg()
+ .valueSeparator()
+ .desc("Age (in days) of cache item before being recomputed")
+ .build();
- nextLineTabStop = leftPad + descPad + "-a,--aaa".length();
- expected = lpad + "-a,--aaa" + dpad + "dddd dddd" + EOL + hf.createPadding(nextLineTabStop) + "dddd dddd";
- sb.setLength(0);
- hf.renderOptions(sb, 25, options, leftPad, descPad);
- assertEquals("long wrapped option", expected, sb.toString());
+ final Option server = Option.builder("s").longOpt("server")
+ .hasArg()
+ .valueSeparator()
+ .desc("The NLT server address")
+ .build();
- options = new Options().addOption("a", "aaa", false, "dddd dddd dddd dddd").addOption("b", false, "feeee eeee eeee eeee");
- expected = lpad + "-a,--aaa" + dpad + "dddd dddd" + EOL + hf.createPadding(nextLineTabStop) + "dddd dddd" + EOL + lpad + "-b " + dpad
- + "feeee eeee" + EOL + hf.createPadding(nextLineTabStop) + "eeee eeee";
- sb.setLength(0);
- hf.renderOptions(sb, 25, options, leftPad, descPad);
- assertEquals("multiple wrapped options", expected, sb.toString());
+ final Option numResults = Option.builder("r").longOpt("results")
+ .hasArg()
+ .valueSeparator()
+ .desc("Number of results per item")
+ .build();
+
+ final Option configFile = Option.builder().longOpt("config")
+ .hasArg()
+ .valueSeparator()
+ .desc("Use the specified configuration file")
+ .build();
+ //@formatter:on
+
+ final Options mOptions = new Options();
+ mOptions.addOption(help);
+ mOptions.addOption(version);
+ mOptions.addOption(newRun);
+ mOptions.addOption(trackerRun);
+ mOptions.addOption(timeLimit);
+ mOptions.addOption(age);
+ mOptions.addOption(server);
+ mOptions.addOption(numResults);
+ mOptions.addOption(configFile);
+
+ final HelpFormatter formatter = new HelpFormatter();
+ final String eol = System.getProperty("line.separator");
+ final StringWriter out = new StringWriter();
+ formatter.printHelp(new PrintWriter(out), 80, "commandline", "header", mOptions, 2, 2, "footer", true);
+ //@formatter:off
+ assertEquals(
+ "usage: commandline [-a <arg>] [--config <arg>] [-h] [-l <arg>] [-n] [-r <arg>]" + eol +
+ " [-s <arg>] [-t] [-v]" + eol +
+ "header" + eol +
+ " -a,--age <arg> Age (in days) of cache item before being recomputed" + eol +
+ " --config <arg> Use the specified configuration file" + eol +
+ " -h,--help print this message" + eol +
+ " -l,--limit <arg> Set time limit for execution, in mintues" + eol +
+ " -n,--new Create NLT cache entries only for new items" + eol +
+ " -r,--results <arg> Number of results per item" + eol +
+ " -s,--server <arg> The NLT server address" + eol +
+ " -t,--tracker Create NLT cache entries only for tracker items" + eol +
+ " -v,--version print version information" + eol +
+ "footer" + eol,
+ out.toString());
+ //@formatter:on
}
@Test
@@ -212,86 +311,6 @@ public class HelpFormatterTest {
}
@Test
- public void testAutomaticUsage() throws Exception {
- final HelpFormatter hf = new HelpFormatter();
- Options options;
- String expected = "usage: app [-a]";
- final ByteArrayOutputStream out = new ByteArrayOutputStream();
- final PrintWriter pw = new PrintWriter(out);
-
- options = new Options().addOption("a", false, "aaaa aaaa aaaa aaaa aaaa");
- hf.printUsage(pw, 60, "app", options);
- pw.flush();
- assertEquals("simple auto usage", expected, out.toString().trim());
- out.reset();
-
- expected = "usage: app [-a] [-b]";
- options = new Options().addOption("a", false, "aaaa aaaa aaaa aaaa aaaa").addOption("b", false, "bbb");
- hf.printUsage(pw, 60, "app", options);
- pw.flush();
- assertEquals("simple auto usage", expected, out.toString().trim());
- out.reset();
- }
-
- // This test ensures the options are properly sorted
- // See https://issues.apache.org/jira/browse/CLI-131
- @Test
- public void testPrintUsage() {
- final Option optionA = new Option("a", "first");
- final Option optionB = new Option("b", "second");
- final Option optionC = new Option("c", "third");
- final Options opts = new Options();
- opts.addOption(optionA);
- opts.addOption(optionB);
- opts.addOption(optionC);
- final HelpFormatter helpFormatter = new HelpFormatter();
- final ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
- final PrintWriter printWriter = new PrintWriter(bytesOut);
- helpFormatter.printUsage(printWriter, 80, "app", opts);
- printWriter.close();
- assertEquals("usage: app [-a] [-b] [-c]" + EOL, bytesOut.toString());
- }
-
- // uses the test for CLI-131 to implement CLI-155
- @Test
- public void testPrintSortedUsage() {
- final Options opts = new Options();
- opts.addOption(new Option("a", "first"));
- opts.addOption(new Option("b", "second"));
- opts.addOption(new Option("c", "third"));
-
- final HelpFormatter helpFormatter = new HelpFormatter();
- helpFormatter.setOptionComparator(new Comparator<Option>() {
- @Override
- public int compare(final Option opt1, final Option opt2) {
- // reverses the functionality of the default comparator
- return opt2.getKey().compareToIgnoreCase(opt1.getKey());
- }
- });
-
- final StringWriter out = new StringWriter();
- helpFormatter.printUsage(new PrintWriter(out), 80, "app", opts);
-
- assertEquals("usage: app [-c] [-b] [-a]" + EOL, out.toString());
- }
-
- @Test
- public void testPrintSortedUsageWithNullComparator() {
- final Options opts = new Options();
- opts.addOption(new Option("c", "first"));
- opts.addOption(new Option("b", "second"));
- opts.addOption(new Option("a", "third"));
-
- final HelpFormatter helpFormatter = new HelpFormatter();
- helpFormatter.setOptionComparator(null);
-
- final StringWriter out = new StringWriter();
- helpFormatter.printUsage(new PrintWriter(out), 80, "app", opts);
-
- assertEquals("usage: app [-c] [-b] [-a]" + EOL, out.toString());
- }
-
- @Test
public void testPrintOptionGroupUsage() {
final OptionGroup group = new OptionGroup();
group.addOption(Option.builder("a").build());
@@ -310,22 +329,45 @@ public class HelpFormatterTest {
}
@Test
- public void testPrintRequiredOptionGroupUsage() {
- final OptionGroup group = new OptionGroup();
- group.addOption(Option.builder("a").build());
- group.addOption(Option.builder("b").build());
- group.addOption(Option.builder("c").build());
- group.setRequired(true);
+ public void testPrintOptions() throws Exception {
+ final StringBuffer sb = new StringBuffer();
+ final HelpFormatter hf = new HelpFormatter();
+ final int leftPad = 1;
+ final int descPad = 3;
+ final String lpad = hf.createPadding(leftPad);
+ final String dpad = hf.createPadding(descPad);
+ Options options;
+ String expected;
- final Options options = new Options();
- options.addOptionGroup(group);
+ options = new Options().addOption("a", false, "aaaa aaaa aaaa aaaa aaaa");
+ expected = lpad + "-a" + dpad + "aaaa aaaa aaaa aaaa aaaa";
+ hf.renderOptions(sb, 60, options, leftPad, descPad);
+ assertEquals("simple non-wrapped option", expected, sb.toString());
- final StringWriter out = new StringWriter();
+ int nextLineTabStop = leftPad + descPad + "-a".length();
+ expected = lpad + "-a" + dpad + "aaaa aaaa aaaa" + EOL + hf.createPadding(nextLineTabStop) + "aaaa aaaa";
+ sb.setLength(0);
+ hf.renderOptions(sb, nextLineTabStop + 17, options, leftPad, descPad);
+ assertEquals("simple wrapped option", expected, sb.toString());
- final HelpFormatter formatter = new HelpFormatter();
- formatter.printUsage(new PrintWriter(out), 80, "app", options);
+ options = new Options().addOption("a", "aaa", false, "dddd dddd dddd dddd");
+ expected = lpad + "-a,--aaa" + dpad + "dddd dddd dddd dddd";
+ sb.setLength(0);
+ hf.renderOptions(sb, 60, options, leftPad, descPad);
+ assertEquals("long non-wrapped option", expected, sb.toString());
- assertEquals("usage: app -a | -b | -c" + EOL, out.toString());
+ nextLineTabStop = leftPad + descPad + "-a,--aaa".length();
+ expected = lpad + "-a,--aaa" + dpad + "dddd dddd" + EOL + hf.createPadding(nextLineTabStop) + "dddd dddd";
+ sb.setLength(0);
+ hf.renderOptions(sb, 25, options, leftPad, descPad);
+ assertEquals("long wrapped option", expected, sb.toString());
+
+ options = new Options().addOption("a", "aaa", false, "dddd dddd dddd dddd").addOption("b", false, "feeee eeee eeee eeee");
+ expected = lpad + "-a,--aaa" + dpad + "dddd dddd" + EOL + hf.createPadding(nextLineTabStop) + "dddd dddd" + EOL + lpad + "-b " + dpad
+ + "feeee eeee" + EOL + hf.createPadding(nextLineTabStop) + "eeee eeee";
+ sb.setLength(0);
+ hf.renderOptions(sb, 25, options, leftPad, descPad);
+ assertEquals("multiple wrapped options", expected, sb.toString());
}
@Test
@@ -346,222 +388,180 @@ public class HelpFormatterTest {
}
@Test
- public void testDefaultArgName() {
- final Option option = Option.builder("f").hasArg().required(true).build();
+ public void testPrintRequiredOptionGroupUsage() {
+ final OptionGroup group = new OptionGroup();
+ group.addOption(Option.builder("a").build());
+ group.addOption(Option.builder("b").build());
+ group.addOption(Option.builder("c").build());
+ group.setRequired(true);
final Options options = new Options();
- options.addOption(option);
+ options.addOptionGroup(group);
final StringWriter out = new StringWriter();
final HelpFormatter formatter = new HelpFormatter();
- formatter.setArgName("argument");
formatter.printUsage(new PrintWriter(out), 80, "app", options);
- assertEquals("usage: app -f <argument>" + EOL, out.toString());
- }
-
- @Test
- public void testRtrim() {
- final HelpFormatter formatter = new HelpFormatter();
-
- assertEquals(null, formatter.rtrim(null));
- assertEquals("", formatter.rtrim(""));
- assertEquals(" foo", formatter.rtrim(" foo "));
+ assertEquals("usage: app -a | -b | -c" + EOL, out.toString());
}
+ // uses the test for CLI-131 to implement CLI-155
@Test
- public void testAccessors() {
- final HelpFormatter formatter = new HelpFormatter();
-
- formatter.setArgName("argname");
- assertEquals("arg name", "argname", formatter.getArgName());
+ public void testPrintSortedUsage() {
+ final Options opts = new Options();
+ opts.addOption(new Option("a", "first"));
+ opts.addOption(new Option("b", "second"));
+ opts.addOption(new Option("c", "third"));
- formatter.setDescPadding(3);
- assertEquals("desc padding", 3, formatter.getDescPadding());
+ final HelpFormatter helpFormatter = new HelpFormatter();
+ helpFormatter.setOptionComparator(new Comparator<Option>() {
+ @Override
+ public int compare(final Option opt1, final Option opt2) {
+ // reverses the functionality of the default comparator
+ return opt2.getKey().compareToIgnoreCase(opt1.getKey());
+ }
+ });
- formatter.setLeftPadding(7);
- assertEquals("left padding", 7, formatter.getLeftPadding());
+ final StringWriter out = new StringWriter();
+ helpFormatter.printUsage(new PrintWriter(out), 80, "app", opts);
- formatter.setLongOptPrefix("~~");
- assertEquals("long opt prefix", "~~", formatter.getLongOptPrefix());
+ assertEquals("usage: app [-c] [-b] [-a]" + EOL, out.toString());
+ }
- formatter.setNewLine("\n");
- assertEquals("new line", "\n", formatter.getNewLine());
+ @Test
+ public void testPrintSortedUsageWithNullComparator() {
+ final Options opts = new Options();
+ opts.addOption(new Option("c", "first"));
+ opts.addOption(new Option("b", "second"));
+ opts.addOption(new Option("a", "third"));
- formatter.setOptPrefix("~");
- assertEquals("opt prefix", "~", formatter.getOptPrefix());
+ final HelpFormatter helpFormatter = new HelpFormatter();
+ helpFormatter.setOptionComparator(null);
- formatter.setSyntaxPrefix("-> ");
- assertEquals("syntax prefix", "-> ", formatter.getSyntaxPrefix());
+ final StringWriter out = new StringWriter();
+ helpFormatter.printUsage(new PrintWriter(out), 80, "app", opts);
- formatter.setWidth(80);
- assertEquals("width", 80, formatter.getWidth());
+ assertEquals("usage: app [-c] [-b] [-a]" + EOL, out.toString());
}
+ // This test ensures the options are properly sorted
+ // See https://issues.apache.org/jira/browse/CLI-131
@Test
- public void testHeaderStartingWithLineSeparator() {
- // related to Bugzilla #21215
- final Options options = new Options();
- final HelpFormatter formatter = new HelpFormatter();
- final String header = EOL + "Header";
- final String footer = "Footer";
- final StringWriter out = new StringWriter();
- formatter.printHelp(new PrintWriter(out), 80, "foobar", header, options, 2, 2, footer, true);
- //@formatter:off
- assertEquals(
- "usage: foobar" + EOL +
- "" + EOL +
- "Header" + EOL +
- "" + EOL +
- "Footer" + EOL,
- out.toString());
- //@formatter:on
+ public void testPrintUsage() {
+ final Option optionA = new Option("a", "first");
+ final Option optionB = new Option("b", "second");
+ final Option optionC = new Option("c", "third");
+ final Options opts = new Options();
+ opts.addOption(optionA);
+ opts.addOption(optionB);
+ opts.addOption(optionC);
+ final HelpFormatter helpFormatter = new HelpFormatter();
+ final ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
+ final PrintWriter printWriter = new PrintWriter(bytesOut);
+ helpFormatter.printUsage(printWriter, 80, "app", opts);
+ printWriter.close();
+ assertEquals("usage: app [-a] [-b] [-c]" + EOL, bytesOut.toString());
}
@Test
- public void testIndentedHeaderAndFooter() {
- // related to CLI-207
- final Options options = new Options();
- final HelpFormatter formatter = new HelpFormatter();
- final String header = " Header1\n Header2";
- final String footer = " Footer1\n Footer2";
- final StringWriter out = new StringWriter();
- formatter.printHelp(new PrintWriter(out), 80, "foobar", header, options, 2, 2, footer, true);
+ public void testRenderWrappedTextMultiLine() {
+ // multi line text
+ final int width = 16;
+ final int padding = 0;
//@formatter:off
- assertEquals(
- "usage: foobar" + EOL +
- " Header1" + EOL +
- " Header2" + EOL +
- "" + EOL +
- " Footer1" + EOL +
- " Footer2" + EOL,
- out.toString());
+ final String expected = "aaaa aaaa aaaa" + EOL +
+ "aaaaaa" + EOL +
+ "aaaaa";
//@formatter:on
+
+ final StringBuffer sb = new StringBuffer();
+ new HelpFormatter().renderWrappedText(sb, width, padding, expected);
+ assertEquals("multi line text", expected, sb.toString());
}
@Test
- public void testOptionWithoutShortFormat() {
- // related to Bugzilla #19383 (CLI-67)
- final Options options = new Options();
- options.addOption(new Option("a", "aaa", false, "aaaaaaa"));
- options.addOption(new Option(null, "bbb", false, "bbbbbbb"));
- options.addOption(new Option("c", null, false, "ccccccc"));
-
- final HelpFormatter formatter = new HelpFormatter();
- final StringWriter out = new StringWriter();
- formatter.printHelp(new PrintWriter(out), 80, "foobar", "", options, 2, 2, "", true);
+ public void testRenderWrappedTextMultiLinePadded() {
+ // multi-line padded text
+ final int width = 16;
+ final int padding = 4;
//@formatter:off
- assertEquals(
- "usage: foobar [-a] [--bbb] [-c]" + EOL +
- " -a,--aaa aaaaaaa" + EOL +
- " --bbb bbbbbbb" + EOL +
- " -c ccccccc" + EOL,
- out.toString());
+ final String text = "aaaa aaaa aaaa" + EOL +
+ "aaaaaa" + EOL +
+ "aaaaa";
+ final String expected = "aaaa aaaa aaaa" + EOL +
+ " aaaaaa" + EOL +
+ " aaaaa";
//@formatter:on
+
+ final StringBuffer sb = new StringBuffer();
+ new HelpFormatter().renderWrappedText(sb, width, padding, text);
+ assertEquals("multi-line padded text", expected, sb.toString());
}
@Test
- public void testOptionWithoutShortFormat2() {
- // related to Bugzilla #27635 (CLI-26)
- final Option help = new Option("h", "help", false, "print this message");
- final Option version = new Option("v", "version", false, "print version information");
- final Option newRun = new Option("n", "new", false, "Create NLT cache entries only for new items");
- final Option trackerRun = new Option("t", "tracker", false, "Create NLT cache entries only for tracker items");
-
- //@formatter:off
- final Option timeLimit = Option.builder("l")
- .longOpt("limit")
- .hasArg()
- .valueSeparator()
- .desc("Set time limit for execution, in mintues")
- .build();
-
- final Option age = Option.builder("a").longOpt("age")
- .hasArg()
- .valueSeparator()
- .desc("Age (in days) of cache item before being recomputed")
- .build();
-
- final Option server = Option.builder("s").longOpt("server")
- .hasArg()
- .valueSeparator()
- .desc("The NLT server address")
- .build();
+ public void testRenderWrappedTextSingleLine() {
+ // single line text
+ final int width = 12;
+ final int padding = 0;
+ final String text = "This is a test.";
+ final String expected = "This is a" + EOL + "test.";
- final Option numResults = Option.builder("r").longOpt("results")
- .hasArg()
- .valueSeparator()
- .desc("Number of results per item")
- .build();
+ final StringBuffer sb = new StringBuffer();
+ new HelpFormatter().renderWrappedText(sb, width, padding, text);
+ assertEquals("single line text", expected, sb.toString());
+ }
- final Option configFile = Option.builder().longOpt("config")
- .hasArg()
- .valueSeparator()
- .desc("Use the specified configuration file")
- .build();
- //@formatter:on
+ @Test
+ public void testRenderWrappedTextSingleLinePadded() {
+ // single line padded text
+ final int width = 12;
+ final int padding = 4;
+ final String text = "This is a test.";
+ final String expected = "This is a" + EOL + " test.";
- final Options mOptions = new Options();
- mOptions.addOption(help);
- mOptions.addOption(version);
- mOptions.addOption(newRun);
- mOptions.addOption(trackerRun);
- mOptions.addOption(timeLimit);
- mOptions.addOption(age);
- mOptions.addOption(server);
- mOptions.addOption(numResults);
- mOptions.addOption(configFile);
+ final StringBuffer sb = new StringBuffer();
+ new HelpFormatter().renderWrappedText(sb, width, padding, text);
+ assertEquals("single line padded text", expected, sb.toString());
+ }
- final HelpFormatter formatter = new HelpFormatter();
- final String eol = System.getProperty("line.separator");
- final StringWriter out = new StringWriter();
- formatter.printHelp(new PrintWriter(out), 80, "commandline", "header", mOptions, 2, 2, "footer", true);
+ @Test
+ public void testRenderWrappedTextSingleLinePadded2() {
+ // single line padded text 2
+ final int width = 53;
+ final int padding = 24;
//@formatter:off
- assertEquals(
- "usage: commandline [-a <arg>] [--config <arg>] [-h] [-l <arg>] [-n] [-r <arg>]" + eol +
- " [-s <arg>] [-t] [-v]" + eol +
- "header" + eol +
- " -a,--age <arg> Age (in days) of cache item before being recomputed" + eol +
- " --config <arg> Use the specified configuration file" + eol +
- " -h,--help print this message" + eol +
- " -l,--limit <arg> Set time limit for execution, in mintues" + eol +
- " -n,--new Create NLT cache entries only for new items" + eol +
- " -r,--results <arg> Number of results per item" + eol +
- " -s,--server <arg> The NLT server address" + eol +
- " -t,--tracker Create NLT cache entries only for tracker items" + eol +
- " -v,--version print version information" + eol +
- "footer" + eol,
- out.toString());
+ final String text = " -p,--period <PERIOD> PERIOD is time duration of form " +
+ "DATE[-DATE] where DATE has form YYYY[MM[DD]]";
+ final String expected = " -p,--period <PERIOD> PERIOD is time duration of" + EOL +
+ " form DATE[-DATE] where DATE" + EOL +
+ " has form YYYY[MM[DD]]";
//@formatter:on
+
+ final StringBuffer sb = new StringBuffer();
+ new HelpFormatter().renderWrappedText(sb, width, padding, text);
+ assertEquals("single line padded text 2", expected, sb.toString());
}
@Test
- public void testHelpWithLongOptSeparator() throws Exception {
- final Options options = new Options();
- options.addOption("f", true, "the file");
- options.addOption(Option.builder("s").longOpt("size").desc("the size").hasArg().argName("SIZE").build());
- options.addOption(Option.builder().longOpt("age").desc("the age").hasArg().build());
-
- final HelpFormatter formatter = new HelpFormatter();
- assertEquals(HelpFormatter.DEFAULT_LONG_OPT_SEPARATOR, formatter.getLongOptSeparator());
- formatter.setLongOptSeparator("=");
- assertEquals("=", formatter.getLongOptSeparator());
+ public void testRenderWrappedTextWordCut() {
+ final int width = 7;
+ final int padding = 0;
+ final String text = "Thisisatest.";
+ final String expected = "Thisisa" + EOL + "test.";
- final StringWriter out = new StringWriter();
+ final StringBuffer sb = new StringBuffer();
+ new HelpFormatter().renderWrappedText(sb, width, padding, text);
+ assertEquals("cut and wrap", expected, sb.toString());
+ }
- formatter.printHelp(new PrintWriter(out), 80, "create", "header", options, 2, 2, "footer");
+ @Test
+ public void testRtrim() {
+ final HelpFormatter formatter = new HelpFormatter();
- //@formatter:off
- assertEquals(
- "usage: create" + EOL +
- "header" + EOL +
- " --age=<arg> the age" + EOL +
- " -f <arg> the file" + EOL +
- " -s,--size=<SIZE> the size" + EOL +
- "footer" + EOL,
- out.toString());
- //@formatter:on
+ assertEquals(null, formatter.rtrim(null));
+ assertEquals("", formatter.rtrim(""));
+ assertEquals(" foo", formatter.rtrim(" foo "));
}
@Test
diff --git a/src/test/java/org/apache/commons/cli/OptionBuilderTest.java b/src/test/java/org/apache/commons/cli/OptionBuilderTest.java
index fe8ffae..d976b77 100644
--- a/src/test/java/org/apache/commons/cli/OptionBuilderTest.java
+++ b/src/test/java/org/apache/commons/cli/OptionBuilderTest.java
@@ -27,63 +27,6 @@ import org.junit.Test;
@SuppressWarnings("deprecation") // OptionBuilder is marked deprecated
public class OptionBuilderTest {
@Test
- public void testCompleteOption() {
- //@formatter:off
- final Option simple = OptionBuilder.withLongOpt("simple option")
- .hasArg()
- .isRequired()
- .hasArgs()
- .withType(Float.class)
- .withDescription("this is a simple option")
- .create('s');
- //@formatter:on
-
- assertEquals("s", simple.getOpt());
- assertEquals("simple option", simple.getLongOpt());
- assertEquals("this is a simple option", simple.getDescription());
- assertEquals(simple.getType(), Float.class);
- assertTrue(simple.hasArg());
- assertTrue(simple.isRequired());
- assertTrue(simple.hasArgs());
- }
-
- @Test
- public void testTwoCompleteOptions() {
- //@formatter:off
- Option simple = OptionBuilder.withLongOpt("simple option")
- .hasArg()
- .isRequired()
- .hasArgs()
- .withType(Float.class)
- .withDescription("this is a simple option")
- .create('s');
- //@formatter:on
-
- assertEquals("s", simple.getOpt());
- assertEquals("simple option", simple.getLongOpt());
- assertEquals("this is a simple option", simple.getDescription());
- assertEquals(simple.getType(), Float.class);
- assertTrue(simple.hasArg());
- assertTrue(simple.isRequired());
- assertTrue(simple.hasArgs());
-
- //@formatter:off
- simple = OptionBuilder.withLongOpt("dimple option")
- .hasArg()
- .withDescription("this is a dimple option")
- .create('d');
- //@formatter:on
-
- assertEquals("d", simple.getOpt());
- assertEquals("dimple option", simple.getLongOpt());
- assertEquals("this is a dimple option", simple.getDescription());
- assertEquals(String.class, simple.getType());
- assertTrue(simple.hasArg());
- assertTrue(!simple.isRequired());
- assertTrue(!simple.hasArgs());
- }
-
- @Test
public void testBaseOptionCharOpt() {
final Option base = OptionBuilder.withDescription("option description").create('o');
@@ -102,32 +45,56 @@ public class OptionBuilderTest {
}
@Test
- public void testSpecialOptChars() throws Exception {
- // '?'
- final Option opt1 = OptionBuilder.withDescription("help options").create('?');
- assertEquals("?", opt1.getOpt());
-
- // '@'
- final Option opt2 = OptionBuilder.withDescription("read from stdin").create('@');
- assertEquals("@", opt2.getOpt());
+ public void testBuilderIsResettedAlways() {
+ try {
+ OptionBuilder.withDescription("JUnit").create('"');
+ fail("IllegalArgumentException expected");
+ } catch (final IllegalArgumentException e) {
+ // expected
+ }
+ assertNull("we inherited a description", OptionBuilder.create('x').getDescription());
- // ' '
try {
- OptionBuilder.create(' ');
- fail("IllegalArgumentException not caught");
+ OptionBuilder.withDescription("JUnit").create();
+ fail("IllegalArgumentException expected");
} catch (final IllegalArgumentException e) {
- // success
+ // expected
}
+ assertNull("we inherited a description", OptionBuilder.create('x').getDescription());
}
@Test
- public void testOptionArgNumbers() {
+ public void testCompleteOption() {
//@formatter:off
- final Option opt = OptionBuilder.withDescription("option description")
- .hasArgs(2)
- .create('o');
+ final Option simple = OptionBuilder.withLongOpt("simple option")
+ .hasArg()
+ .isRequired()
+ .hasArgs()
+ .withType(Float.class)
+ .withDescription("this is a simple option")
+ .create('s');
//@formatter:on
- assertEquals(2, opt.getArgs());
+
+ assertEquals("s", simple.getOpt());
+ assertEquals("simple option", simple.getLongOpt());
+ assertEquals("this is a simple option", simple.getDescription());
+ assertEquals(simple.getType(), Float.class);
+ assertTrue(simple.hasArg());
+ assertTrue(simple.isRequired());
+ assertTrue(simple.hasArgs());
+ }
+
+ @Test
+ public void testCreateIncompleteOption() {
+ try {
+ OptionBuilder.hasArg().create();
+ fail("Incomplete option should be rejected");
+ } catch (final IllegalArgumentException e) {
+ // expected
+
+ // implicitly reset the builder
+ OptionBuilder.create("opt");
+ }
}
@Test
@@ -158,34 +125,67 @@ public class OptionBuilderTest {
}
@Test
- public void testCreateIncompleteOption() {
- try {
- OptionBuilder.hasArg().create();
- fail("Incomplete option should be rejected");
- } catch (final IllegalArgumentException e) {
- // expected
-
- // implicitly reset the builder
- OptionBuilder.create("opt");
- }
+ public void testOptionArgNumbers() {
+ //@formatter:off
+ final Option opt = OptionBuilder.withDescription("option description")
+ .hasArgs(2)
+ .create('o');
+ //@formatter:on
+ assertEquals(2, opt.getArgs());
}
@Test
- public void testBuilderIsResettedAlways() {
- try {
- OptionBuilder.withDescription("JUnit").create('"');
- fail("IllegalArgumentException expected");
- } catch (final IllegalArgumentException e) {
- // expected
- }
- assertNull("we inherited a description", OptionBuilder.create('x').getDescription());
+ public void testSpecialOptChars() throws Exception {
+ // '?'
+ final Option opt1 = OptionBuilder.withDescription("help options").create('?');
+ assertEquals("?", opt1.getOpt());
+ // '@'
+ final Option opt2 = OptionBuilder.withDescription("read from stdin").create('@');
+ assertEquals("@", opt2.getOpt());
+
+ // ' '
try {
- OptionBuilder.withDescription("JUnit").create();
- fail("IllegalArgumentException expected");
+ OptionBuilder.create(' ');
+ fail("IllegalArgumentException not caught");
} catch (final IllegalArgumentException e) {
- // expected
+ // success
}
- assertNull("we inherited a description", OptionBuilder.create('x').getDescription());
+ }
+
+ @Test
+ public void testTwoCompleteOptions() {
+ //@formatter:off
+ Option simple = OptionBuilder.withLongOpt("simple option")
+ .hasArg()
+ .isRequired()
+ .hasArgs()
+ .withType(Float.class)
+ .withDescription("this is a simple option")
+ .create('s');
+ //@formatter:on
+
+ assertEquals("s", simple.getOpt());
+ assertEquals("simple option", simple.getLongOpt());
+ assertEquals("this is a simple option", simple.getDescription());
+ assertEquals(simple.getType(), Float.class);
+ assertTrue(simple.hasArg());
+ assertTrue(simple.isRequired());
+ assertTrue(simple.hasArgs());
+
+ //@formatter:off
+ simple = OptionBuilder.withLongOpt("dimple option")
+ .hasArg()
+ .withDescription("this is a dimple option")
+ .create('d');
+ //@formatter:on
+
+ assertEquals("d", simple.getOpt());
+ assertEquals("dimple option", simple.getLongOpt());
+ assertEquals("this is a dimple option", simple.getDescription());
+ assertEquals(String.class, simple.getType());
+ assertTrue(simple.hasArg());
+ assertTrue(!simple.isRequired());
+ assertTrue(!simple.hasArgs());
}
}
diff --git a/src/test/java/org/apache/commons/cli/OptionGroupTest.java b/src/test/java/org/apache/commons/cli/OptionGroupTest.java
index 4444e82..bbfe9df 100644
--- a/src/test/java/org/apache/commons/cli/OptionGroupTest.java
+++ b/src/test/java/org/apache/commons/cli/OptionGroupTest.java
@@ -60,45 +60,29 @@ public class OptionGroupTest {
}
@Test
- public void testSingleOptionFromGroup() throws Exception {
- final String[] args = {"-f"};
-
- final CommandLine cl = parser.parse(options, args);
+ public void testGetNames() {
+ final OptionGroup group = new OptionGroup();
+ group.addOption(OptionBuilder.create('a'));
+ group.addOption(OptionBuilder.create('b'));
- assertTrue("Confirm -r is NOT set", !cl.hasOption("r"));
- assertTrue("Confirm -f is set", cl.hasOption("f"));
- assertTrue("Confirm -d is NOT set", !cl.hasOption("d"));
- assertTrue("Confirm -s is NOT set", !cl.hasOption("s"));
- assertTrue("Confirm -c is NOT set", !cl.hasOption("c"));
- assertTrue("Confirm no extra args", cl.getArgList().isEmpty());
+ assertNotNull("null names", group.getNames());
+ assertEquals(2, group.getNames().size());
+ assertTrue(group.getNames().contains("a"));
+ assertTrue(group.getNames().contains("b"));
}
@Test
- public void testSingleOption() throws Exception {
- final String[] args = {"-r"};
+ public void testNoOptionsExtraArgs() throws Exception {
+ final String[] args = {"arg1", "arg2"};
final CommandLine cl = parser.parse(options, args);
- assertTrue("Confirm -r is set", cl.hasOption("r"));
+ assertTrue("Confirm -r is NOT set", !cl.hasOption("r"));
assertTrue("Confirm -f is NOT set", !cl.hasOption("f"));
assertTrue("Confirm -d is NOT set", !cl.hasOption("d"));
assertTrue("Confirm -s is NOT set", !cl.hasOption("s"));
assertTrue("Confirm -c is NOT set", !cl.hasOption("c"));
- assertTrue("Confirm no extra args", cl.getArgList().isEmpty());
- }
-
- @Test
- public void testTwoValidOptions() throws Exception {
- final String[] args = {"-r", "-f"};
-
- final CommandLine cl = parser.parse(options, args);
-
- assertTrue("Confirm -r is set", cl.hasOption("r"));
- assertTrue("Confirm -f is set", cl.hasOption("f"));
- assertTrue("Confirm -d is NOT set", !cl.hasOption("d"));
- assertTrue("Confirm -s is NOT set", !cl.hasOption("s"));
- assertTrue("Confirm -c is NOT set", !cl.hasOption("c"));
- assertTrue("Confirm no extra args", cl.getArgList().isEmpty());
+ assertTrue("Confirm TWO extra args", cl.getArgList().size() == 2);
}
@Test
@@ -116,13 +100,13 @@ public class OptionGroupTest {
}
@Test
- public void testTwoValidLongOptions() throws Exception {
- final String[] args = {"--revision", "--file"};
+ public void testSingleOption() throws Exception {
+ final String[] args = {"-r"};
final CommandLine cl = parser.parse(options, args);
assertTrue("Confirm -r is set", cl.hasOption("r"));
- assertTrue("Confirm -f is set", cl.hasOption("f"));
+ assertTrue("Confirm -f is NOT set", !cl.hasOption("f"));
assertTrue("Confirm -d is NOT set", !cl.hasOption("d"));
assertTrue("Confirm -s is NOT set", !cl.hasOption("s"));
assertTrue("Confirm -c is NOT set", !cl.hasOption("c"));
@@ -130,30 +114,35 @@ public class OptionGroupTest {
}
@Test
- public void testNoOptionsExtraArgs() throws Exception {
- final String[] args = {"arg1", "arg2"};
+ public void testSingleOptionFromGroup() throws Exception {
+ final String[] args = {"-f"};
final CommandLine cl = parser.parse(options, args);
assertTrue("Confirm -r is NOT set", !cl.hasOption("r"));
- assertTrue("Confirm -f is NOT set", !cl.hasOption("f"));
+ assertTrue("Confirm -f is set", cl.hasOption("f"));
assertTrue("Confirm -d is NOT set", !cl.hasOption("d"));
assertTrue("Confirm -s is NOT set", !cl.hasOption("s"));
assertTrue("Confirm -c is NOT set", !cl.hasOption("c"));
- assertTrue("Confirm TWO extra args", cl.getArgList().size() == 2);
+ assertTrue("Confirm no extra args", cl.getArgList().isEmpty());
}
@Test
- public void testTwoOptionsFromGroup() throws Exception {
- final String[] args = {"-f", "-d"};
+ public void testToString() {
+ final OptionGroup group1 = new OptionGroup();
+ group1.addOption(new Option(null, "foo", false, "Foo"));
+ group1.addOption(new Option(null, "bar", false, "Bar"));
- try {
- parser.parse(options, args);
- fail("two arguments from group not allowed");
- } catch (final AlreadySelectedException e) {
- assertNotNull("null option group", e.getOptionGroup());
- assertEquals("selected option", "f", e.getOptionGroup().getSelected());
- assertEquals("option", "d", e.getOption().getOpt());
+ if (!"[--bar Bar, --foo Foo]".equals(group1.toString())) {
+ assertEquals("[--foo Foo, --bar Bar]", group1.toString());
+ }
+
+ final OptionGroup group2 = new OptionGroup();
+ group2.addOption(new Option("f", "foo", false, "Foo"));
+ group2.addOption(new Option("b", "bar", false, "Bar"));
+
+ if (!"[-b Bar, -f Foo]".equals(group2.toString())) {
+ assertEquals("[-f Foo, -b Bar]", group2.toString());
}
}
@@ -185,6 +174,20 @@ public class OptionGroupTest {
}
@Test
+ public void testTwoOptionsFromGroup() throws Exception {
+ final String[] args = {"-f", "-d"};
+
+ try {
+ parser.parse(options, args);
+ fail("two arguments from group not allowed");
+ } catch (final AlreadySelectedException e) {
+ assertNotNull("null option group", e.getOptionGroup());
+ assertEquals("selected option", "f", e.getOptionGroup().getSelected());
+ assertEquals("option", "d", e.getOption().getOpt());
+ }
+ }
+
+ @Test
public void testTwoOptionsFromGroupWithProperties() throws Exception {
final String[] args = {"-f"};
@@ -197,42 +200,39 @@ public class OptionGroupTest {
}
@Test
- public void testValidLongOnlyOptions() throws Exception {
- final CommandLine cl1 = parser.parse(options, new String[] {"--export"});
- assertTrue("Confirm --export is set", cl1.hasOption("export"));
+ public void testTwoValidLongOptions() throws Exception {
+ final String[] args = {"--revision", "--file"};
- final CommandLine cl2 = parser.parse(options, new String[] {"--import"});
- assertTrue("Confirm --import is set", cl2.hasOption("import"));
+ final CommandLine cl = parser.parse(options, args);
+
+ assertTrue("Confirm -r is set", cl.hasOption("r"));
+ assertTrue("Confirm -f is set", cl.hasOption("f"));
+ assertTrue("Confirm -d is NOT set", !cl.hasOption("d"));
+ assertTrue("Confirm -s is NOT set", !cl.hasOption("s"));
+ assertTrue("Confirm -c is NOT set", !cl.hasOption("c"));
+ assertTrue("Confirm no extra args", cl.getArgList().isEmpty());
}
@Test
- public void testToString() {
- final OptionGroup group1 = new OptionGroup();
- group1.addOption(new Option(null, "foo", false, "Foo"));
- group1.addOption(new Option(null, "bar", false, "Bar"));
-
- if (!"[--bar Bar, --foo Foo]".equals(group1.toString())) {
- assertEquals("[--foo Foo, --bar Bar]", group1.toString());
- }
+ public void testTwoValidOptions() throws Exception {
+ final String[] args = {"-r", "-f"};
- final OptionGroup group2 = new OptionGroup();
- group2.addOption(new Option("f", "foo", false, "Foo"));
- group2.addOption(new Option("b", "bar", false, "Bar"));
+ final CommandLine cl = parser.parse(options, args);
- if (!"[-b Bar, -f Foo]".equals(group2.toString())) {
- assertEquals("[-f Foo, -b Bar]", group2.toString());
- }
+ assertTrue("Confirm -r is set", cl.hasOption("r"));
+ assertTrue("Confirm -f is set", cl.hasOption("f"));
+ assertTrue("Confirm -d is NOT set", !cl.hasOption("d"));
+ assertTrue("Confirm -s is NOT set", !cl.hasOption("s"));
+ assertTrue("Confirm -c is NOT set", !cl.hasOption("c"));
+ assertTrue("Confirm no extra args", cl.getArgList().isEmpty());
}
@Test
- public void testGetNames() {
- final OptionGroup group = new OptionGroup();
- group.addOption(OptionBuilder.create('a'));
- group.addOption(OptionBuilder.create('b'));
+ public void testValidLongOnlyOptions() throws Exception {
+ final CommandLine cl1 = parser.parse(options, new String[] {"--export"});
+ assertTrue("Confirm --export is set", cl1.hasOption("export"));
- assertNotNull("null names", group.getNames());
- assertEquals(2, group.getNames().size());
- assertTrue(group.getNames().contains("a"));
- assertTrue(group.getNames().contains("b"));
+ final CommandLine cl2 = parser.parse(options, new String[] {"--import"});
+ assertTrue("Confirm --import is set", cl2.hasOption("import"));
}
}
diff --git a/src/test/java/org/apache/commons/cli/OptionTest.java b/src/test/java/org/apache/commons/cli/OptionTest.java
index e04fd18..839cd39 100644
--- a/src/test/java/org/apache/commons/cli/OptionTest.java
+++ b/src/test/java/org/apache/commons/cli/OptionTest.java
@@ -26,6 +26,22 @@ import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class OptionTest {
+ private static class DefaultOption extends Option {
+ private static final long serialVersionUID = 1L;
+
+ private final String defaultValue;
+
+ DefaultOption(final String opt, final String description, final String defaultValue) throws IllegalArgumentException {
+ super(opt, true, description);
+ this.defaultValue = defaultValue;
+ }
+
+ @Override
+ public String getValue() {
+ return super.getValue() != null ? super.getValue() : defaultValue;
+ }
+ }
+
private static class TestOption extends Option {
private static final long serialVersionUID = 1L;
@@ -40,6 +56,60 @@ public class OptionTest {
}
}
+ private static void checkOption(final Option option, final String opt, final String description, final String longOpt, final int numArgs,
+ final String argName, final boolean required, final boolean optionalArg, final char valueSeparator, final Class<?> cls) {
+ assertEquals(opt, option.getOpt());
+ assertEquals(description, option.getDescription());
+ assertEquals(longOpt, option.getLongOpt());
+ assertEquals(numArgs, option.getArgs());
+ assertEquals(argName, option.getArgName());
+ assertEquals(required, option.isRequired());
+
+ assertEquals(optionalArg, option.hasOptionalArg());
+ assertEquals(valueSeparator, option.getValueSeparator());
+ assertEquals(cls, option.getType());
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testBuilderInsufficientParams1() {
+ Option.builder().desc("desc").build();
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testBuilderInsufficientParams2() {
+ Option.builder(null).desc("desc").build();
+ }
+
+ @Test
+ public void testBuilderMethods() {
+ final char defaultSeparator = (char) 0;
+
+ checkOption(Option.builder("a").desc("desc").build(), "a", "desc", null, Option.UNINITIALIZED, null, false, false, defaultSeparator, String.class);
+ checkOption(Option.builder("a").desc("desc").build(), "a", "desc", null, Option.UNINITIALIZED, null, false, false, defaultSeparator, String.class);
+ checkOption(Option.builder("a").desc("desc").longOpt("aaa").build(), "a", "desc", "aaa", Option.UNINITIALIZED, null, false, false, defaultSeparator,
+ String.class);
+ checkOption(Option.builder("a").desc("desc").hasArg(true).build(), "a", "desc", null, 1, null, false, false, defaultSeparator, String.class);
+ checkOption(Option.builder("a").desc("desc").hasArg(false).build(), "a", "desc", null, Option.UNINITIALIZED, null, false, false, defaultSeparator,
+ String.class);
+ checkOption(Option.builder("a").desc("desc").hasArg(true).build(), "a", "desc", null, 1, null, false, false, defaultSeparator, String.class);
+ checkOption(Option.builder("a").desc("desc").numberOfArgs(3).build(), "a", "desc", null, 3, null, false, false, defaultSeparator, String.class);
+ checkOption(Option.builder("a").desc("desc").required(true).build(), "a", "desc", null, Option.UNINITIALIZED, null, true, false, defaultSeparator,
+ String.class);
+ checkOption(Option.builder("a").desc("desc").required(false).build(), "a", "desc", null, Option.UNINITIALIZED, null, false, false, defaultSeparator,
+ String.class);
+
+ checkOption(Option.builder("a").desc("desc").argName("arg1").build(), "a", "desc", null, Option.UNINITIALIZED, "arg1", false, false, defaultSeparator,
+ String.class);
+ checkOption(Option.builder("a").desc("desc").optionalArg(false).build(), "a", "desc", null, Option.UNINITIALIZED, null, false, false, defaultSeparator,
+ String.class);
+ checkOption(Option.builder("a").desc("desc").optionalArg(true).build(), "a", "desc", null, Option.UNINITIALIZED, null, false, true, defaultSeparator,
+ String.class);
+ checkOption(Option.builder("a").desc("desc").valueSeparator(':').build(), "a", "desc", null, Option.UNINITIALIZED, null, false, false, ':',
+ String.class);
+ checkOption(Option.builder("a").desc("desc").type(Integer.class).build(), "a", "desc", null, Option.UNINITIALIZED, null, false, false, defaultSeparator,
+ Integer.class);
+ }
+
@Test
public void testClear() {
final TestOption option = new TestOption("x", true, "");
@@ -68,34 +138,18 @@ public class OptionTest {
}
@Test
- public void testHashCode() {
- assertNotEquals(Option.builder("test").build().hashCode(), Option.builder("test2").build().hashCode());
- assertNotEquals(Option.builder("test").build().hashCode(), Option.builder().longOpt("test").build().hashCode());
- assertNotEquals(Option.builder("test").build().hashCode(), Option.builder("test").longOpt("long test").build().hashCode());
- }
-
- private static class DefaultOption extends Option {
- private static final long serialVersionUID = 1L;
-
- private final String defaultValue;
+ public void testGetValue() {
+ final Option option = new Option("f", null);
+ option.setArgs(Option.UNLIMITED_VALUES);
- DefaultOption(final String opt, final String description, final String defaultValue) throws IllegalArgumentException {
- super(opt, true, description);
- this.defaultValue = defaultValue;
- }
+ assertEquals("default", option.getValue("default"));
+ assertEquals(null, option.getValue(0));
- @Override
- public String getValue() {
- return super.getValue() != null ? super.getValue() : defaultValue;
- }
- }
+ option.addValueForProcessing("foo");
- @Test
- public void testSubclass() {
- final Option option = new DefaultOption("f", "file", "myfile.txt");
- final Option clone = (Option) option.clone();
- assertEquals("myfile.txt", clone.getValue());
- assertEquals(DefaultOption.class, clone.getClass());
+ assertEquals("foo", option.getValue());
+ assertEquals("foo", option.getValue(0));
+ assertEquals("foo", option.getValue("default"));
}
@Test
@@ -133,72 +187,18 @@ public class OptionTest {
}
@Test
- public void testGetValue() {
- final Option option = new Option("f", null);
- option.setArgs(Option.UNLIMITED_VALUES);
-
- assertEquals("default", option.getValue("default"));
- assertEquals(null, option.getValue(0));
-
- option.addValueForProcessing("foo");
-
- assertEquals("foo", option.getValue());
- assertEquals("foo", option.getValue(0));
- assertEquals("foo", option.getValue("default"));
+ public void testHashCode() {
+ assertNotEquals(Option.builder("test").build().hashCode(), Option.builder("test2").build().hashCode());
+ assertNotEquals(Option.builder("test").build().hashCode(), Option.builder().longOpt("test").build().hashCode());
+ assertNotEquals(Option.builder("test").build().hashCode(), Option.builder("test").longOpt("long test").build().hashCode());
}
@Test
- public void testBuilderMethods() {
- final char defaultSeparator = (char) 0;
-
- checkOption(Option.builder("a").desc("desc").build(), "a", "desc", null, Option.UNINITIALIZED, null, false, false, defaultSeparator, String.class);
- checkOption(Option.builder("a").desc("desc").build(), "a", "desc", null, Option.UNINITIALIZED, null, false, false, defaultSeparator, String.class);
- checkOption(Option.builder("a").desc("desc").longOpt("aaa").build(), "a", "desc", "aaa", Option.UNINITIALIZED, null, false, false, defaultSeparator,
- String.class);
- checkOption(Option.builder("a").desc("desc").hasArg(true).build(), "a", "desc", null, 1, null, false, false, defaultSeparator, String.class);
- checkOption(Option.builder("a").desc("desc").hasArg(false).build(), "a", "desc", null, Option.UNINITIALIZED, null, false, false, defaultSeparator,
- String.class);
- checkOption(Option.builder("a").desc("desc").hasArg(true).build(), "a", "desc", null, 1, null, false, false, defaultSeparator, String.class);
- checkOption(Option.builder("a").desc("desc").numberOfArgs(3).build(), "a", "desc", null, 3, null, false, false, defaultSeparator, String.class);
- checkOption(Option.builder("a").desc("desc").required(true).build(), "a", "desc", null, Option.UNINITIALIZED, null, true, false, defaultSeparator,
- String.class);
- checkOption(Option.builder("a").desc("desc").required(false).build(), "a", "desc", null, Option.UNINITIALIZED, null, false, false, defaultSeparator,
- String.class);
-
- checkOption(Option.builder("a").desc("desc").argName("arg1").build(), "a", "desc", null, Option.UNINITIALIZED, "arg1", false, false, defaultSeparator,
- String.class);
- checkOption(Option.builder("a").desc("desc").optionalArg(false).build(), "a", "desc", null, Option.UNINITIALIZED, null, false, false, defaultSeparator,
- String.class);
- checkOption(Option.builder("a").desc("desc").optionalArg(true).build(), "a", "desc", null, Option.UNINITIALIZED, null, false, true, defaultSeparator,
- String.class);
- checkOption(Option.builder("a").desc("desc").valueSeparator(':').build(), "a", "desc", null, Option.UNINITIALIZED, null, false, false, ':',
- String.class);
- checkOption(Option.builder("a").desc("desc").type(Integer.class).build(), "a", "desc", null, Option.UNINITIALIZED, null, false, false, defaultSeparator,
- Integer.class);
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void testBuilderInsufficientParams1() {
- Option.builder().desc("desc").build();
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void testBuilderInsufficientParams2() {
- Option.builder(null).desc("desc").build();
- }
-
- private static void checkOption(final Option option, final String opt, final String description, final String longOpt, final int numArgs,
- final String argName, final boolean required, final boolean optionalArg, final char valueSeparator, final Class<?> cls) {
- assertEquals(opt, option.getOpt());
- assertEquals(description, option.getDescription());
- assertEquals(longOpt, option.getLongOpt());
- assertEquals(numArgs, option.getArgs());
- assertEquals(argName, option.getArgName());
- assertEquals(required, option.isRequired());
-
- assertEquals(optionalArg, option.hasOptionalArg());
- assertEquals(valueSeparator, option.getValueSeparator());
- assertEquals(cls, option.getType());
+ public void testSubclass() {
+ final Option option = new DefaultOption("f", "file", "myfile.txt");
+ final Option clone = (Option) option.clone();
+ assertEquals("myfile.txt", clone.getValue());
+ assertEquals(DefaultOption.class, clone.getClass());
}
}
diff --git a/src/test/java/org/apache/commons/cli/OptionsTest.java b/src/test/java/org/apache/commons/cli/OptionsTest.java
index 9082ef0..8452cba 100644
--- a/src/test/java/org/apache/commons/cli/OptionsTest.java
+++ b/src/test/java/org/apache/commons/cli/OptionsTest.java
@@ -30,14 +30,11 @@ import org.junit.Test;
@SuppressWarnings("deprecation") // tests some deprecated classes
public class OptionsTest {
@Test
- public void testSimple() {
+ public void testDuplicateLong() {
final Options opts = new Options();
-
- opts.addOption("a", false, "toggle -a");
- opts.addOption("b", true, "toggle -b");
-
- assertTrue(opts.hasOption("a"));
- assertTrue(opts.hasOption("b"));
+ opts.addOption("a", "--a", false, "toggle -a");
+ opts.addOption("a", "--a", false, "toggle -a*");
+ assertEquals("last one in wins", "toggle -a*", opts.getOption("a").getDescription());
}
@Test
@@ -50,22 +47,33 @@ public class OptionsTest {
}
@Test
- public void testLong() {
- final Options opts = new Options();
-
- opts.addOption("a", "--a", false, "toggle -a");
- opts.addOption("b", "--b", true, "set -b");
+ public void testGetMatchingOpts() {
+ final Options options = new Options();
+ options.addOption(OptionBuilder.withLongOpt("version").create());
+ options.addOption(OptionBuilder.withLongOpt("verbose").create());
- assertTrue(opts.hasOption("a"));
- assertTrue(opts.hasOption("b"));
+ assertTrue(options.getMatchingOptions("foo").isEmpty());
+ assertEquals(1, options.getMatchingOptions("version").size());
+ assertEquals(2, options.getMatchingOptions("ver").size());
}
@Test
- public void testDuplicateLong() {
- final Options opts = new Options();
- opts.addOption("a", "--a", false, "toggle -a");
- opts.addOption("a", "--a", false, "toggle -a*");
- assertEquals("last one in wins", "toggle -a*", opts.getOption("a").getDescription());
+ public void testGetOptionsGroups() {
+ final Options options = new Options();
+
+ final OptionGroup group1 = new OptionGroup();
+ group1.addOption(OptionBuilder.create('a'));
+ group1.addOption(OptionBuilder.create('b'));
+
+ final OptionGroup group2 = new OptionGroup();
+ group2.addOption(OptionBuilder.create('x'));
+ group2.addOption(OptionBuilder.create('y'));
+
+ options.addOptionGroup(group1);
+ options.addOptionGroup(group2);
+
+ assertNotNull(options.getOptionGroups());
+ assertEquals(2, options.getOptionGroups().size());
}
@Test
@@ -100,6 +108,17 @@ public class OptionsTest {
}
@Test
+ public void testLong() {
+ final Options opts = new Options();
+
+ opts.addOption("a", "--a", false, "toggle -a");
+ opts.addOption("b", "--b", true, "set -b");
+
+ assertTrue(opts.hasOption("a"));
+ assertTrue(opts.hasOption("b"));
+ }
+
+ @Test
public void testMissingOptionException() throws ParseException {
final Options options = new Options();
options.addOption(OptionBuilder.isRequired().create("f"));
@@ -125,6 +144,17 @@ public class OptionsTest {
}
@Test
+ public void testSimple() {
+ final Options opts = new Options();
+
+ opts.addOption("a", false, "toggle -a");
+ opts.addOption("b", true, "toggle -b");
+
+ assertTrue(opts.hasOption("a"));
+ assertTrue(opts.hasOption("b"));
+ }
+
+ @Test
public void testToString() {
final Options options = new Options();
options.addOption("f", "foo", true, "Foo");
@@ -135,34 +165,4 @@ public class OptionsTest {
assertTrue("foo option missing", s.toLowerCase().contains("foo"));
assertTrue("bar option missing", s.toLowerCase().contains("bar"));
}
-
- @Test
- public void testGetOptionsGroups() {
- final Options options = new Options();
-
- final OptionGroup group1 = new OptionGroup();
- group1.addOption(OptionBuilder.create('a'));
- group1.addOption(OptionBuilder.create('b'));
-
- final OptionGroup group2 = new OptionGroup();
- group2.addOption(OptionBuilder.create('x'));
- group2.addOption(OptionBuilder.create('y'));
-
- options.addOptionGroup(group1);
- options.addOptionGroup(group2);
-
- assertNotNull(options.getOptionGroups());
- assertEquals(2, options.getOptionGroups().size());
- }
-
- @Test
- public void testGetMatchingOpts() {
- final Options options = new Options();
- options.addOption(OptionBuilder.withLongOpt("version").create());
- options.addOption(OptionBuilder.withLongOpt("verbose").create());
-
- assertTrue(options.getMatchingOptions("foo").isEmpty());
- assertEquals(1, options.getMatchingOptions("version").size());
- assertEquals(2, options.getMatchingOptions("ver").size());
- }
}
diff --git a/src/test/java/org/apache/commons/cli/ParserTestCase.java b/src/test/java/org/apache/commons/cli/ParserTestCase.java
index c404c9e..b85adcd 100644
--- a/src/test/java/org/apache/commons/cli/ParserTestCase.java
+++ b/src/test/java/org/apache/commons/cli/ParserTestCase.java
@@ -38,6 +38,17 @@ public abstract class ParserTestCase {
protected Options options;
+ @SuppressWarnings("deprecation")
+ private CommandLine parse(final CommandLineParser parser, final Options opts, final String[] args, final Properties properties) throws ParseException {
+ if (parser instanceof Parser) {
+ return ((Parser) parser).parse(opts, args, properties);
+ }
+ if (parser instanceof DefaultParser) {
+ return ((DefaultParser) parser).parse(opts, args, properties);
+ }
+ throw new UnsupportedOperationException("Default options not supported by this parser");
+ }
+
@Before
public void setUp() {
//@formatter:off
@@ -49,93 +60,130 @@ public abstract class ParserTestCase {
}
@Test
- public void testSimpleShort() throws Exception {
- final String[] args = {"-a", "-b", "toast", "foo", "bar"};
-
- final CommandLine cl = parser.parse(options, args);
-
- assertTrue("Confirm -a is set", cl.hasOption("a"));
- assertTrue("Confirm -b is set", cl.hasOption("b"));
- assertTrue("Confirm arg of -b", cl.getOptionValue("b").equals("toast"));
- assertTrue("Confirm size of extra args", cl.getArgList().size() == 2);
- }
+ public void testAmbiguousLongWithoutEqualSingleDash() throws Exception {
+ final String[] args = {"-b", "-foobar"};
- @Test
- public void testSimpleLong() throws Exception {
- final String[] args = {"--enable-a", "--bfile", "toast", "foo", "bar"};
+ final Options options = new Options();
+ options.addOption(OptionBuilder.withLongOpt("foo").hasOptionalArg().create('f'));
+ options.addOption(OptionBuilder.withLongOpt("bar").hasOptionalArg().create('b'));
final CommandLine cl = parser.parse(options, args);
- assertTrue("Confirm -a is set", cl.hasOption("a"));
- assertTrue("Confirm -b is set", cl.hasOption("b"));
- assertTrue("Confirm arg of -b", cl.getOptionValue("b").equals("toast"));
- assertTrue("Confirm arg of --bfile", cl.getOptionValue("bfile").equals("toast"));
- assertTrue("Confirm size of extra args", cl.getArgList().size() == 2);
+ assertTrue(cl.hasOption("b"));
+ assertTrue(cl.hasOption("f"));
+ assertEquals("bar", cl.getOptionValue("foo"));
}
@Test
- public void testMultiple() throws Exception {
- final String[] args = {"-c", "foobar", "-b", "toast"};
+ public void testAmbiguousPartialLongOption1() throws Exception {
+ final String[] args = {"--ver"};
- CommandLine cl = parser.parse(options, args, true);
- assertTrue("Confirm -c is set", cl.hasOption("c"));
- assertTrue("Confirm 3 extra args: " + cl.getArgList().size(), cl.getArgList().size() == 3);
+ final Options options = new Options();
+ options.addOption(OptionBuilder.withLongOpt("version").create());
+ options.addOption(OptionBuilder.withLongOpt("verbose").create());
- cl = parser.parse(options, cl.getArgs());
+ boolean caught = false;
- assertTrue("Confirm -c is not set", !cl.hasOption("c"));
- assertTrue("Confirm -b is set", cl.hasOption("b"));
- assertTrue("Confirm arg of -b", cl.getOptionValue("b").equals("toast"));
- assertTrue("Confirm 1 extra arg: " + cl.getArgList().size(), cl.getArgList().size() == 1);
- assertTrue("Confirm value of extra arg: " + cl.getArgList().get(0), cl.getArgList().get(0).equals("foobar"));
+ try {
+ parser.parse(options, args);
+ } catch (final AmbiguousOptionException e) {
+ caught = true;
+ assertEquals("Partial option", "--ver", e.getOption());
+ assertNotNull("Matching options null", e.getMatchingOptions());
+ assertEquals("Matching options size", 2, e.getMatchingOptions().size());
+ }
+
+ assertTrue("Confirm MissingArgumentException caught", caught);
}
@Test
- public void testMultipleWithLong() throws Exception {
- final String[] args = {"--copt", "foobar", "--bfile", "toast"};
+ public void testAmbiguousPartialLongOption2() throws Exception {
+ final String[] args = {"-ver"};
- CommandLine cl = parser.parse(options, args, true);
- assertTrue("Confirm -c is set", cl.hasOption("c"));
- assertTrue("Confirm 3 extra args: " + cl.getArgList().size(), cl.getArgList().size() == 3);
+ final Options options = new Options();
+ options.addOption(OptionBuilder.withLongOpt("version").create());
+ options.addOption(OptionBuilder.withLongOpt("verbose").create());
- cl = parser.parse(options, cl.getArgs());
+ boolean caught = false;
- assertTrue("Confirm -c is not set", !cl.hasOption("c"));
- assertTrue("Confirm -b is set", cl.hasOption("b"));
- assertTrue("Confirm arg of -b", cl.getOptionValue("b").equals("toast"));
- assertTrue("Confirm 1 extra arg: " + cl.getArgList().size(), cl.getArgList().size() == 1);
- assertTrue("Confirm value of extra arg: " + cl.getArgList().get(0), cl.getArgList().get(0).equals("foobar"));
+ try {
+ parser.parse(options, args);
+ } catch (final AmbiguousOptionException e) {
+ caught = true;
+ assertEquals("Partial option", "-ver", e.getOption());
+ assertNotNull("Matching options null", e.getMatchingOptions());
+ assertEquals("Matching options size", 2, e.getMatchingOptions().size());
+ }
+
+ assertTrue("Confirm MissingArgumentException caught", caught);
}
@Test
- public void testUnrecognizedOption() throws Exception {
- final String[] args = {"-a", "-d", "-b", "toast", "foo", "bar"};
+ public void testAmbiguousPartialLongOption3() throws Exception {
+ final String[] args = {"--ver=1"};
+
+ final Options options = new Options();
+ options.addOption(OptionBuilder.withLongOpt("version").create());
+ options.addOption(OptionBuilder.withLongOpt("verbose").hasOptionalArg().create());
+
+ boolean caught = false;
try {
parser.parse(options, args);
- fail("UnrecognizedOptionException wasn't thrown");
- } catch (final UnrecognizedOptionException e) {
- assertEquals("-d", e.getOption());
+ } catch (final AmbiguousOptionException e) {
+ caught = true;
+ assertEquals("Partial option", "--ver", e.getOption());
+ assertNotNull("Matching options null", e.getMatchingOptions());
+ assertEquals("Matching options size", 2, e.getMatchingOptions().size());
}
+
+ assertTrue("Confirm MissingArgumentException caught", caught);
}
@Test
- public void testMissingArg() throws Exception {
- final String[] args = {"-b"};
+ public void testAmbiguousPartialLongOption4() throws Exception {
+ final String[] args = {"-ver=1"};
+
+ final Options options = new Options();
+ options.addOption(OptionBuilder.withLongOpt("version").create());
+ options.addOption(OptionBuilder.withLongOpt("verbose").hasOptionalArg().create());
boolean caught = false;
try {
parser.parse(options, args);
- } catch (final MissingArgumentException e) {
+ } catch (final AmbiguousOptionException e) {
caught = true;
- assertEquals("option missing an argument", "b", e.getOption().getOpt());
+ assertEquals("Partial option", "-ver", e.getOption());
+ assertNotNull("Matching options null", e.getMatchingOptions());
+ assertEquals("Matching options size", 2, e.getMatchingOptions().size());
}
assertTrue("Confirm MissingArgumentException caught", caught);
}
@Test
+ public void testArgumentStartingWithHyphen() throws Exception {
+ final String[] args = {"-b", "-foo"};
+
+ final CommandLine cl = parser.parse(options, args);
+ assertEquals("-foo", cl.getOptionValue("b"));
+ }
+
+ @Test
+ public void testBursting() throws Exception {
+ final String[] args = {"-acbtoast", "foo", "bar"};
+
+ final CommandLine cl = parser.parse(options, args);
+
+ assertTrue("Confirm -a is set", cl.hasOption("a"));
+ assertTrue("Confirm -b is set", cl.hasOption("b"));
+ assertTrue("Confirm -c is set", cl.hasOption("c"));
+ assertTrue("Confirm arg of -b", cl.getOptionValue("b").equals("toast"));
+ assertTrue("Confirm size of extra args", cl.getArgList().size() == 2);
+ }
+
+ @Test
public void testDoubleDash1() throws Exception {
final String[] args = {"--copt", "--", "-b", "toast"};
@@ -162,87 +210,20 @@ public abstract class ParserTestCase {
}
@Test
- public void testSingleDash() throws Exception {
- final String[] args = {"--copt", "-b", "-", "-a", "-"};
-
- final CommandLine cl = parser.parse(options, args);
-
- assertTrue("Confirm -a is set", cl.hasOption("a"));
- assertTrue("Confirm -b is set", cl.hasOption("b"));
- assertTrue("Confirm arg of -b", cl.getOptionValue("b").equals("-"));
- assertTrue("Confirm 1 extra arg: " + cl.getArgList().size(), cl.getArgList().size() == 1);
- assertTrue("Confirm value of extra arg: " + cl.getArgList().get(0), cl.getArgList().get(0).equals("-"));
- }
-
- @Test
- public void testStopAtUnexpectedArg() throws Exception {
- final String[] args = {"-c", "foober", "-b", "toast"};
-
- final CommandLine cl = parser.parse(options, args, true);
- assertTrue("Confirm -c is set", cl.hasOption("c"));
- assertTrue("Confirm 3 extra args: " + cl.getArgList().size(), cl.getArgList().size() == 3);
- }
-
- @Test
- public void testStopAtExpectedArg() throws Exception {
- final String[] args = {"-b", "foo"};
-
- final CommandLine cl = parser.parse(options, args, true);
-
- assertTrue("Confirm -b is set", cl.hasOption('b'));
- assertEquals("Confirm -b is set", "foo", cl.getOptionValue('b'));
- assertTrue("Confirm no extra args: " + cl.getArgList().size(), cl.getArgList().isEmpty());
- }
-
- @Test
- public void testStopAtNonOptionShort() throws Exception {
- final String[] args = {"-z", "-a", "-btoast"};
-
- final CommandLine cl = parser.parse(options, args, true);
- assertFalse("Confirm -a is not set", cl.hasOption("a"));
- assertTrue("Confirm 3 extra args: " + cl.getArgList().size(), cl.getArgList().size() == 3);
- }
-
- @Test
- public void testStopAtNonOptionLong() throws Exception {
- final String[] args = {"--zop==1", "-abtoast", "--b=bar"};
-
- final CommandLine cl = parser.parse(options, args, true);
-
- assertFalse("Confirm -a is not set", cl.hasOption("a"));
- assertFalse("Confirm -b is not set", cl.hasOption("b"));
- assertTrue("Confirm 3 extra args: " + cl.getArgList().size(), cl.getArgList().size() == 3);
- }
-
- @Test
- public void testNegativeArgument() throws Exception {
- final String[] args = {"-b", "-1"};
-
- final CommandLine cl = parser.parse(options, args);
- assertEquals("-1", cl.getOptionValue("b"));
- }
-
- @Test
- public void testNegativeOption() throws Exception {
- final String[] args = {"-b", "-1"};
+ public void testLongWithEqualDoubleDash() throws Exception {
+ final String[] args = {"--foo=bar"};
- options.addOption("1", false, null);
+ final Options options = new Options();
+ options.addOption(OptionBuilder.withLongOpt("foo").hasArg().create('f'));
final CommandLine cl = parser.parse(options, args);
- assertEquals("-1", cl.getOptionValue("b"));
- }
- @Test
- public void testArgumentStartingWithHyphen() throws Exception {
- final String[] args = {"-b", "-foo"};
-
- final CommandLine cl = parser.parse(options, args);
- assertEquals("-foo", cl.getOptionValue("b"));
+ assertEquals("bar", cl.getOptionValue("foo"));
}
@Test
- public void testShortWithEqual() throws Exception {
- final String[] args = {"-f=bar"};
+ public void testLongWithEqualSingleDash() throws Exception {
+ final String[] args = {"-foo=bar"};
final Options options = new Options();
options.addOption(OptionBuilder.withLongOpt("foo").hasArg().create('f'));
@@ -253,20 +234,20 @@ public abstract class ParserTestCase {
}
@Test
- public void testShortWithoutEqual() throws Exception {
- final String[] args = {"-fbar"};
+ public void testLongWithoutEqualDoubleDash() throws Exception {
+ final String[] args = {"--foobar"};
final Options options = new Options();
options.addOption(OptionBuilder.withLongOpt("foo").hasArg().create('f'));
- final CommandLine cl = parser.parse(options, args);
+ final CommandLine cl = parser.parse(options, args, true);
- assertEquals("bar", cl.getOptionValue("foo"));
+ assertFalse(cl.hasOption("foo")); // foo isn't expected to be recognized with a double dash
}
@Test
- public void testLongWithEqualDoubleDash() throws Exception {
- final String[] args = {"--foo=bar"};
+ public void testLongWithoutEqualSingleDash() throws Exception {
+ final String[] args = {"-foobar"};
final Options options = new Options();
options.addOption(OptionBuilder.withLongOpt("foo").hasArg().create('f'));
@@ -277,483 +258,577 @@ public abstract class ParserTestCase {
}
@Test
- public void testLongWithEqualSingleDash() throws Exception {
- final String[] args = {"-foo=bar"};
+ public void testLongWithUnexpectedArgument1() throws Exception {
+ final String[] args = {"--foo=bar"};
final Options options = new Options();
- options.addOption(OptionBuilder.withLongOpt("foo").hasArg().create('f'));
+ options.addOption(OptionBuilder.withLongOpt("foo").create('f'));
- final CommandLine cl = parser.parse(options, args);
+ try {
+ parser.parse(options, args);
+ } catch (final UnrecognizedOptionException e) {
+ assertEquals("--foo=bar", e.getOption());
+ return;
+ }
- assertEquals("bar", cl.getOptionValue("foo"));
+ fail("UnrecognizedOptionException not thrown");
}
@Test
- public void testLongWithoutEqualSingleDash() throws Exception {
+ public void testLongWithUnexpectedArgument2() throws Exception {
final String[] args = {"-foobar"};
final Options options = new Options();
- options.addOption(OptionBuilder.withLongOpt("foo").hasArg().create('f'));
+ options.addOption(OptionBuilder.withLongOpt("foo").create('f'));
- final CommandLine cl = parser.parse(options, args);
+ try {
+ parser.parse(options, args);
+ } catch (final UnrecognizedOptionException e) {
+ assertEquals("-foobar", e.getOption());
+ return;
+ }
- assertEquals("bar", cl.getOptionValue("foo"));
+ fail("UnrecognizedOptionException not thrown");
}
@Test
- public void testAmbiguousLongWithoutEqualSingleDash() throws Exception {
- final String[] args = {"-b", "-foobar"};
+ public void testMissingArg() throws Exception {
+ final String[] args = {"-b"};
- final Options options = new Options();
- options.addOption(OptionBuilder.withLongOpt("foo").hasOptionalArg().create('f'));
- options.addOption(OptionBuilder.withLongOpt("bar").hasOptionalArg().create('b'));
+ boolean caught = false;
- final CommandLine cl = parser.parse(options, args);
+ try {
+ parser.parse(options, args);
+ } catch (final MissingArgumentException e) {
+ caught = true;
+ assertEquals("option missing an argument", "b", e.getOption().getOpt());
+ }
- assertTrue(cl.hasOption("b"));
- assertTrue(cl.hasOption("f"));
- assertEquals("bar", cl.getOptionValue("foo"));
+ assertTrue("Confirm MissingArgumentException caught", caught);
}
@Test
- public void testLongWithoutEqualDoubleDash() throws Exception {
- final String[] args = {"--foobar"};
+ public void testMissingArgWithBursting() throws Exception {
+ final String[] args = {"-acb"};
- final Options options = new Options();
- options.addOption(OptionBuilder.withLongOpt("foo").hasArg().create('f'));
+ boolean caught = false;
- final CommandLine cl = parser.parse(options, args, true);
+ try {
+ parser.parse(options, args);
+ } catch (final MissingArgumentException e) {
+ caught = true;
+ assertEquals("option missing an argument", "b", e.getOption().getOpt());
+ }
- assertFalse(cl.hasOption("foo")); // foo isn't expected to be recognized with a double dash
+ assertTrue("Confirm MissingArgumentException caught", caught);
}
@Test
- public void testLongWithUnexpectedArgument1() throws Exception {
- final String[] args = {"--foo=bar"};
+ public void testMissingRequiredGroup() throws Exception {
+ final OptionGroup group = new OptionGroup();
+ group.addOption(OptionBuilder.create("a"));
+ group.addOption(OptionBuilder.create("b"));
+ group.setRequired(true);
final Options options = new Options();
- options.addOption(OptionBuilder.withLongOpt("foo").create('f'));
+ options.addOptionGroup(group);
+ options.addOption(OptionBuilder.isRequired().create("c"));
try {
- parser.parse(options, args);
- } catch (final UnrecognizedOptionException e) {
- assertEquals("--foo=bar", e.getOption());
- return;
+ parser.parse(options, new String[] {"-c"});
+ fail("MissingOptionException not thrown");
+ } catch (final MissingOptionException e) {
+ assertEquals(1, e.getMissingOptions().size());
+ assertTrue(e.getMissingOptions().get(0) instanceof OptionGroup);
+ } catch (final ParseException e) {
+ fail("Expected to catch MissingOptionException");
}
-
- fail("UnrecognizedOptionException not thrown");
}
@Test
- public void testLongWithUnexpectedArgument2() throws Exception {
- final String[] args = {"-foobar"};
+ public void testMissingRequiredOption() {
+ final String[] args = {"-a"};
final Options options = new Options();
- options.addOption(OptionBuilder.withLongOpt("foo").create('f'));
+ options.addOption("a", "enable-a", false, null);
+ options.addOption(OptionBuilder.withLongOpt("bfile").hasArg().isRequired().create('b'));
try {
parser.parse(options, args);
- } catch (final UnrecognizedOptionException e) {
- assertEquals("-foobar", e.getOption());
- return;
+ fail("exception should have been thrown");
+ } catch (final MissingOptionException e) {
+ assertEquals("Incorrect exception message", "Missing required option: b", e.getMessage());
+ assertTrue(e.getMissingOptions().contains("b"));
+ } catch (final ParseException e) {
+ fail("expected to catch MissingOptionException");
}
-
- fail("UnrecognizedOptionException not thrown");
}
@Test
- public void testShortWithUnexpectedArgument() throws Exception {
- final String[] args = {"-f=bar"};
+ public void testMissingRequiredOptions() {
+ final String[] args = {"-a"};
final Options options = new Options();
- options.addOption(OptionBuilder.withLongOpt("foo").create('f'));
+ options.addOption("a", "enable-a", false, null);
+ options.addOption(OptionBuilder.withLongOpt("bfile").hasArg().isRequired().create('b'));
+ options.addOption(OptionBuilder.withLongOpt("cfile").hasArg().isRequired().create('c'));
try {
parser.parse(options, args);
- } catch (final UnrecognizedOptionException e) {
- assertEquals("-f=bar", e.getOption());
- return;
+ fail("exception should have been thrown");
+ } catch (final MissingOptionException e) {
+ assertEquals("Incorrect exception message", "Missing required options: b, c", e.getMessage());
+ assertTrue(e.getMissingOptions().contains("b"));
+ assertTrue(e.getMissingOptions().contains("c"));
+ } catch (final ParseException e) {
+ fail("expected to catch MissingOptionException");
}
-
- fail("UnrecognizedOptionException not thrown");
}
@Test
- public void testPropertiesOption1() throws Exception {
- final String[] args = {"-Jsource=1.5", "-J", "target", "1.5", "foo"};
-
- final Options options = new Options();
- options.addOption(OptionBuilder.withValueSeparator().hasArgs(2).create('J'));
+ public void testMultiple() throws Exception {
+ final String[] args = {"-c", "foobar", "-b", "toast"};
- final CommandLine cl = parser.parse(options, args);
+ CommandLine cl = parser.parse(options, args, true);
+ assertTrue("Confirm -c is set", cl.hasOption("c"));
+ assertTrue("Confirm 3 extra args: " + cl.getArgList().size(), cl.getArgList().size() == 3);
- final List<String> values = Arrays.asList(cl.getOptionValues("J"));
- assertNotNull("null values", values);
- assertEquals("number of values", 4, values.size());
- assertEquals("value 1", "source", values.get(0));
- assertEquals("value 2", "1.5", values.get(1));
- assertEquals("value 3", "target", values.get(2));
- assertEquals("value 4", "1.5", values.get(3));
+ cl = parser.parse(options, cl.getArgs());
- final List<?> argsleft = cl.getArgList();
- assertEquals("Should be 1 arg left", 1, argsleft.size());
- assertEquals("Expecting foo", "foo", argsleft.get(0));
+ assertTrue("Confirm -c is not set", !cl.hasOption("c"));
+ assertTrue("Confirm -b is set", cl.hasOption("b"));
+ assertTrue("Confirm arg of -b", cl.getOptionValue("b").equals("toast"));
+ assertTrue("Confirm 1 extra arg: " + cl.getArgList().size(), cl.getArgList().size() == 1);
+ assertTrue("Confirm value of extra arg: " + cl.getArgList().get(0), cl.getArgList().get(0).equals("foobar"));
}
@Test
- public void testPropertiesOption2() throws Exception {
- final String[] args = {"-Dparam1", "-Dparam2=value2", "-D"};
-
- final Options options = new Options();
- options.addOption(OptionBuilder.withValueSeparator().hasOptionalArgs(2).create('D'));
+ public void testMultipleWithLong() throws Exception {
+ final String[] args = {"--copt", "foobar", "--bfile", "toast"};
- final CommandLine cl = parser.parse(options, args);
+ CommandLine cl = parser.parse(options, args, true);
+ assertTrue("Confirm -c is set", cl.hasOption("c"));
+ assertTrue("Confirm 3 extra args: " + cl.getArgList().size(), cl.getArgList().size() == 3);
- final Properties props = cl.getOptionProperties("D");
- assertNotNull("null properties", props);
- assertEquals("number of properties in " + props, 2, props.size());
- assertEquals("property 1", "true", props.getProperty("param1"));
- assertEquals("property 2", "value2", props.getProperty("param2"));
+ cl = parser.parse(options, cl.getArgs());
- final List<?> argsleft = cl.getArgList();
- assertEquals("Should be no arg left", 0, argsleft.size());
+ assertTrue("Confirm -c is not set", !cl.hasOption("c"));
+ assertTrue("Confirm -b is set", cl.hasOption("b"));
+ assertTrue("Confirm arg of -b", cl.getOptionValue("b").equals("toast"));
+ assertTrue("Confirm 1 extra arg: " + cl.getArgList().size(), cl.getArgList().size() == 1);
+ assertTrue("Confirm value of extra arg: " + cl.getArgList().get(0), cl.getArgList().get(0).equals("foobar"));
}
@Test
- public void testUnambiguousPartialLongOption1() throws Exception {
- final String[] args = {"--ver"};
-
- final Options options = new Options();
- options.addOption(OptionBuilder.withLongOpt("version").create());
- options.addOption(OptionBuilder.withLongOpt("help").create());
+ public void testNegativeArgument() throws Exception {
+ final String[] args = {"-b", "-1"};
final CommandLine cl = parser.parse(options, args);
-
- assertTrue("Confirm --version is set", cl.hasOption("version"));
+ assertEquals("-1", cl.getOptionValue("b"));
}
@Test
- public void testUnambiguousPartialLongOption2() throws Exception {
- final String[] args = {"-ver"};
+ public void testNegativeOption() throws Exception {
+ final String[] args = {"-b", "-1"};
- final Options options = new Options();
- options.addOption(OptionBuilder.withLongOpt("version").create());
- options.addOption(OptionBuilder.withLongOpt("help").create());
+ options.addOption("1", false, null);
final CommandLine cl = parser.parse(options, args);
-
- assertTrue("Confirm --version is set", cl.hasOption("version"));
+ assertEquals("-1", cl.getOptionValue("b"));
}
@Test
- public void testUnambiguousPartialLongOption3() throws Exception {
- final String[] args = {"--ver=1"};
+ public void testOptionAndRequiredOption() throws Exception {
+ final String[] args = {"-a", "-b", "file"};
final Options options = new Options();
- options.addOption(OptionBuilder.withLongOpt("verbose").hasOptionalArg().create());
- options.addOption(OptionBuilder.withLongOpt("help").create());
+ options.addOption("a", "enable-a", false, null);
+ options.addOption(OptionBuilder.withLongOpt("bfile").hasArg().isRequired().create('b'));
final CommandLine cl = parser.parse(options, args);
- assertTrue("Confirm --verbose is set", cl.hasOption("verbose"));
- assertEquals("1", cl.getOptionValue("verbose"));
+ assertTrue("Confirm -a is set", cl.hasOption("a"));
+ assertTrue("Confirm -b is set", cl.hasOption("b"));
+ assertTrue("Confirm arg of -b", cl.getOptionValue("b").equals("file"));
+ assertTrue("Confirm NO of extra args", cl.getArgList().isEmpty());
}
@Test
- public void testUnambiguousPartialLongOption4() throws Exception {
- final String[] args = {"-ver=1"};
+ public void testOptionGroup() throws Exception {
+ final OptionGroup group = new OptionGroup();
+ group.addOption(OptionBuilder.create("a"));
+ group.addOption(OptionBuilder.create("b"));
final Options options = new Options();
- options.addOption(OptionBuilder.withLongOpt("verbose").hasOptionalArg().create());
- options.addOption(OptionBuilder.withLongOpt("help").create());
+ options.addOptionGroup(group);
- final CommandLine cl = parser.parse(options, args);
+ parser.parse(options, new String[] {"-b"});
- assertTrue("Confirm --verbose is set", cl.hasOption("verbose"));
- assertEquals("1", cl.getOptionValue("verbose"));
+ assertEquals("selected option", "b", group.getSelected());
}
@Test
- public void testAmbiguousPartialLongOption1() throws Exception {
- final String[] args = {"--ver"};
+ public void testOptionGroupLong() throws Exception {
+ final OptionGroup group = new OptionGroup();
+ group.addOption(OptionBuilder.withLongOpt("foo").create());
+ group.addOption(OptionBuilder.withLongOpt("bar").create());
final Options options = new Options();
- options.addOption(OptionBuilder.withLongOpt("version").create());
- options.addOption(OptionBuilder.withLongOpt("verbose").create());
-
- boolean caught = false;
+ options.addOptionGroup(group);
- try {
- parser.parse(options, args);
- } catch (final AmbiguousOptionException e) {
- caught = true;
- assertEquals("Partial option", "--ver", e.getOption());
- assertNotNull("Matching options null", e.getMatchingOptions());
- assertEquals("Matching options size", 2, e.getMatchingOptions().size());
- }
+ final CommandLine cl = parser.parse(options, new String[] {"--bar"});
- assertTrue("Confirm MissingArgumentException caught", caught);
+ assertTrue(cl.hasOption("bar"));
+ assertEquals("selected option", "bar", group.getSelected());
}
@Test
- public void testAmbiguousPartialLongOption2() throws Exception {
+ public void testPartialLongOptionSingleDash() throws Exception {
final String[] args = {"-ver"};
final Options options = new Options();
options.addOption(OptionBuilder.withLongOpt("version").create());
- options.addOption(OptionBuilder.withLongOpt("verbose").create());
-
- boolean caught = false;
+ options.addOption(OptionBuilder.hasArg().create('v'));
- try {
- parser.parse(options, args);
- } catch (final AmbiguousOptionException e) {
- caught = true;
- assertEquals("Partial option", "-ver", e.getOption());
- assertNotNull("Matching options null", e.getMatchingOptions());
- assertEquals("Matching options size", 2, e.getMatchingOptions().size());
- }
+ final CommandLine cl = parser.parse(options, args);
- assertTrue("Confirm MissingArgumentException caught", caught);
+ assertTrue("Confirm --version is set", cl.hasOption("version"));
+ assertTrue("Confirm -v is not set", !cl.hasOption("v"));
}
@Test
- public void testAmbiguousPartialLongOption3() throws Exception {
- final String[] args = {"--ver=1"};
+ public void testPropertiesOption1() throws Exception {
+ final String[] args = {"-Jsource=1.5", "-J", "target", "1.5", "foo"};
final Options options = new Options();
- options.addOption(OptionBuilder.withLongOpt("version").create());
- options.addOption(OptionBuilder.withLongOpt("verbose").hasOptionalArg().create());
+ options.addOption(OptionBuilder.withValueSeparator().hasArgs(2).create('J'));
- boolean caught = false;
+ final CommandLine cl = parser.parse(options, args);
- try {
- parser.parse(options, args);
- } catch (final AmbiguousOptionException e) {
- caught = true;
- assertEquals("Partial option", "--ver", e.getOption());
- assertNotNull("Matching options null", e.getMatchingOptions());
- assertEquals("Matching options size", 2, e.getMatchingOptions().size());
- }
+ final List<String> values = Arrays.asList(cl.getOptionValues("J"));
+ assertNotNull("null values", values);
+ assertEquals("number of values", 4, values.size());
+ assertEquals("value 1", "source", values.get(0));
+ assertEquals("value 2", "1.5", values.get(1));
+ assertEquals("value 3", "target", values.get(2));
+ assertEquals("value 4", "1.5", values.get(3));
- assertTrue("Confirm MissingArgumentException caught", caught);
+ final List<?> argsleft = cl.getArgList();
+ assertEquals("Should be 1 arg left", 1, argsleft.size());
+ assertEquals("Expecting foo", "foo", argsleft.get(0));
}
@Test
- public void testAmbiguousPartialLongOption4() throws Exception {
- final String[] args = {"-ver=1"};
+ public void testPropertiesOption2() throws Exception {
+ final String[] args = {"-Dparam1", "-Dparam2=value2", "-D"};
final Options options = new Options();
- options.addOption(OptionBuilder.withLongOpt("version").create());
- options.addOption(OptionBuilder.withLongOpt("verbose").hasOptionalArg().create());
+ options.addOption(OptionBuilder.withValueSeparator().hasOptionalArgs(2).create('D'));
- boolean caught = false;
+ final CommandLine cl = parser.parse(options, args);
- try {
- parser.parse(options, args);
- } catch (final AmbiguousOptionException e) {
- caught = true;
- assertEquals("Partial option", "-ver", e.getOption());
- assertNotNull("Matching options null", e.getMatchingOptions());
- assertEquals("Matching options size", 2, e.getMatchingOptions().size());
- }
+ final Properties props = cl.getOptionProperties("D");
+ assertNotNull("null properties", props);
+ assertEquals("number of properties in " + props, 2, props.size());
+ assertEquals("property 1", "true", props.getProperty("param1"));
+ assertEquals("property 2", "value2", props.getProperty("param2"));
- assertTrue("Confirm MissingArgumentException caught", caught);
+ final List<?> argsleft = cl.getArgList();
+ assertEquals("Should be no arg left", 0, argsleft.size());
}
@Test
- public void testPartialLongOptionSingleDash() throws Exception {
- final String[] args = {"-ver"};
+ public void testPropertyOptionFlags() throws Exception {
+ final Options opts = new Options();
+ opts.addOption("a", false, "toggle -a");
+ opts.addOption("c", "c", false, "toggle -c");
+ opts.addOption(OptionBuilder.hasOptionalArg().create('e'));
- final Options options = new Options();
- options.addOption(OptionBuilder.withLongOpt("version").create());
- options.addOption(OptionBuilder.hasArg().create('v'));
+ Properties properties = new Properties();
+ properties.setProperty("a", "true");
+ properties.setProperty("c", "yes");
+ properties.setProperty("e", "1");
- final CommandLine cl = parser.parse(options, args);
+ CommandLine cmd = parse(parser, opts, null, properties);
+ assertTrue(cmd.hasOption("a"));
+ assertTrue(cmd.hasOption("c"));
+ assertTrue(cmd.hasOption("e"));
- assertTrue("Confirm --version is set", cl.hasOption("version"));
- assertTrue("Confirm -v is not set", !cl.hasOption("v"));
+ properties = new Properties();
+ properties.setProperty("a", "false");
+ properties.setProperty("c", "no");
+ properties.setProperty("e", "0");
+
+ cmd = parse(parser, opts, null, properties);
+ assertTrue(!cmd.hasOption("a"));
+ assertTrue(!cmd.hasOption("c"));
+ assertTrue(cmd.hasOption("e")); // this option accepts an argument
+
+ properties = new Properties();
+ properties.setProperty("a", "TRUE");
+ properties.setProperty("c", "nO");
+ properties.setProperty("e", "TrUe");
+
+ cmd = parse(parser, opts, null, properties);
+ assertTrue(cmd.hasOption("a"));
+ assertTrue(!cmd.hasOption("c"));
+ assertTrue(cmd.hasOption("e"));
+
+ properties = new Properties();
+ properties.setProperty("a", "just a string");
+ properties.setProperty("e", "");
+
+ cmd = parse(parser, opts, null, properties);
+ assertTrue(!cmd.hasOption("a"));
+ assertTrue(!cmd.hasOption("c"));
+ assertTrue(cmd.hasOption("e"));
+
+ properties = new Properties();
+ properties.setProperty("a", "0");
+ properties.setProperty("c", "1");
+
+ cmd = parse(parser, opts, null, properties);
+ assertTrue(!cmd.hasOption("a"));
+ assertTrue(cmd.hasOption("c"));
}
@Test
- public void testWithRequiredOption() throws Exception {
- final String[] args = {"-b", "file"};
+ public void testPropertyOptionGroup() throws Exception {
+ final Options opts = new Options();
- final Options options = new Options();
- options.addOption("a", "enable-a", false, null);
- options.addOption(OptionBuilder.withLongOpt("bfile").hasArg().isRequired().create('b'));
+ final OptionGroup group1 = new OptionGroup();
+ group1.addOption(new Option("a", null));
+ group1.addOption(new Option("b", null));
+ opts.addOptionGroup(group1);
- final CommandLine cl = parser.parse(options, args);
+ final OptionGroup group2 = new OptionGroup();
+ group2.addOption(new Option("x", null));
+ group2.addOption(new Option("y", null));
+ opts.addOptionGroup(group2);
- assertTrue("Confirm -a is NOT set", !cl.hasOption("a"));
- assertTrue("Confirm -b is set", cl.hasOption("b"));
- assertTrue("Confirm arg of -b", cl.getOptionValue("b").equals("file"));
- assertTrue("Confirm NO of extra args", cl.getArgList().isEmpty());
+ final String[] args = {"-a"};
+
+ final Properties properties = new Properties();
+ properties.put("b", "true");
+ properties.put("x", "true");
+
+ final CommandLine cmd = parse(parser, opts, args, properties);
+
+ assertTrue(cmd.hasOption("a"));
+ assertFalse(cmd.hasOption("b"));
+ assertTrue(cmd.hasOption("x"));
+ assertFalse(cmd.hasOption("y"));
}
@Test
- public void testOptionAndRequiredOption() throws Exception {
- final String[] args = {"-a", "-b", "file"};
+ public void testPropertyOptionMultipleValues() throws Exception {
+ final Options opts = new Options();
+ opts.addOption(OptionBuilder.hasArgs().withValueSeparator(',').create('k'));
- final Options options = new Options();
- options.addOption("a", "enable-a", false, null);
- options.addOption(OptionBuilder.withLongOpt("bfile").hasArg().isRequired().create('b'));
+ final Properties properties = new Properties();
+ properties.setProperty("k", "one,two");
- final CommandLine cl = parser.parse(options, args);
+ final String[] values = {"one", "two"};
- assertTrue("Confirm -a is set", cl.hasOption("a"));
- assertTrue("Confirm -b is set", cl.hasOption("b"));
- assertTrue("Confirm arg of -b", cl.getOptionValue("b").equals("file"));
- assertTrue("Confirm NO of extra args", cl.getArgList().isEmpty());
+ final CommandLine cmd = parse(parser, opts, null, properties);
+ assertTrue(cmd.hasOption("k"));
+ assertTrue(Arrays.equals(values, cmd.getOptionValues('k')));
}
@Test
- public void testMissingRequiredOption() {
- final String[] args = {"-a"};
+ public void testPropertyOptionRequired() throws Exception {
+ final Options opts = new Options();
+ opts.addOption(OptionBuilder.isRequired().create("f"));
- final Options options = new Options();
- options.addOption("a", "enable-a", false, null);
- options.addOption(OptionBuilder.withLongOpt("bfile").hasArg().isRequired().create('b'));
+ final Properties properties = new Properties();
+ properties.setProperty("f", "true");
- try {
- parser.parse(options, args);
- fail("exception should have been thrown");
- } catch (final MissingOptionException e) {
- assertEquals("Incorrect exception message", "Missing required option: b", e.getMessage());
- assertTrue(e.getMissingOptions().contains("b"));
- } catch (final ParseException e) {
- fail("expected to catch MissingOptionException");
- }
+ final CommandLine cmd = parse(parser, opts, null, properties);
+ assertTrue(cmd.hasOption("f"));
}
@Test
- public void testMissingRequiredOptions() {
- final String[] args = {"-a"};
+ public void testPropertyOptionSingularValue() throws Exception {
+ final Options opts = new Options();
+ opts.addOption(OptionBuilder.hasOptionalArgs(2).withLongOpt("hide").create());
- final Options options = new Options();
- options.addOption("a", "enable-a", false, null);
- options.addOption(OptionBuilder.withLongOpt("bfile").hasArg().isRequired().create('b'));
- options.addOption(OptionBuilder.withLongOpt("cfile").hasArg().isRequired().create('c'));
+ final Properties properties = new Properties();
+ properties.setProperty("hide", "seek");
+
+ final CommandLine cmd = parse(parser, opts, null, properties);
+ assertTrue(cmd.hasOption("hide"));
+ assertEquals("seek", cmd.getOptionValue("hide"));
+ assertTrue(!cmd.hasOption("fake"));
+ }
+
+ @Test
+ public void testPropertyOptionUnexpected() throws Exception {
+ final Options opts = new Options();
+
+ final Properties properties = new Properties();
+ properties.setProperty("f", "true");
try {
- parser.parse(options, args);
- fail("exception should have been thrown");
- } catch (final MissingOptionException e) {
- assertEquals("Incorrect exception message", "Missing required options: b, c", e.getMessage());
- assertTrue(e.getMissingOptions().contains("b"));
- assertTrue(e.getMissingOptions().contains("c"));
- } catch (final ParseException e) {
- fail("expected to catch MissingOptionException");
+ parse(parser, opts, null, properties);
+ fail("UnrecognizedOptionException expected");
+ } catch (final UnrecognizedOptionException e) {
+ // expected
}
}
@Test
- public void testMissingRequiredGroup() throws Exception {
- final OptionGroup group = new OptionGroup();
- group.addOption(OptionBuilder.create("a"));
- group.addOption(OptionBuilder.create("b"));
- group.setRequired(true);
+ public void testPropertyOverrideValues() throws Exception {
+ final Options opts = new Options();
+ opts.addOption(OptionBuilder.hasOptionalArgs(2).create('i'));
+ opts.addOption(OptionBuilder.hasOptionalArgs().create('j'));
- final Options options = new Options();
- options.addOptionGroup(group);
- options.addOption(OptionBuilder.isRequired().create("c"));
+ final String[] args = {"-j", "found", "-i", "ink"};
+
+ final Properties properties = new Properties();
+ properties.setProperty("j", "seek");
+
+ final CommandLine cmd = parse(parser, opts, args, properties);
+ assertTrue(cmd.hasOption("j"));
+ assertEquals("found", cmd.getOptionValue("j"));
+ assertTrue(cmd.hasOption("i"));
+ assertEquals("ink", cmd.getOptionValue("i"));
+ assertTrue(!cmd.hasOption("fake"));
+ }
+
+ @Test
+ public void testReuseOptionsTwice() throws Exception {
+ final Options opts = new Options();
+ opts.addOption(OptionBuilder.isRequired().create('v'));
+
+ // first parsing
+ parser.parse(opts, new String[] {"-v"});
try {
- parser.parse(options, new String[] {"-c"});
+ // second parsing, with the same Options instance and an invalid command line
+ parser.parse(opts, new String[0]);
fail("MissingOptionException not thrown");
} catch (final MissingOptionException e) {
- assertEquals(1, e.getMissingOptions().size());
- assertTrue(e.getMissingOptions().get(0) instanceof OptionGroup);
- } catch (final ParseException e) {
- fail("Expected to catch MissingOptionException");
+ // expected
}
}
@Test
- public void testOptionGroup() throws Exception {
- final OptionGroup group = new OptionGroup();
- group.addOption(OptionBuilder.create("a"));
- group.addOption(OptionBuilder.create("b"));
+ public void testShortWithEqual() throws Exception {
+ final String[] args = {"-f=bar"};
final Options options = new Options();
- options.addOptionGroup(group);
+ options.addOption(OptionBuilder.withLongOpt("foo").hasArg().create('f'));
- parser.parse(options, new String[] {"-b"});
+ final CommandLine cl = parser.parse(options, args);
- assertEquals("selected option", "b", group.getSelected());
+ assertEquals("bar", cl.getOptionValue("foo"));
}
@Test
- public void testOptionGroupLong() throws Exception {
- final OptionGroup group = new OptionGroup();
- group.addOption(OptionBuilder.withLongOpt("foo").create());
- group.addOption(OptionBuilder.withLongOpt("bar").create());
+ public void testShortWithoutEqual() throws Exception {
+ final String[] args = {"-fbar"};
final Options options = new Options();
- options.addOptionGroup(group);
+ options.addOption(OptionBuilder.withLongOpt("foo").hasArg().create('f'));
- final CommandLine cl = parser.parse(options, new String[] {"--bar"});
+ final CommandLine cl = parser.parse(options, args);
- assertTrue(cl.hasOption("bar"));
- assertEquals("selected option", "bar", group.getSelected());
+ assertEquals("bar", cl.getOptionValue("foo"));
}
@Test
- public void testReuseOptionsTwice() throws Exception {
- final Options opts = new Options();
- opts.addOption(OptionBuilder.isRequired().create('v'));
+ public void testShortWithUnexpectedArgument() throws Exception {
+ final String[] args = {"-f=bar"};
- // first parsing
- parser.parse(opts, new String[] {"-v"});
+ final Options options = new Options();
+ options.addOption(OptionBuilder.withLongOpt("foo").create('f'));
try {
- // second parsing, with the same Options instance and an invalid command line
- parser.parse(opts, new String[0]);
- fail("MissingOptionException not thrown");
- } catch (final MissingOptionException e) {
- // expected
+ parser.parse(options, args);
+ } catch (final UnrecognizedOptionException e) {
+ assertEquals("-f=bar", e.getOption());
+ return;
}
+
+ fail("UnrecognizedOptionException not thrown");
}
@Test
- public void testBursting() throws Exception {
- final String[] args = {"-acbtoast", "foo", "bar"};
+ public void testSimpleLong() throws Exception {
+ final String[] args = {"--enable-a", "--bfile", "toast", "foo", "bar"};
+
+ final CommandLine cl = parser.parse(options, args);
+
+ assertTrue("Confirm -a is set", cl.hasOption("a"));
+ assertTrue("Confirm -b is set", cl.hasOption("b"));
+ assertTrue("Confirm arg of -b", cl.getOptionValue("b").equals("toast"));
+ assertTrue("Confirm arg of --bfile", cl.getOptionValue("bfile").equals("toast"));
+ assertTrue("Confirm size of extra args", cl.getArgList().size() == 2);
+ }
+
+ @Test
+ public void testSimpleShort() throws Exception {
+ final String[] args = {"-a", "-b", "toast", "foo", "bar"};
+
+ final CommandLine cl = parser.parse(options, args);
+
+ assertTrue("Confirm -a is set", cl.hasOption("a"));
+ assertTrue("Confirm -b is set", cl.hasOption("b"));
+ assertTrue("Confirm arg of -b", cl.getOptionValue("b").equals("toast"));
+ assertTrue("Confirm size of extra args", cl.getArgList().size() == 2);
+ }
+
+ @Test
+ public void testSingleDash() throws Exception {
+ final String[] args = {"--copt", "-b", "-", "-a", "-"};
final CommandLine cl = parser.parse(options, args);
assertTrue("Confirm -a is set", cl.hasOption("a"));
assertTrue("Confirm -b is set", cl.hasOption("b"));
- assertTrue("Confirm -c is set", cl.hasOption("c"));
- assertTrue("Confirm arg of -b", cl.getOptionValue("b").equals("toast"));
- assertTrue("Confirm size of extra args", cl.getArgList().size() == 2);
+ assertTrue("Confirm arg of -b", cl.getOptionValue("b").equals("-"));
+ assertTrue("Confirm 1 extra arg: " + cl.getArgList().size(), cl.getArgList().size() == 1);
+ assertTrue("Confirm value of extra arg: " + cl.getArgList().get(0), cl.getArgList().get(0).equals("-"));
}
@Test
- public void testUnrecognizedOptionWithBursting() throws Exception {
- final String[] args = {"-adbtoast", "foo", "bar"};
+ public void testStopAtExpectedArg() throws Exception {
+ final String[] args = {"-b", "foo"};
- try {
- parser.parse(options, args);
- fail("UnrecognizedOptionException wasn't thrown");
- } catch (final UnrecognizedOptionException e) {
- assertEquals("-adbtoast", e.getOption());
- }
+ final CommandLine cl = parser.parse(options, args, true);
+
+ assertTrue("Confirm -b is set", cl.hasOption('b'));
+ assertEquals("Confirm -b is set", "foo", cl.getOptionValue('b'));
+ assertTrue("Confirm no extra args: " + cl.getArgList().size(), cl.getArgList().isEmpty());
}
@Test
- public void testMissingArgWithBursting() throws Exception {
- final String[] args = {"-acb"};
+ public void testStopAtNonOptionLong() throws Exception {
+ final String[] args = {"--zop==1", "-abtoast", "--b=bar"};
- boolean caught = false;
+ final CommandLine cl = parser.parse(options, args, true);
- try {
- parser.parse(options, args);
- } catch (final MissingArgumentException e) {
- caught = true;
- assertEquals("option missing an argument", "b", e.getOption().getOpt());
- }
+ assertFalse("Confirm -a is not set", cl.hasOption("a"));
+ assertFalse("Confirm -b is not set", cl.hasOption("b"));
+ assertTrue("Confirm 3 extra args: " + cl.getArgList().size(), cl.getArgList().size() == 3);
+ }
- assertTrue("Confirm MissingArgumentException caught", caught);
+ @Test
+ public void testStopAtNonOptionShort() throws Exception {
+ final String[] args = {"-z", "-a", "-btoast"};
+
+ final CommandLine cl = parser.parse(options, args, true);
+ assertFalse("Confirm -a is not set", cl.hasOption("a"));
+ assertTrue("Confirm 3 extra args: " + cl.getArgList().size(), cl.getArgList().size() == 3);
+ }
+
+ @Test
+ public void testStopAtUnexpectedArg() throws Exception {
+ final String[] args = {"-c", "foober", "-b", "toast"};
+
+ final CommandLine cl = parser.parse(options, args, true);
+ assertTrue("Confirm -c is set", cl.hasOption("c"));
+ assertTrue("Confirm 3 extra args: " + cl.getArgList().size(), cl.getArgList().size() == 3);
}
@Test
@@ -786,187 +861,112 @@ public abstract class ParserTestCase {
}
@Test
- public void testUnlimitedArgs() throws Exception {
- final String[] args = {"-e", "one", "two", "-f", "alpha"};
+ public void testUnambiguousPartialLongOption1() throws Exception {
+ final String[] args = {"--ver"};
final Options options = new Options();
- options.addOption(OptionBuilder.hasArgs().create("e"));
- options.addOption(OptionBuilder.hasArgs().create("f"));
+ options.addOption(OptionBuilder.withLongOpt("version").create());
+ options.addOption(OptionBuilder.withLongOpt("help").create());
final CommandLine cl = parser.parse(options, args);
- assertTrue("Confirm -e is set", cl.hasOption("e"));
- assertEquals("number of arg for -e", 2, cl.getOptionValues("e").length);
- assertTrue("Confirm -f is set", cl.hasOption("f"));
- assertEquals("number of arg for -f", 1, cl.getOptionValues("f").length);
- }
-
- @SuppressWarnings("deprecation")
- private CommandLine parse(final CommandLineParser parser, final Options opts, final String[] args, final Properties properties) throws ParseException {
- if (parser instanceof Parser) {
- return ((Parser) parser).parse(opts, args, properties);
- }
- if (parser instanceof DefaultParser) {
- return ((DefaultParser) parser).parse(opts, args, properties);
- }
- throw new UnsupportedOperationException("Default options not supported by this parser");
+ assertTrue("Confirm --version is set", cl.hasOption("version"));
}
@Test
- public void testPropertyOptionSingularValue() throws Exception {
- final Options opts = new Options();
- opts.addOption(OptionBuilder.hasOptionalArgs(2).withLongOpt("hide").create());
+ public void testUnambiguousPartialLongOption2() throws Exception {
+ final String[] args = {"-ver"};
- final Properties properties = new Properties();
- properties.setProperty("hide", "seek");
+ final Options options = new Options();
+ options.addOption(OptionBuilder.withLongOpt("version").create());
+ options.addOption(OptionBuilder.withLongOpt("help").create());
- final CommandLine cmd = parse(parser, opts, null, properties);
- assertTrue(cmd.hasOption("hide"));
- assertEquals("seek", cmd.getOptionValue("hide"));
- assertTrue(!cmd.hasOption("fake"));
+ final CommandLine cl = parser.parse(options, args);
+
+ assertTrue("Confirm --version is set", cl.hasOption("version"));
}
@Test
- public void testPropertyOptionFlags() throws Exception {
- final Options opts = new Options();
- opts.addOption("a", false, "toggle -a");
- opts.addOption("c", "c", false, "toggle -c");
- opts.addOption(OptionBuilder.hasOptionalArg().create('e'));
-
- Properties properties = new Properties();
- properties.setProperty("a", "true");
- properties.setProperty("c", "yes");
- properties.setProperty("e", "1");
-
- CommandLine cmd = parse(parser, opts, null, properties);
- assertTrue(cmd.hasOption("a"));
- assertTrue(cmd.hasOption("c"));
- assertTrue(cmd.hasOption("e"));
-
- properties = new Properties();
- properties.setProperty("a", "false");
- properties.setProperty("c", "no");
- properties.setProperty("e", "0");
-
- cmd = parse(parser, opts, null, properties);
- assertTrue(!cmd.hasOption("a"));
- assertTrue(!cmd.hasOption("c"));
- assertTrue(cmd.hasOption("e")); // this option accepts an argument
-
- properties = new Properties();
- properties.setProperty("a", "TRUE");
- properties.setProperty("c", "nO");
- properties.setProperty("e", "TrUe");
-
- cmd = parse(parser, opts, null, properties);
- assertTrue(cmd.hasOption("a"));
- assertTrue(!cmd.hasOption("c"));
- assertTrue(cmd.hasOption("e"));
-
- properties = new Properties();
- properties.setProperty("a", "just a string");
- properties.setProperty("e", "");
+ public void testUnambiguousPartialLongOption3() throws Exception {
+ final String[] args = {"--ver=1"};
- cmd = parse(parser, opts, null, properties);
- assertTrue(!cmd.hasOption("a"));
- assertTrue(!cmd.hasOption("c"));
- assertTrue(cmd.hasOption("e"));
+ final Options options = new Options();
+ options.addOption(OptionBuilder.withLongOpt("verbose").hasOptionalArg().create());
+ options.addOption(OptionBuilder.withLongOpt("help").create());
- properties = new Properties();
- properties.setProperty("a", "0");
- properties.setProperty("c", "1");
+ final CommandLine cl = parser.parse(options, args);
- cmd = parse(parser, opts, null, properties);
- assertTrue(!cmd.hasOption("a"));
- assertTrue(cmd.hasOption("c"));
+ assertTrue("Confirm --verbose is set", cl.hasOption("verbose"));
+ assertEquals("1", cl.getOptionValue("verbose"));
}
@Test
- public void testPropertyOptionMultipleValues() throws Exception {
- final Options opts = new Options();
- opts.addOption(OptionBuilder.hasArgs().withValueSeparator(',').create('k'));
+ public void testUnambiguousPartialLongOption4() throws Exception {
+ final String[] args = {"-ver=1"};
- final Properties properties = new Properties();
- properties.setProperty("k", "one,two");
+ final Options options = new Options();
+ options.addOption(OptionBuilder.withLongOpt("verbose").hasOptionalArg().create());
+ options.addOption(OptionBuilder.withLongOpt("help").create());
- final String[] values = {"one", "two"};
+ final CommandLine cl = parser.parse(options, args);
- final CommandLine cmd = parse(parser, opts, null, properties);
- assertTrue(cmd.hasOption("k"));
- assertTrue(Arrays.equals(values, cmd.getOptionValues('k')));
+ assertTrue("Confirm --verbose is set", cl.hasOption("verbose"));
+ assertEquals("1", cl.getOptionValue("verbose"));
}
@Test
- public void testPropertyOverrideValues() throws Exception {
- final Options opts = new Options();
- opts.addOption(OptionBuilder.hasOptionalArgs(2).create('i'));
- opts.addOption(OptionBuilder.hasOptionalArgs().create('j'));
+ public void testUnlimitedArgs() throws Exception {
+ final String[] args = {"-e", "one", "two", "-f", "alpha"};
- final String[] args = {"-j", "found", "-i", "ink"};
+ final Options options = new Options();
+ options.addOption(OptionBuilder.hasArgs().create("e"));
+ options.addOption(OptionBuilder.hasArgs().create("f"));
- final Properties properties = new Properties();
- properties.setProperty("j", "seek");
+ final CommandLine cl = parser.parse(options, args);
- final CommandLine cmd = parse(parser, opts, args, properties);
- assertTrue(cmd.hasOption("j"));
- assertEquals("found", cmd.getOptionValue("j"));
- assertTrue(cmd.hasOption("i"));
- assertEquals("ink", cmd.getOptionValue("i"));
- assertTrue(!cmd.hasOption("fake"));
+ assertTrue("Confirm -e is set", cl.hasOption("e"));
+ assertEquals("number of arg for -e", 2, cl.getOptionValues("e").length);
+ assertTrue("Confirm -f is set", cl.hasOption("f"));
+ assertEquals("number of arg for -f", 1, cl.getOptionValues("f").length);
}
@Test
- public void testPropertyOptionRequired() throws Exception {
- final Options opts = new Options();
- opts.addOption(OptionBuilder.isRequired().create("f"));
-
- final Properties properties = new Properties();
- properties.setProperty("f", "true");
+ public void testUnrecognizedOption() throws Exception {
+ final String[] args = {"-a", "-d", "-b", "toast", "foo", "bar"};
- final CommandLine cmd = parse(parser, opts, null, properties);
- assertTrue(cmd.hasOption("f"));
+ try {
+ parser.parse(options, args);
+ fail("UnrecognizedOptionException wasn't thrown");
+ } catch (final UnrecognizedOptionException e) {
+ assertEquals("-d", e.getOption());
+ }
}
@Test
- public void testPropertyOptionUnexpected() throws Exception {
- final Options opts = new Options();
-
- final Properties properties = new Properties();
- properties.setProperty("f", "true");
+ public void testUnrecognizedOptionWithBursting() throws Exception {
+ final String[] args = {"-adbtoast", "foo", "bar"};
try {
- parse(parser, opts, null, properties);
- fail("UnrecognizedOptionException expected");
+ parser.parse(options, args);
+ fail("UnrecognizedOptionException wasn't thrown");
} catch (final UnrecognizedOptionException e) {
- // expected
+ assertEquals("-adbtoast", e.getOption());
}
}
@Test
- public void testPropertyOptionGroup() throws Exception {
- final Options opts = new Options();
-
- final OptionGroup group1 = new OptionGroup();
- group1.addOption(new Option("a", null));
- group1.addOption(new Option("b", null));
- opts.addOptionGroup(group1);
-
- final OptionGroup group2 = new OptionGroup();
- group2.addOption(new Option("x", null));
- group2.addOption(new Option("y", null));
- opts.addOptionGroup(group2);
-
- final String[] args = {"-a"};
+ public void testWithRequiredOption() throws Exception {
+ final String[] args = {"-b", "file"};
- final Properties properties = new Properties();
- properties.put("b", "true");
- properties.put("x", "true");
+ final Options options = new Options();
+ options.addOption("a", "enable-a", false, null);
+ options.addOption(OptionBuilder.withLongOpt("bfile").hasArg().isRequired().create('b'));
- final CommandLine cmd = parse(parser, opts, args, properties);
+ final CommandLine cl = parser.parse(options, args);
- assertTrue(cmd.hasOption("a"));
- assertFalse(cmd.hasOption("b"));
- assertTrue(cmd.hasOption("x"));
- assertFalse(cmd.hasOption("y"));
+ assertTrue("Confirm -a is NOT set", !cl.hasOption("a"));
+ assertTrue("Confirm -b is set", cl.hasOption("b"));
+ assertTrue("Confirm arg of -b", cl.getOptionValue("b").equals("file"));
+ assertTrue("Confirm NO of extra args", cl.getArgList().isEmpty());
}
}
diff --git a/src/test/java/org/apache/commons/cli/PatternOptionBuilderTest.java b/src/test/java/org/apache/commons/cli/PatternOptionBuilderTest.java
index e39eaf9..55a2850 100644
--- a/src/test/java/org/apache/commons/cli/PatternOptionBuilderTest.java
+++ b/src/test/java/org/apache/commons/cli/PatternOptionBuilderTest.java
@@ -39,6 +39,83 @@ import org.junit.Test;
@SuppressWarnings("deprecation") // tests some deprecated classes
public class PatternOptionBuilderTest {
@Test
+ public void testClassPattern() throws Exception {
+ final Options options = PatternOptionBuilder.parsePattern("c+d+");
+ final CommandLineParser parser = new PosixParser();
+ final CommandLine line = parser.parse(options, new String[] {"-c", "java.util.Calendar", "-d", "System.DateTime"});
+
+ assertEquals("c value", Calendar.class, line.getOptionObject("c"));
+ assertNull("d value", line.getOptionObject("d"));
+ }
+
+ @Test
+ public void testEmptyPattern() throws Exception {
+ final Options options = PatternOptionBuilder.parsePattern("");
+ assertTrue(options.getOptions().isEmpty());
+ }
+
+ @Test
+ public void testExistingFilePattern() throws Exception {
+ final Options options = PatternOptionBuilder.parsePattern("g<");
+ final CommandLineParser parser = new PosixParser();
+ final CommandLine line = parser.parse(options, new String[] {"-g", "src/test/resources/org/apache/commons/cli/existing-readable.file"});
+
+ final Object parsedReadableFileStream = line.getOptionObject("g");
+
+ assertNotNull("option g not parsed", parsedReadableFileStream);
+ assertTrue("option g not FileInputStream", parsedReadableFileStream instanceof FileInputStream);
+ }
+
+ @Test
+ public void testExistingFilePatternFileNotExist() throws Exception {
+ final Options options = PatternOptionBuilder.parsePattern("f<");
+ final CommandLineParser parser = new PosixParser();
+ final CommandLine line = parser.parse(options, new String[] {"-f", "non-existing.file"});
+
+ assertNull("option f parsed", line.getOptionObject("f"));
+ }
+
+ @Test
+ public void testNumberPattern() throws Exception {
+ final Options options = PatternOptionBuilder.parsePattern("n%d%x%");
+ final CommandLineParser parser = new PosixParser();
+ final CommandLine line = parser.parse(options, new String[] {"-n", "1", "-d", "2.1", "-x", "3,5"});
+
+ assertEquals("n object class", Long.class, line.getOptionObject("n").getClass());
+ assertEquals("n value", Long.valueOf(1), line.getOptionObject("n"));
+
+ assertEquals("d object class", Double.class, line.getOptionObject("d").getClass());
+ assertEquals("d value", Double.valueOf(2.1), line.getOptionObject("d"));
+
+ assertNull("x object", line.getOptionObject("x"));
+ }
+
+ @Test
+ public void testObjectPattern() throws Exception {
+ final Options options = PatternOptionBuilder.parsePattern("o@i@n@");
+ final CommandLineParser parser = new PosixParser();
+ final CommandLine line = parser.parse(options, new String[] {"-o", "java.lang.String", "-i", "java.util.Calendar", "-n", "System.DateTime"});
+
+ assertEquals("o value", "", line.getOptionObject("o"));
+ assertNull("i value", line.getOptionObject("i"));
+ assertNull("n value", line.getOptionObject("n"));
+ }
+
+ @Test
+ public void testRequiredOption() throws Exception {
+ final Options options = PatternOptionBuilder.parsePattern("!n%m%");
+ final CommandLineParser parser = new PosixParser();
+
+ try {
+ parser.parse(options, new String[] {""});
+ fail("MissingOptionException wasn't thrown");
+ } catch (final MissingOptionException e) {
+ assertEquals(1, e.getMissingOptions().size());
+ assertTrue(e.getMissingOptions().contains("n"));
+ }
+ }
+
+ @Test
public void testSimplePattern() throws Exception {
final Options options = PatternOptionBuilder.parsePattern("a:b@cde>f+n%t/m*z#");
final String[] args = {"-c", "-a", "foo", "-b", "java.util.Vector", "-e", "build.xml", "-f", "java.util.Calendar", "-n", "4.5", "-t",
@@ -86,12 +163,6 @@ public class PatternOptionBuilderTest {
}
@Test
- public void testEmptyPattern() throws Exception {
- final Options options = PatternOptionBuilder.parsePattern("");
- assertTrue(options.getOptions().isEmpty());
- }
-
- @Test
public void testUntypedPattern() throws Exception {
final Options options = PatternOptionBuilder.parsePattern("abc");
final CommandLineParser parser = new PosixParser();
@@ -106,42 +177,6 @@ public class PatternOptionBuilderTest {
}
@Test
- public void testNumberPattern() throws Exception {
- final Options options = PatternOptionBuilder.parsePattern("n%d%x%");
- final CommandLineParser parser = new PosixParser();
- final CommandLine line = parser.parse(options, new String[] {"-n", "1", "-d", "2.1", "-x", "3,5"});
-
- assertEquals("n object class", Long.class, line.getOptionObject("n").getClass());
- assertEquals("n value", Long.valueOf(1), line.getOptionObject("n"));
-
- assertEquals("d object class", Double.class, line.getOptionObject("d").getClass());
- assertEquals("d value", Double.valueOf(2.1), line.getOptionObject("d"));
-
- assertNull("x object", line.getOptionObject("x"));
- }
-
- @Test
- public void testClassPattern() throws Exception {
- final Options options = PatternOptionBuilder.parsePattern("c+d+");
- final CommandLineParser parser = new PosixParser();
- final CommandLine line = parser.parse(options, new String[] {"-c", "java.util.Calendar", "-d", "System.DateTime"});
-
- assertEquals("c value", Calendar.class, line.getOptionObject("c"));
- assertNull("d value", line.getOptionObject("d"));
- }
-
- @Test
- public void testObjectPattern() throws Exception {
- final Options options = PatternOptionBuilder.parsePattern("o@i@n@");
- final CommandLineParser parser = new PosixParser();
- final CommandLine line = parser.parse(options, new String[] {"-o", "java.lang.String", "-i", "java.util.Calendar", "-n", "System.DateTime"});
-
- assertEquals("o value", "", line.getOptionObject("o"));
- assertNull("i value", line.getOptionObject("i"));
- assertNull("n value", line.getOptionObject("n"));
- }
-
- @Test
public void testURLPattern() throws Exception {
final Options options = PatternOptionBuilder.parsePattern("u/v/");
final CommandLineParser parser = new PosixParser();
@@ -150,39 +185,4 @@ public class PatternOptionBuilderTest {
assertEquals("u value", new URL("https://commons.apache.org"), line.getOptionObject("u"));
assertNull("v value", line.getOptionObject("v"));
}
-
- @Test
- public void testExistingFilePattern() throws Exception {
- final Options options = PatternOptionBuilder.parsePattern("g<");
- final CommandLineParser parser = new PosixParser();
- final CommandLine line = parser.parse(options, new String[] {"-g", "src/test/resources/org/apache/commons/cli/existing-readable.file"});
-
- final Object parsedReadableFileStream = line.getOptionObject("g");
-
- assertNotNull("option g not parsed", parsedReadableFileStream);
- assertTrue("option g not FileInputStream", parsedReadableFileStream instanceof FileInputStream);
- }
-
- @Test
- public void testExistingFilePatternFileNotExist() throws Exception {
- final Options options = PatternOptionBuilder.parsePattern("f<");
- final CommandLineParser parser = new PosixParser();
- final CommandLine line = parser.parse(options, new String[] {"-f", "non-existing.file"});
-
- assertNull("option f parsed", line.getOptionObject("f"));
- }
-
- @Test
- public void testRequiredOption() throws Exception {
- final Options options = PatternOptionBuilder.parsePattern("!n%m%");
- final CommandLineParser parser = new PosixParser();
-
- try {
- parser.parse(options, new String[] {""});
- fail("MissingOptionException wasn't thrown");
- } catch (final MissingOptionException e) {
- assertEquals(1, e.getMissingOptions().size());
- assertTrue(e.getMissingOptions().contains("n"));
- }
- }
}
diff --git a/src/test/java/org/apache/commons/cli/PosixParserTest.java b/src/test/java/org/apache/commons/cli/PosixParserTest.java
index bdfc6be..5efb938 100644
--- a/src/test/java/org/apache/commons/cli/PosixParserTest.java
+++ b/src/test/java/org/apache/commons/cli/PosixParserTest.java
@@ -36,54 +36,54 @@ public class PosixParserTest extends ParserTestCase {
@Override
@Test
@Ignore("not supported by the PosixParser")
- public void testDoubleDash2() throws Exception {
+ public void testAmbiguousLongWithoutEqualSingleDash() throws Exception {
}
@Override
@Test
@Ignore("not supported by the PosixParser")
- public void testLongWithoutEqualSingleDash() throws Exception {
+ public void testAmbiguousPartialLongOption4() throws Exception {
}
@Override
@Test
@Ignore("not supported by the PosixParser")
- public void testAmbiguousLongWithoutEqualSingleDash() throws Exception {
+ public void testDoubleDash2() throws Exception {
}
@Override
@Test
- @Ignore("not supported by the PosixParser (CLI-184)")
- public void testNegativeOption() throws Exception {
+ @Ignore("not supported by the PosixParser")
+ public void testLongWithEqualSingleDash() throws Exception {
}
@Override
@Test
@Ignore("not supported by the PosixParser")
- public void testLongWithUnexpectedArgument1() throws Exception {
+ public void testLongWithoutEqualSingleDash() throws Exception {
}
@Override
@Test
@Ignore("not supported by the PosixParser")
- public void testLongWithEqualSingleDash() throws Exception {
+ public void testLongWithUnexpectedArgument1() throws Exception {
}
@Override
@Test
- @Ignore("not supported by the PosixParser")
- public void testShortWithEqual() throws Exception {
+ @Ignore("not supported by the PosixParser (CLI-184)")
+ public void testNegativeOption() throws Exception {
}
@Override
@Test
@Ignore("not supported by the PosixParser")
- public void testUnambiguousPartialLongOption4() throws Exception {
+ public void testShortWithEqual() throws Exception {
}
@Override
@Test
@Ignore("not supported by the PosixParser")
- public void testAmbiguousPartialLongOption4() throws Exception {
+ public void testUnambiguousPartialLongOption4() throws Exception {
}
}
diff --git a/src/test/java/org/apache/commons/cli/TypeHandlerTest.java b/src/test/java/org/apache/commons/cli/TypeHandlerTest.java
index 43745f5..1eb192c 100644
--- a/src/test/java/org/apache/commons/cli/TypeHandlerTest.java
+++ b/src/test/java/org/apache/commons/cli/TypeHandlerTest.java
@@ -29,30 +29,56 @@ import org.junit.Test;
public class TypeHandlerTest {
+ public static class Instantiable {
+ }
+
+ public static final class NotInstantiable {
+ private NotInstantiable() {
+ }
+ }
+
@Test
- public void testCreateValueString() throws Exception {
- assertEquals("String", TypeHandler.createValue("String", PatternOptionBuilder.STRING_VALUE));
+ public void testCreateValueClass() throws Exception {
+ final Object clazz = TypeHandler.createValue(Instantiable.class.getName(), PatternOptionBuilder.CLASS_VALUE);
+ assertEquals(Instantiable.class, clazz);
}
@Test(expected = ParseException.class)
- public void testCreateValueObject_unknownClass() throws Exception {
- TypeHandler.createValue("unknown", PatternOptionBuilder.OBJECT_VALUE);
+ public void testCreateValueClass_notFound() throws Exception {
+ TypeHandler.createValue("what ever", PatternOptionBuilder.CLASS_VALUE);
+ }
+
+ @Test(expected = UnsupportedOperationException.class)
+ public void testCreateValueDate() throws Exception {
+ TypeHandler.createValue("what ever", PatternOptionBuilder.DATE_VALUE);
+ }
+
+ @Test
+ public void testCreateValueExistingFile() throws Exception {
+ final FileInputStream result = TypeHandler.createValue("src/test/resources/org/apache/commons/cli/existing-readable.file",
+ PatternOptionBuilder.EXISTING_FILE_VALUE);
+ assertNotNull(result);
}
@Test(expected = ParseException.class)
- public void testCreateValueObject_notInstantiableClass() throws Exception {
- TypeHandler.createValue(NotInstantiable.class.getName(), PatternOptionBuilder.OBJECT_VALUE);
+ public void testCreateValueExistingFile_nonExistingFile() throws Exception {
+ TypeHandler.createValue("non-existing.file", PatternOptionBuilder.EXISTING_FILE_VALUE);
}
@Test
- public void testCreateValueObject_InstantiableClass() throws Exception {
- final Object result = TypeHandler.createValue(Instantiable.class.getName(), PatternOptionBuilder.OBJECT_VALUE);
- assertTrue(result instanceof Instantiable);
+ public void testCreateValueFile() throws Exception {
+ final File result = TypeHandler.createValue("some-file.txt", PatternOptionBuilder.FILE_VALUE);
+ assertEquals("some-file.txt", result.getName());
+ }
+
+ @Test(expected = UnsupportedOperationException.class)
+ public void testCreateValueFiles() throws Exception {
+ TypeHandler.createValue("some.files", PatternOptionBuilder.FILES_VALUE);
}
@Test(expected = ParseException.class)
- public void testCreateValueNumber_noNumber() throws Exception {
- TypeHandler.createValue("not a number", PatternOptionBuilder.NUMBER_VALUE);
+ public void testCreateValueInteger_failure() throws Exception {
+ TypeHandler.createValue("just-a-string", Integer.class);
}
@Test
@@ -65,43 +91,30 @@ public class TypeHandlerTest {
assertEquals(Long.valueOf(15), TypeHandler.createValue("15", PatternOptionBuilder.NUMBER_VALUE));
}
- @Test(expected = UnsupportedOperationException.class)
- public void testCreateValueDate() throws Exception {
- TypeHandler.createValue("what ever", PatternOptionBuilder.DATE_VALUE);
- }
-
@Test(expected = ParseException.class)
- public void testCreateValueClass_notFound() throws Exception {
- TypeHandler.createValue("what ever", PatternOptionBuilder.CLASS_VALUE);
- }
-
- @Test
- public void testCreateValueClass() throws Exception {
- final Object clazz = TypeHandler.createValue(Instantiable.class.getName(), PatternOptionBuilder.CLASS_VALUE);
- assertEquals(Instantiable.class, clazz);
+ public void testCreateValueNumber_noNumber() throws Exception {
+ TypeHandler.createValue("not a number", PatternOptionBuilder.NUMBER_VALUE);
}
@Test
- public void testCreateValueFile() throws Exception {
- final File result = TypeHandler.createValue("some-file.txt", PatternOptionBuilder.FILE_VALUE);
- assertEquals("some-file.txt", result.getName());
+ public void testCreateValueObject_InstantiableClass() throws Exception {
+ final Object result = TypeHandler.createValue(Instantiable.class.getName(), PatternOptionBuilder.OBJECT_VALUE);
+ assertTrue(result instanceof Instantiable);
}
- @Test
- public void testCreateValueExistingFile() throws Exception {
- final FileInputStream result = TypeHandler.createValue("src/test/resources/org/apache/commons/cli/existing-readable.file",
- PatternOptionBuilder.EXISTING_FILE_VALUE);
- assertNotNull(result);
+ @Test(expected = ParseException.class)
+ public void testCreateValueObject_notInstantiableClass() throws Exception {
+ TypeHandler.createValue(NotInstantiable.class.getName(), PatternOptionBuilder.OBJECT_VALUE);
}
@Test(expected = ParseException.class)
- public void testCreateValueExistingFile_nonExistingFile() throws Exception {
- TypeHandler.createValue("non-existing.file", PatternOptionBuilder.EXISTING_FILE_VALUE);
+ public void testCreateValueObject_unknownClass() throws Exception {
+ TypeHandler.createValue("unknown", PatternOptionBuilder.OBJECT_VALUE);
}
- @Test(expected = UnsupportedOperationException.class)
- public void testCreateValueFiles() throws Exception {
- TypeHandler.createValue("some.files", PatternOptionBuilder.FILES_VALUE);
+ @Test
+ public void testCreateValueString() throws Exception {
+ assertEquals("String", TypeHandler.createValue("String", PatternOptionBuilder.STRING_VALUE));
}
@Test
@@ -115,17 +128,4 @@ public class TypeHandlerTest {
public void testCreateValueURL_malformed() throws Exception {
TypeHandler.createValue("malformed-url", PatternOptionBuilder.URL_VALUE);
}
-
- @Test(expected = ParseException.class)
- public void testCreateValueInteger_failure() throws Exception {
- TypeHandler.createValue("just-a-string", Integer.class);
- }
-
- public static class Instantiable {
- }
-
- public static final class NotInstantiable {
- private NotInstantiable() {
- }
- }
}
diff --git a/src/test/java/org/apache/commons/cli/UtilTest.java b/src/test/java/org/apache/commons/cli/UtilTest.java
index 71a8afd..66ca33e 100644
--- a/src/test/java/org/apache/commons/cli/UtilTest.java
+++ b/src/test/java/org/apache/commons/cli/UtilTest.java
@@ -24,14 +24,6 @@ import org.junit.Test;
public class UtilTest {
@Test
- public void testStripLeadingHyphens() {
- assertEquals("f", Util.stripLeadingHyphens("-f"));
- assertEquals("foo", Util.stripLeadingHyphens("--foo"));
- assertEquals("-foo", Util.stripLeadingHyphens("---foo"));
- assertNull(Util.stripLeadingHyphens(null));
- }
-
- @Test
public void testStripLeadingAndTrailingQuotes() {
assertEquals("foo", Util.stripLeadingAndTrailingQuotes("\"foo\""));
assertEquals("foo \"bar\"", Util.stripLeadingAndTrailingQuotes("foo \"bar\""));
@@ -39,4 +31,12 @@ public class UtilTest {
assertEquals("\"foo\" and \"bar\"", Util.stripLeadingAndTrailingQuotes("\"foo\" and \"bar\""));
assertEquals("\"", Util.stripLeadingAndTrailingQuotes("\""));
}
+
+ @Test
+ public void testStripLeadingHyphens() {
+ assertEquals("f", Util.stripLeadingHyphens("-f"));
+ assertEquals("foo", Util.stripLeadingHyphens("--foo"));
+ assertEquals("-foo", Util.stripLeadingHyphens("---foo"));
+ assertNull(Util.stripLeadingHyphens(null));
+ }
}
diff --git a/src/test/java/org/apache/commons/cli/ValueTest.java b/src/test/java/org/apache/commons/cli/ValueTest.java
index dc02fe8..e54db88 100644
--- a/src/test/java/org/apache/commons/cli/ValueTest.java
+++ b/src/test/java/org/apache/commons/cli/ValueTest.java
@@ -51,32 +51,6 @@ public class ValueTest {
}
@Test
- public void testShortNoArg() {
- assertTrue(cl.hasOption("a"));
- assertNull(cl.getOptionValue("a"));
- }
-
- @Test
- public void testShortNoArgWithOption() {
- assertTrue(cl.hasOption(opts.getOption("a")));
- assertNull(cl.getOptionValue(opts.getOption("a")));
- }
-
- @Test
- public void testShortWithArg() {
- assertTrue(cl.hasOption("b"));
- assertNotNull(cl.getOptionValue("b"));
- assertEquals(cl.getOptionValue("b"), "foo");
- }
-
- @Test
- public void testShortWithArgWithOption() {
- assertTrue(cl.hasOption(opts.getOption("b")));
- assertNotNull(cl.getOptionValue(opts.getOption("b")));
- assertEquals(cl.getOptionValue(opts.getOption("b")), "foo");
- }
-
- @Test
public void testLongNoArg() {
assertTrue(cl.hasOption("c"));
assertNull(cl.getOptionValue("c"));
@@ -89,57 +63,79 @@ public class ValueTest {
}
@Test
- public void testLongWithArg() {
- assertTrue(cl.hasOption("d"));
- assertNotNull(cl.getOptionValue("d"));
- assertEquals(cl.getOptionValue("d"), "bar");
+ public void testLongOptionalArgValue() throws Exception {
+ final String[] args = {"--fish", "face"};
+
+ final Parser parser = new PosixParser();
+ final CommandLine cmd = parser.parse(opts, args);
+ assertTrue(cmd.hasOption("fish"));
+ assertEquals("face", cmd.getOptionValue("fish"));
}
@Test
- public void testLongWithArgWithOption() {
- assertTrue(cl.hasOption(opts.getOption("d")));
- assertNotNull(cl.getOptionValue(opts.getOption("d")));
- assertEquals(cl.getOptionValue(opts.getOption("d")), "bar");
+ public void testLongOptionalArgValues() throws Exception {
+ final String[] args = {"--gravy", "gold", "garden"};
+
+ final Parser parser = new PosixParser();
+ final CommandLine cmd = parser.parse(opts, args);
+ assertTrue(cmd.hasOption("gravy"));
+ assertEquals("gold", cmd.getOptionValue("gravy"));
+ assertEquals("gold", cmd.getOptionValues("gravy")[0]);
+ assertEquals("garden", cmd.getOptionValues("gravy")[1]);
+ assertEquals(cmd.getArgs().length, 0);
}
@Test
- public void testShortOptionalArgNoValue() throws Exception {
- final String[] args = {"-e"};
+ public void testLongOptionalArgValuesWithOption() throws Exception {
+ final String[] args = {"--gravy", "gold", "garden"};
final Parser parser = new PosixParser();
final CommandLine cmd = parser.parse(opts, args);
- assertTrue(cmd.hasOption("e"));
- assertNull(cmd.getOptionValue("e"));
+ assertTrue(cmd.hasOption(opts.getOption("gravy")));
+ assertEquals("gold", cmd.getOptionValue(opts.getOption("gravy")));
+ assertEquals("gold", cmd.getOptionValues(opts.getOption("gravy"))[0]);
+ assertEquals("garden", cmd.getOptionValues(opts.getOption("gravy"))[1]);
+ assertEquals(cmd.getArgs().length, 0);
}
@Test
- public void testShortOptionalArgNoValueWithOption() throws Exception {
- final String[] args = {"-e"};
+ public void testLongOptionalArgValueWithOption() throws Exception {
+ final String[] args = {"--fish", "face"};
final Parser parser = new PosixParser();
final CommandLine cmd = parser.parse(opts, args);
- assertTrue(cmd.hasOption(opts.getOption("e")));
- assertNull(cmd.getOptionValue(opts.getOption("e")));
+ assertTrue(cmd.hasOption(opts.getOption("fish")));
+ assertEquals("face", cmd.getOptionValue(opts.getOption("fish")));
}
@Test
- public void testShortOptionalArgValue() throws Exception {
- final String[] args = {"-e", "everything"};
+ public void testLongOptionalNArgValues() throws Exception {
+ final String[] args = {"--hide", "house", "hair", "head"};
final Parser parser = new PosixParser();
+
final CommandLine cmd = parser.parse(opts, args);
- assertTrue(cmd.hasOption("e"));
- assertEquals("everything", cmd.getOptionValue("e"));
+ assertTrue(cmd.hasOption("hide"));
+ assertEquals("house", cmd.getOptionValue("hide"));
+ assertEquals("house", cmd.getOptionValues("hide")[0]);
+ assertEquals("hair", cmd.getOptionValues("hide")[1]);
+ assertEquals(cmd.getArgs().length, 1);
+ assertEquals("head", cmd.getArgs()[0]);
}
@Test
- public void testShortOptionalArgValueWithOption() throws Exception {
- final String[] args = {"-e", "everything"};
+ public void testLongOptionalNArgValuesWithOption() throws Exception {
+ final String[] args = {"--hide", "house", "hair", "head"};
final Parser parser = new PosixParser();
+
final CommandLine cmd = parser.parse(opts, args);
- assertTrue(cmd.hasOption(opts.getOption("e")));
- assertEquals("everything", cmd.getOptionValue(opts.getOption("e")));
+ assertTrue(cmd.hasOption(opts.getOption("hide")));
+ assertEquals("house", cmd.getOptionValue(opts.getOption("hide")));
+ assertEquals("house", cmd.getOptionValues(opts.getOption("hide"))[0]);
+ assertEquals("hair", cmd.getOptionValues(opts.getOption("hide"))[1]);
+ assertEquals(cmd.getArgs().length, 1);
+ assertEquals("head", cmd.getArgs()[0]);
}
@Test
@@ -163,23 +159,59 @@ public class ValueTest {
}
@Test
- public void testLongOptionalArgValue() throws Exception {
- final String[] args = {"--fish", "face"};
+ public void testLongWithArg() {
+ assertTrue(cl.hasOption("d"));
+ assertNotNull(cl.getOptionValue("d"));
+ assertEquals(cl.getOptionValue("d"), "bar");
+ }
+
+ @Test
+ public void testLongWithArgWithOption() {
+ assertTrue(cl.hasOption(opts.getOption("d")));
+ assertNotNull(cl.getOptionValue(opts.getOption("d")));
+ assertEquals(cl.getOptionValue(opts.getOption("d")), "bar");
+ }
+
+ @Test
+ public void testShortNoArg() {
+ assertTrue(cl.hasOption("a"));
+ assertNull(cl.getOptionValue("a"));
+ }
+
+ @Test
+ public void testShortNoArgWithOption() {
+ assertTrue(cl.hasOption(opts.getOption("a")));
+ assertNull(cl.getOptionValue(opts.getOption("a")));
+ }
+
+ @Test
+ public void testShortOptionalArgNoValue() throws Exception {
+ final String[] args = {"-e"};
final Parser parser = new PosixParser();
final CommandLine cmd = parser.parse(opts, args);
- assertTrue(cmd.hasOption("fish"));
- assertEquals("face", cmd.getOptionValue("fish"));
+ assertTrue(cmd.hasOption("e"));
+ assertNull(cmd.getOptionValue("e"));
}
@Test
- public void testLongOptionalArgValueWithOption() throws Exception {
- final String[] args = {"--fish", "face"};
+ public void testShortOptionalArgNoValueWithOption() throws Exception {
+ final String[] args = {"-e"};
final Parser parser = new PosixParser();
final CommandLine cmd = parser.parse(opts, args);
- assertTrue(cmd.hasOption(opts.getOption("fish")));
- assertEquals("face", cmd.getOptionValue(opts.getOption("fish")));
+ assertTrue(cmd.hasOption(opts.getOption("e")));
+ assertNull(cmd.getOptionValue(opts.getOption("e")));
+ }
+
+ @Test
+ public void testShortOptionalArgValue() throws Exception {
+ final String[] args = {"-e", "everything"};
+
+ final Parser parser = new PosixParser();
+ final CommandLine cmd = parser.parse(opts, args);
+ assertTrue(cmd.hasOption("e"));
+ assertEquals("everything", cmd.getOptionValue("e"));
}
@Test
@@ -209,29 +241,13 @@ public class ValueTest {
}
@Test
- public void testLongOptionalArgValues() throws Exception {
- final String[] args = {"--gravy", "gold", "garden"};
-
- final Parser parser = new PosixParser();
- final CommandLine cmd = parser.parse(opts, args);
- assertTrue(cmd.hasOption("gravy"));
- assertEquals("gold", cmd.getOptionValue("gravy"));
- assertEquals("gold", cmd.getOptionValues("gravy")[0]);
- assertEquals("garden", cmd.getOptionValues("gravy")[1]);
- assertEquals(cmd.getArgs().length, 0);
- }
-
- @Test
- public void testLongOptionalArgValuesWithOption() throws Exception {
- final String[] args = {"--gravy", "gold", "garden"};
+ public void testShortOptionalArgValueWithOption() throws Exception {
+ final String[] args = {"-e", "everything"};
final Parser parser = new PosixParser();
final CommandLine cmd = parser.parse(opts, args);
- assertTrue(cmd.hasOption(opts.getOption("gravy")));
- assertEquals("gold", cmd.getOptionValue(opts.getOption("gravy")));
- assertEquals("gold", cmd.getOptionValues(opts.getOption("gravy"))[0]);
- assertEquals("garden", cmd.getOptionValues(opts.getOption("gravy"))[1]);
- assertEquals(cmd.getArgs().length, 0);
+ assertTrue(cmd.hasOption(opts.getOption("e")));
+ assertEquals("everything", cmd.getOptionValue(opts.getOption("e")));
}
@Test
@@ -265,32 +281,16 @@ public class ValueTest {
}
@Test
- public void testLongOptionalNArgValues() throws Exception {
- final String[] args = {"--hide", "house", "hair", "head"};
-
- final Parser parser = new PosixParser();
-
- final CommandLine cmd = parser.parse(opts, args);
- assertTrue(cmd.hasOption("hide"));
- assertEquals("house", cmd.getOptionValue("hide"));
- assertEquals("house", cmd.getOptionValues("hide")[0]);
- assertEquals("hair", cmd.getOptionValues("hide")[1]);
- assertEquals(cmd.getArgs().length, 1);
- assertEquals("head", cmd.getArgs()[0]);
+ public void testShortWithArg() {
+ assertTrue(cl.hasOption("b"));
+ assertNotNull(cl.getOptionValue("b"));
+ assertEquals(cl.getOptionValue("b"), "foo");
}
@Test
- public void testLongOptionalNArgValuesWithOption() throws Exception {
- final String[] args = {"--hide", "house", "hair", "head"};
-
- final Parser parser = new PosixParser();
-
- final CommandLine cmd = parser.parse(opts, args);
- assertTrue(cmd.hasOption(opts.getOption("hide")));
- assertEquals("house", cmd.getOptionValue(opts.getOption("hide")));
- assertEquals("house", cmd.getOptionValues(opts.getOption("hide"))[0]);
- assertEquals("hair", cmd.getOptionValues(opts.getOption("hide"))[1]);
- assertEquals(cmd.getArgs().length, 1);
- assertEquals("head", cmd.getArgs()[0]);
+ public void testShortWithArgWithOption() {
+ assertTrue(cl.hasOption(opts.getOption("b")));
+ assertNotNull(cl.getOptionValue(opts.getOption("b")));
+ assertEquals(cl.getOptionValue(opts.getOption("b")), "foo");
}
}
diff --git a/src/test/java/org/apache/commons/cli/ValuesTest.java b/src/test/java/org/apache/commons/cli/ValuesTest.java
index ea7429e..548f1f0 100644
--- a/src/test/java/org/apache/commons/cli/ValuesTest.java
+++ b/src/test/java/org/apache/commons/cli/ValuesTest.java
@@ -73,6 +73,43 @@ public class ValuesTest {
}
@Test
+ public void testCharSeparator() {
+ // tests the char methods of CommandLine that delegate to the String methods
+ assertTrue("Option j is not set", cmd.hasOption("j"));
+ assertTrue("Option j is not set", cmd.hasOption('j'));
+ assertArrayEquals(new String[] {"key", "value", "key", "value"}, cmd.getOptionValues("j"));
+ assertArrayEquals(new String[] {"key", "value", "key", "value"}, cmd.getOptionValues('j'));
+
+ assertTrue("Option k is not set", cmd.hasOption("k"));
+ assertTrue("Option k is not set", cmd.hasOption('k'));
+ assertArrayEquals(new String[] {"key1", "value1", "key2", "value2"}, cmd.getOptionValues("k"));
+ assertArrayEquals(new String[] {"key1", "value1", "key2", "value2"}, cmd.getOptionValues('k'));
+
+ assertTrue("Option m is not set", cmd.hasOption("m"));
+ assertTrue("Option m is not set", cmd.hasOption('m'));
+ assertArrayEquals(new String[] {"key", "value"}, cmd.getOptionValues("m"));
+ assertArrayEquals(new String[] {"key", "value"}, cmd.getOptionValues('m'));
+ }
+
+ @Test
+ public void testComplexValues() {
+ assertTrue("Option i is not set", cmd.hasOption("i"));
+ assertTrue("Option h is not set", cmd.hasOption("h"));
+ assertArrayEquals(new String[] {"val1", "val2"}, cmd.getOptionValues("h"));
+ }
+
+ @Test
+ public void testExtraArgs() {
+ assertArrayEquals("Extra args", new String[] {"arg1", "arg2", "arg3"}, cmd.getArgs());
+ }
+
+ @Test
+ public void testMultipleArgValues() {
+ assertTrue("Option e is not set", cmd.hasOption("e"));
+ assertArrayEquals(new String[] {"one", "two"}, cmd.getOptionValues("e"));
+ }
+
+ @Test
public void testShortArgs() {
assertTrue("Option a is not set", cmd.hasOption("a"));
assertTrue("Option c is not set", cmd.hasOption("c"));
@@ -93,48 +130,11 @@ public class ValuesTest {
}
@Test
- public void testMultipleArgValues() {
- assertTrue("Option e is not set", cmd.hasOption("e"));
- assertArrayEquals(new String[] {"one", "two"}, cmd.getOptionValues("e"));
- }
-
- @Test
public void testTwoArgValues() {
assertTrue("Option g is not set", cmd.hasOption("g"));
assertArrayEquals(new String[] {"val1", "val2"}, cmd.getOptionValues("g"));
}
- @Test
- public void testComplexValues() {
- assertTrue("Option i is not set", cmd.hasOption("i"));
- assertTrue("Option h is not set", cmd.hasOption("h"));
- assertArrayEquals(new String[] {"val1", "val2"}, cmd.getOptionValues("h"));
- }
-
- @Test
- public void testExtraArgs() {
- assertArrayEquals("Extra args", new String[] {"arg1", "arg2", "arg3"}, cmd.getArgs());
- }
-
- @Test
- public void testCharSeparator() {
- // tests the char methods of CommandLine that delegate to the String methods
- assertTrue("Option j is not set", cmd.hasOption("j"));
- assertTrue("Option j is not set", cmd.hasOption('j'));
- assertArrayEquals(new String[] {"key", "value", "key", "value"}, cmd.getOptionValues("j"));
- assertArrayEquals(new String[] {"key", "value", "key", "value"}, cmd.getOptionValues('j'));
-
- assertTrue("Option k is not set", cmd.hasOption("k"));
- assertTrue("Option k is not set", cmd.hasOption('k'));
- assertArrayEquals(new String[] {"key1", "value1", "key2", "value2"}, cmd.getOptionValues("k"));
- assertArrayEquals(new String[] {"key1", "value1", "key2", "value2"}, cmd.getOptionValues('k'));
-
- assertTrue("Option m is not set", cmd.hasOption("m"));
- assertTrue("Option m is not set", cmd.hasOption('m'));
- assertArrayEquals(new String[] {"key", "value"}, cmd.getOptionValues("m"));
- assertArrayEquals(new String[] {"key", "value"}, cmd.getOptionValues('m'));
- }
-
/**
* jkeyes - commented out this test as the new architecture breaks this type of functionality. I have left the test here
* in case I get a brainwave on how to resolve this.
diff --git a/src/test/java/org/apache/commons/cli/bug/BugCLI252Test.java b/src/test/java/org/apache/commons/cli/bug/BugCLI252Test.java
index 763231a..e39ac52 100644
--- a/src/test/java/org/apache/commons/cli/bug/BugCLI252Test.java
+++ b/src/test/java/org/apache/commons/cli/bug/BugCLI252Test.java
@@ -26,9 +26,11 @@ import org.junit.Test;
public class BugCLI252Test {
- @Test
- public void testExactOptionNameMatch() throws ParseException {
- new DefaultParser().parse(getOptions(), new String[] {"--prefix"});
+ private Options getOptions() {
+ final Options options = new Options();
+ options.addOption(Option.builder().longOpt("prefix").build());
+ options.addOption(Option.builder().longOpt("prefixplusplus").build());
+ return options;
}
@Test(expected = AmbiguousOptionException.class)
@@ -36,11 +38,9 @@ public class BugCLI252Test {
new DefaultParser().parse(getOptions(), new String[] {"--pref"});
}
- private Options getOptions() {
- final Options options = new Options();
- options.addOption(Option.builder().longOpt("prefix").build());
- options.addOption(Option.builder().longOpt("prefixplusplus").build());
- return options;
+ @Test
+ public void testExactOptionNameMatch() throws ParseException {
+ new DefaultParser().parse(getOptions(), new String[] {"--prefix"});
}
}
diff --git a/src/test/java/org/apache/commons/cli/bug/BugCLI265Test.java b/src/test/java/org/apache/commons/cli/bug/BugCLI265Test.java
index 4639cc7..c891f76 100644
--- a/src/test/java/org/apache/commons/cli/bug/BugCLI265Test.java
+++ b/src/test/java/org/apache/commons/cli/bug/BugCLI265Test.java
@@ -53,12 +53,15 @@ public class BugCLI265Test {
}
@Test
- public void shouldParseShortOptionWithValue() throws Exception {
- final String[] shortOptionWithValue = {"-t1", "path/to/my/db"};
+ public void shouldParseConcatenatedShortOptions() throws Exception {
+ final String[] concatenatedShortOptions = {"-t1", "-ab"};
- final CommandLine commandLine = parser.parse(options, shortOptionWithValue);
+ final CommandLine commandLine = parser.parse(options, concatenatedShortOptions);
- assertEquals("path/to/my/db", commandLine.getOptionValue("t1"));
+ assertTrue(commandLine.hasOption("t1"));
+ assertNull(commandLine.getOptionValue("t1"));
+ assertTrue(commandLine.hasOption("a"));
+ assertTrue(commandLine.hasOption("b"));
assertFalse(commandLine.hasOption("last"));
}
@@ -74,15 +77,12 @@ public class BugCLI265Test {
}
@Test
- public void shouldParseConcatenatedShortOptions() throws Exception {
- final String[] concatenatedShortOptions = {"-t1", "-ab"};
+ public void shouldParseShortOptionWithValue() throws Exception {
+ final String[] shortOptionWithValue = {"-t1", "path/to/my/db"};
- final CommandLine commandLine = parser.parse(options, concatenatedShortOptions);
+ final CommandLine commandLine = parser.parse(options, shortOptionWithValue);
- assertTrue(commandLine.hasOption("t1"));
- assertNull(commandLine.getOptionValue("t1"));
- assertTrue(commandLine.hasOption("a"));
- assertTrue(commandLine.hasOption("b"));
+ assertEquals("path/to/my/db", commandLine.getOptionValue("t1"));
assertFalse(commandLine.hasOption("last"));
}
}
diff --git a/src/test/java/org/apache/commons/cli/bug/BugCLI266Test.java b/src/test/java/org/apache/commons/cli/bug/BugCLI266Test.java
index 910d483..21b2aa1 100644
--- a/src/test/java/org/apache/commons/cli/bug/BugCLI266Test.java
+++ b/src/test/java/org/apache/commons/cli/bug/BugCLI266Test.java
@@ -36,26 +36,38 @@ public class BugCLI266Test {
private final List<String> insertedOrder = Arrays.asList("h", "d", "f", "x", "s", "p", "t", "w", "o");
private final List<String> sortOrder = Arrays.asList("d", "f", "h", "o", "p", "s", "t", "w", "x");
- @Test
- public void testOptionComparatorDefaultOrder() throws ParseException {
- final HelpFormatter formatter = new HelpFormatter();
- final List<Option> options = new ArrayList<>(getOptions().getOptions());
- Collections.sort(options, formatter.getOptionComparator());
- int i = 0;
- for (final Option o : options) {
- Assert.assertEquals(o.getOpt(), sortOrder.get(i));
- i++;
- }
- }
+ private void buildOptionsGroup(final Options options) {
+ final OptionGroup firstGroup = new OptionGroup();
+ final OptionGroup secondGroup = new OptionGroup();
+ firstGroup.setRequired(true);
+ secondGroup.setRequired(true);
- @Test
- public void testOptionComparatorInsertedOrder() throws ParseException {
- final Collection<Option> options = getOptions().getOptions();
- int i = 0;
- for (final Option o : options) {
- Assert.assertEquals(o.getOpt(), insertedOrder.get(i));
- i++;
- }
+ //@formatter:off
+ firstGroup.addOption(Option.builder("d")
+ .longOpt("db")
+ .hasArg()
+ .argName("table-name")
+ .build());
+ firstGroup.addOption(Option.builder("f")
+ .longOpt("flat-file")
+ .hasArg()
+ .argName("input.csv")
+ .build());
+ //@formatter:on
+ options.addOptionGroup(firstGroup);
+ //@formatter:off
+ secondGroup.addOption(Option.builder("x")
+ .hasArg()
+ .argName("arg1")
+ .build());
+ secondGroup.addOption(Option.builder("s")
+ .build());
+ secondGroup.addOption(Option.builder("p")
+ .hasArg()
+ .argName("arg1")
+ .build());
+ //@formatter:on
+ options.addOptionGroup(secondGroup);
}
private Options getOptions() {
@@ -92,37 +104,25 @@ public class BugCLI266Test {
return options;
}
- private void buildOptionsGroup(final Options options) {
- final OptionGroup firstGroup = new OptionGroup();
- final OptionGroup secondGroup = new OptionGroup();
- firstGroup.setRequired(true);
- secondGroup.setRequired(true);
+ @Test
+ public void testOptionComparatorDefaultOrder() throws ParseException {
+ final HelpFormatter formatter = new HelpFormatter();
+ final List<Option> options = new ArrayList<>(getOptions().getOptions());
+ Collections.sort(options, formatter.getOptionComparator());
+ int i = 0;
+ for (final Option o : options) {
+ Assert.assertEquals(o.getOpt(), sortOrder.get(i));
+ i++;
+ }
+ }
- //@formatter:off
- firstGroup.addOption(Option.builder("d")
- .longOpt("db")
- .hasArg()
- .argName("table-name")
- .build());
- firstGroup.addOption(Option.builder("f")
- .longOpt("flat-file")
- .hasArg()
- .argName("input.csv")
- .build());
- //@formatter:on
- options.addOptionGroup(firstGroup);
- //@formatter:off
- secondGroup.addOption(Option.builder("x")
- .hasArg()
- .argName("arg1")
- .build());
- secondGroup.addOption(Option.builder("s")
- .build());
- secondGroup.addOption(Option.builder("p")
- .hasArg()
- .argName("arg1")
- .build());
- //@formatter:on
- options.addOptionGroup(secondGroup);
+ @Test
+ public void testOptionComparatorInsertedOrder() throws ParseException {
+ final Collection<Option> options = getOptions().getOptions();
+ int i = 0;
+ for (final Option o : options) {
+ Assert.assertEquals(o.getOpt(), insertedOrder.get(i));
+ i++;
+ }
}
}
diff --git a/src/test/java/org/apache/commons/cli/bug/BugCLI71Test.java b/src/test/java/org/apache/commons/cli/bug/BugCLI71Test.java
index 714548e..8457c80 100644
--- a/src/test/java/org/apache/commons/cli/bug/BugCLI71Test.java
+++ b/src/test/java/org/apache/commons/cli/bug/BugCLI71Test.java
@@ -58,13 +58,13 @@ public class BugCLI71Test {
}
@Test
- public void testMistakenArgument() throws Exception {
- String[] args = {"-a", "Caesar", "-k", "A"};
- CommandLine line = parser.parse(options, args);
- args = new String[] {"-a", "Caesar", "-k", "a"};
- line = parser.parse(options, args);
+ public void testGetsDefaultIfOptional() throws Exception {
+ final String[] args = {"-k", "-a", "Caesar"};
+ options.getOption("k").setOptionalArg(true);
+ final CommandLine line = parser.parse(options, args);
+
assertEquals("Caesar", line.getOptionValue("a"));
- assertEquals("a", line.getOptionValue("k"));
+ assertEquals("a", line.getOptionValue('k', "a"));
}
@Test
@@ -79,13 +79,13 @@ public class BugCLI71Test {
}
@Test
- public void testGetsDefaultIfOptional() throws Exception {
- final String[] args = {"-k", "-a", "Caesar"};
- options.getOption("k").setOptionalArg(true);
- final CommandLine line = parser.parse(options, args);
-
+ public void testMistakenArgument() throws Exception {
+ String[] args = {"-a", "Caesar", "-k", "A"};
+ CommandLine line = parser.parse(options, args);
+ args = new String[] {"-a", "Caesar", "-k", "a"};
+ line = parser.parse(options, args);
assertEquals("Caesar", line.getOptionValue("a"));
- assertEquals("a", line.getOptionValue('k', "a"));
+ assertEquals("a", line.getOptionValue("k"));
}
}
diff --git a/src/test/java/org/apache/commons/cli/bug/BugsTest.java b/src/test/java/org/apache/commons/cli/bug/BugsTest.java
index 402f86b..983c535 100644
--- a/src/test/java/org/apache/commons/cli/bug/BugsTest.java
+++ b/src/test/java/org/apache/commons/cli/bug/BugsTest.java
@@ -44,6 +44,31 @@ import org.junit.Test;
@SuppressWarnings("deprecation") // tests some deprecated classes
public class BugsTest {
@Test
+ public void test11456() throws Exception {
+ // Posix
+ Options options = new Options();
+ options.addOption(OptionBuilder.hasOptionalArg().create('a'));
+ options.addOption(OptionBuilder.hasArg().create('b'));
+ String[] args = {"-a", "-bvalue"};
+
+ CommandLineParser parser = new PosixParser();
+
+ CommandLine cmd = parser.parse(options, args);
+ assertEquals(cmd.getOptionValue('b'), "value");
+
+ // GNU
+ options = new Options();
+ options.addOption(OptionBuilder.hasOptionalArg().create('a'));
+ options.addOption(OptionBuilder.hasArg().create('b'));
+ args = new String[] {"-a", "-b", "value"};
+
+ parser = new GnuParser();
+
+ cmd = parser.parse(options, args);
+ assertEquals(cmd.getOptionValue('b'), "value");
+ }
+
+ @Test
public void test11457() throws Exception {
final Options options = new Options();
options.addOption(OptionBuilder.withLongOpt("verbose").create());
@@ -112,31 +137,6 @@ public class BugsTest {
}
@Test
- public void test11456() throws Exception {
- // Posix
- Options options = new Options();
- options.addOption(OptionBuilder.hasOptionalArg().create('a'));
- options.addOption(OptionBuilder.hasArg().create('b'));
- String[] args = {"-a", "-bvalue"};
-
- CommandLineParser parser = new PosixParser();
-
- CommandLine cmd = parser.parse(options, args);
- assertEquals(cmd.getOptionValue('b'), "value");
-
- // GNU
- options = new Options();
- options.addOption(OptionBuilder.hasOptionalArg().create('a'));
- options.addOption(OptionBuilder.hasArg().create('b'));
- args = new String[] {"-a", "-b", "value"};
-
- parser = new GnuParser();
-
- cmd = parser.parse(options, args);
- assertEquals(cmd.getOptionValue('b'), "value");
- }
-
- @Test
public void test12210() throws Exception {
// create the main options object which will handle the first parameter
final Options mainOptions = new Options();