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:17 UTC
[commons-cli] 01/03: Clean ups.
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 bc0edc47dbf47cdaa3485cfb724982f377c900df
Author: Gary Gregory <ga...@gmail.com>
AuthorDate: Sat Oct 2 16:04:33 2021 -0400
Clean ups.
- maven-checkstyle-plugin 3.1.1 -> 3.1.2.
- checkstyle -> 9.0
- Updates for 21st century.
- No need to nest else clause.
- Use simple array declarations.
- Use valueOf instead of new for Numbers.
- Consistent formatting.
- Remove some inline comments //-----...
---
pom.xml | 129 +++---
src/conf/checkstyle-suppressions.xml | 13 +-
src/conf/checkstyle.xml | 19 +-
.../commons/cli/AlreadySelectedException.java | 29 +-
.../commons/cli/AmbiguousOptionException.java | 21 +-
.../java/org/apache/commons/cli/BasicParser.java | 27 +-
.../java/org/apache/commons/cli/CommandLine.java | 257 ++++-------
.../org/apache/commons/cli/CommandLineParser.java | 58 +--
.../java/org/apache/commons/cli/DefaultParser.java | 454 ++++++------------
.../java/org/apache/commons/cli/GnuParser.java | 84 ++--
.../java/org/apache/commons/cli/HelpFormatter.java | 483 +++++++------------
.../commons/cli/MissingArgumentException.java | 24 +-
.../apache/commons/cli/MissingOptionException.java | 33 +-
src/main/java/org/apache/commons/cli/Option.java | 411 ++++++-----------
.../java/org/apache/commons/cli/OptionBuilder.java | 129 ++----
.../java/org/apache/commons/cli/OptionGroup.java | 56 +--
.../org/apache/commons/cli/OptionValidator.java | 42 +-
src/main/java/org/apache/commons/cli/Options.java | 89 ++--
.../org/apache/commons/cli/ParseException.java | 9 +-
src/main/java/org/apache/commons/cli/Parser.java | 224 +++------
.../apache/commons/cli/PatternOptionBuilder.java | 148 +++---
.../java/org/apache/commons/cli/PosixParser.java | 206 ++++-----
.../java/org/apache/commons/cli/TypeHandler.java | 151 ++----
.../commons/cli/UnrecognizedOptionException.java | 25 +-
src/main/java/org/apache/commons/cli/Util.java | 30 +-
.../org/apache/commons/cli/ApplicationTest.java | 263 ++++++-----
.../apache/commons/cli/ArgumentIsOptionTest.java | 39 +-
.../org/apache/commons/cli/BasicParserTest.java | 174 ++++---
.../org/apache/commons/cli/CommandLineTest.java | 75 ++-
.../commons/cli/DisablePartialMatchingTest.java | 19 +-
.../java/org/apache/commons/cli/GnuParserTest.java | 153 +++---
.../org/apache/commons/cli/HelpFormatterTest.java | 204 ++++----
.../org/apache/commons/cli/OptionBuilderTest.java | 179 ++++---
.../org/apache/commons/cli/OptionGroupTest.java | 255 +++++-----
.../java/org/apache/commons/cli/OptionTest.java | 117 ++---
.../java/org/apache/commons/cli/OptionsTest.java | 47 +-
.../org/apache/commons/cli/ParserTestCase.java | 512 ++++++++-------------
.../commons/cli/PatternOptionBuilderTest.java | 68 ++-
.../org/apache/commons/cli/PosixParserTest.java | 69 +--
.../org/apache/commons/cli/TypeHandlerTest.java | 91 ++--
src/test/java/org/apache/commons/cli/UtilTest.java | 9 +-
.../java/org/apache/commons/cli/ValueTest.java | 320 ++++++-------
.../java/org/apache/commons/cli/ValuesTest.java | 127 +++--
.../org/apache/commons/cli/bug/BugCLI133Test.java | 5 +-
.../org/apache/commons/cli/bug/BugCLI13Test.java | 32 +-
.../org/apache/commons/cli/bug/BugCLI148Test.java | 16 +-
.../org/apache/commons/cli/bug/BugCLI162Test.java | 273 ++++++-----
.../org/apache/commons/cli/bug/BugCLI18Test.java | 10 +-
.../org/apache/commons/cli/bug/BugCLI252Test.java | 4 +-
.../org/apache/commons/cli/bug/BugCLI265Test.java | 18 +-
.../org/apache/commons/cli/bug/BugCLI266Test.java | 29 +-
.../org/apache/commons/cli/bug/BugCLI71Test.java | 41 +-
.../java/org/apache/commons/cli/bug/BugsTest.java | 244 +++++-----
53 files changed, 2680 insertions(+), 3864 deletions(-)
diff --git a/pom.xml b/pom.xml
index 9471188..1664403 100644
--- a/pom.xml
+++ b/pom.xml
@@ -96,6 +96,21 @@
<id>chtompki</id>
<email>chtompki@apache.org</email>
</developer>
+ <developer>
+ <id>ggregory</id>
+ <name>Gary Gregory</name>
+ <email>ggregory at apache.org</email>
+ <url>https://www.garygregory.com</url>
+ <organization>The Apache Software Foundation</organization>
+ <organizationUrl>https://www.apache.org/</organizationUrl>
+ <roles>
+ <role>PMC Member</role>
+ </roles>
+ <timezone>America/New_York</timezone>
+ <properties>
+ <picUrl>https://people.apache.org/~ggregory/img/garydgregory80.png</picUrl>
+ </properties>
+ </developer>
</developers>
<contributors>
@@ -187,60 +202,18 @@
<commons.jira.pid>12310463</commons.jira.pid>
<!-- The RC version used in the staging repository URL. -->
<commons.rc.version>RC1</commons.rc.version>
-
<commons.scmPubUrl>https://svn.apache.org/repos/infra/websites/production/commons/content/proper/commons-cli</commons.scmPubUrl>
<commons.scmPubCheckoutDirectory>site-content</commons.scmPubCheckoutDirectory>
<commons.encoding>utf-8</commons.encoding>
+ <commons.checkstyle-plugin.version>3.1.2</commons.checkstyle-plugin.version>
+ <commons.checkstyle.impl.version>9.0</commons.checkstyle.impl.version>
</properties>
<build>
<defaultGoal>clean package apache-rat:check clirr:check checkstyle:check findbugs:check javadoc:javadoc</defaultGoal>
- <plugins>
- <plugin>
- <artifactId>maven-assembly-plugin</artifactId>
- <configuration>
- <descriptors>
- <descriptor>src/assembly/bin.xml</descriptor>
- <descriptor>src/assembly/src.xml</descriptor>
- </descriptors>
- <tarLongFileMode>gnu</tarLongFileMode>
- </configuration>
- </plugin>
- <!--
- Fix for https://bugs.openjdk.java.net/browse/JDK-8212233
- which is addressed in maven-javadoc-plugin:3.1.0, see https://issues.apache.org/jira/browse/MJAVADOC-562
- -->
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-javadoc-plugin</artifactId>
- <version>${commons.javadoc.version}</version>
- <configuration>
- <source>7</source>
- </configuration>
- </plugin>
- </plugins>
<pluginManagement>
<plugins>
<plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-scm-publish-plugin</artifactId>
- <configuration>
- <ignorePathsToDelete>
- <ignorePathToDelete>javadocs**</ignorePathToDelete>
- </ignorePathsToDelete>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <version>${commons.checkstyle-plugin.version}</version>
- <configuration>
- <configLocation>${basedir}/src/conf/checkstyle.xml</configLocation>
- <enableRulesSummary>false</enableRulesSummary>
- <suppressionsLocation>${basedir}/src/conf/checkstyle-suppressions.xml</suppressionsLocation>
- </configuration>
- </plugin>
- <plugin>
<groupId>org.apache.rat</groupId>
<artifactId>apache-rat-plugin</artifactId>
<version>${commons.rat.version}</version>
@@ -252,6 +225,24 @@
</configuration>
</plugin>
<plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-checkstyle-plugin</artifactId>
+ <version>${commons.checkstyle-plugin.version}</version>
+ <configuration>
+ <configLocation>${basedir}/src/conf/checkstyle.xml</configLocation>
+ <suppressionsLocation>${basedir}/src/conf/checkstyle-suppressions.xml</suppressionsLocation>
+ <enableRulesSummary>false</enableRulesSummary>
+ <includeTestSourceDirectory>true</includeTestSourceDirectory>
+ </configuration>
+ <dependencies>
+ <dependency>
+ <groupId>com.puppycrawl.tools</groupId>
+ <artifactId>checkstyle</artifactId>
+ <version>${commons.checkstyle.impl.version}</version>
+ </dependency>
+ </dependencies>
+ </plugin>
+ <plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>findbugs-maven-plugin</artifactId>
<version>${commons.findbugs.version}</version>
@@ -261,8 +252,45 @@
<excludeFilterFile>${basedir}/src/conf/findbugs-exclude-filter.xml</excludeFilterFile>
</configuration>
</plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-scm-publish-plugin</artifactId>
+ <configuration>
+ <ignorePathsToDelete>
+ <ignorePathToDelete>javadocs**</ignorePathToDelete>
+ </ignorePathsToDelete>
+ </configuration>
+ </plugin>
</plugins>
</pluginManagement>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-checkstyle-plugin</artifactId>
+ </plugin>
+ <plugin>
+ <artifactId>maven-assembly-plugin</artifactId>
+ <configuration>
+ <descriptors>
+ <descriptor>src/assembly/bin.xml</descriptor>
+ <descriptor>src/assembly/src.xml</descriptor>
+ </descriptors>
+ <tarLongFileMode>gnu</tarLongFileMode>
+ </configuration>
+ </plugin>
+ <!--
+ Fix for https://bugs.openjdk.java.net/browse/JDK-8212233
+ which is addressed in maven-javadoc-plugin:3.1.0, see https://issues.apache.org/jira/browse/MJAVADOC-562
+ -->
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-javadoc-plugin</artifactId>
+ <version>${commons.javadoc.version}</version>
+ <configuration>
+ <source>7</source>
+ </configuration>
+ </plugin>
+ </plugins>
</build>
<reporting>
@@ -280,19 +308,6 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
- <version>${commons.checkstyle-plugin.version}</version>
- <configuration>
- <configLocation>${basedir}/src/conf/checkstyle.xml</configLocation>
- <enableRulesSummary>false</enableRulesSummary>
- <suppressionsLocation>${basedir}/src/conf/checkstyle-suppressions.xml</suppressionsLocation>
- </configuration>
- <reportSets>
- <reportSet>
- <reports>
- <report>checkstyle</report>
- </reports>
- </reportSet>
- </reportSets>
</plugin>
<plugin>
<groupId>org.apache.rat</groupId>
diff --git a/src/conf/checkstyle-suppressions.xml b/src/conf/checkstyle-suppressions.xml
index e4e4b3f..3cb746a 100644
--- a/src/conf/checkstyle-suppressions.xml
+++ b/src/conf/checkstyle-suppressions.xml
@@ -1,5 +1,7 @@
<?xml version="1.0"?>
-<!DOCTYPE suppressions PUBLIC "-//Checkstyle//DTD SuppressionFilter Configuration 1.0//EN" "https://checkstyle.org/dtds/suppressions_1_0.dtd">
+<!DOCTYPE suppressions PUBLIC
+ "-//Checkstyle//DTD SuppressionFilter Configuration 1.2//EN"
+ "https://checkstyle.org/dtds/suppressions_1_2.dtd">
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
@@ -19,6 +21,15 @@
<suppressions>
+ <!-- Suppress some test checks-->
+ <suppress checks="JavadocMethod" files="src[/\\]test[/\\]java[/\\]" />
+ <suppress checks="JavadocPackage" files="src[/\\]test[/\\]java[/\\]" />
+ <suppress checks="JavadocVariable" files="src[/\\]test[/\\]java[/\\]" />
+ <suppress checks="MethodName" files="src[/\\]test[/\\]java[/\\]" />
+ <suppress checks="MagicNumber" files="src[/\\]test[/\\]java[/\\]" />
+ <suppress checks="ParameterNumber" files="src[/\\]test[/\\]java[/\\]" />
+ <suppress checks="MethodLength" files="BugCLI162Test.java" />
+
<!-- Suppress visibility check of some member fields as they have to be kept
for binary compatibility reasons -->
<suppress checks="VisibilityModifier" files="HelpFormatter.java" />
diff --git a/src/conf/checkstyle.xml b/src/conf/checkstyle.xml
index f469667..e2b1b44 100644
--- a/src/conf/checkstyle.xml
+++ b/src/conf/checkstyle.xml
@@ -24,7 +24,6 @@ limitations under the License.
<module name="Checker">
<property name="localeLanguage" value="en"/>
- <property name="severity" value="warning"/>
<!-- Checks that a package.html file exists for each package. -->
<!-- See http://checkstyle.sourceforge.net/config_javadoc.html#JavadocPackage -->
@@ -38,26 +37,18 @@ limitations under the License.
<!-- See http://checkstyle.sf.net/config_misc.html#Translation -->
<module name="Translation"/>
- <!-- Exceptions -->
- <module name="SuppressionFilter">
- <property name="file" value="${checkstyle.suppressions.file}"/>
- </module>
-
<module name="FileTabCharacter">
<property name="eachLine" value="true"/>
</module>
<module name="LineLength">
- <property name="max" value="120"/>
+ <property name="max" value="160"/>
</module>
<module name="TreeWalker">
<!-- Checks for Javadoc comments. -->
<!-- See http://checkstyle.sf.net/config_javadoc.html -->
- <module name="JavadocMethod">
- <property name="scope" value="public"/>
- </module>
<module name="JavadocType"/>
<module name="JavadocVariable"/>
@@ -90,13 +81,11 @@ limitations under the License.
<property name="max" value="9"/>
</module>
-
<!-- Checks for whitespace -->
<!-- See http://checkstyle.sf.net/config_whitespace.html -->
<module name="EmptyForIteratorPad"/>
<module name="NoWhitespaceAfter"/>
<module name="NoWhitespaceBefore"/>
- <module name="OperatorWrap"/>
<module name="ParenPad"/>
<module name="WhitespaceAfter"/>
@@ -115,13 +104,7 @@ limitations under the License.
<module name="EmptyBlock">
<property name="option" value="text"/>
</module>
- <module name="LeftCurly">
- <property name="option" value="nl"/>
- </module>
<module name="NeedBraces"/>
- <module name="RightCurly">
- <property name="option" value="alone"/>
- </module>
<!-- Checks for common coding problems -->
<!-- See http://checkstyle.sf.net/config_coding.html -->
diff --git a/src/main/java/org/apache/commons/cli/AlreadySelectedException.java b/src/main/java/org/apache/commons/cli/AlreadySelectedException.java
index 28548ae..3b1cb01 100644
--- a/src/main/java/org/apache/commons/cli/AlreadySelectedException.java
+++ b/src/main/java/org/apache/commons/cli/AlreadySelectedException.java
@@ -18,11 +18,9 @@
package org.apache.commons.cli;
/**
- * Thrown when more than one option in an option group
- * has been provided.
+ * Thrown when more than one option in an option group has been provided.
*/
-public class AlreadySelectedException extends ParseException
-{
+public class AlreadySelectedException extends ParseException {
/**
* This exception {@code serialVersionUID}.
*/
@@ -35,28 +33,23 @@ public class AlreadySelectedException extends ParseException
private Option option;
/**
- * Construct a new <code>AlreadySelectedException</code>
- * with the specified detail message.
+ * Construct a new <code>AlreadySelectedException</code> with the specified detail message.
*
* @param message the detail message
*/
- public AlreadySelectedException(final String message)
- {
+ public AlreadySelectedException(final String message) {
super(message);
}
/**
- * Construct a new <code>AlreadySelectedException</code>
- * for the specified option group.
+ * Construct a new <code>AlreadySelectedException</code> for the specified option group.
*
- * @param group the option group already selected
+ * @param group the option group already selected
* @param option the option that triggered the exception
* @since 1.2
*/
- public AlreadySelectedException(final OptionGroup group, final Option option)
- {
- this("The option '" + option.getKey() + "' was specified but an option from this group "
- + "has already been selected: '" + group.getSelected() + "'");
+ public AlreadySelectedException(final OptionGroup group, final Option option) {
+ this("The option '" + option.getKey() + "' was specified but an option from this group " + "has already been selected: '" + group.getSelected() + "'");
this.group = group;
this.option = option;
}
@@ -67,8 +60,7 @@ public class AlreadySelectedException extends ParseException
* @return the related option group
* @since 1.2
*/
- public OptionGroup getOptionGroup()
- {
+ public OptionGroup getOptionGroup() {
return group;
}
@@ -78,8 +70,7 @@ public class AlreadySelectedException extends ParseException
* @return the related option
* @since 1.2
*/
- public Option getOption()
- {
+ public Option getOption() {
return option;
}
}
diff --git a/src/main/java/org/apache/commons/cli/AmbiguousOptionException.java b/src/main/java/org/apache/commons/cli/AmbiguousOptionException.java
index c80aeb2..9a523ed 100644
--- a/src/main/java/org/apache/commons/cli/AmbiguousOptionException.java
+++ b/src/main/java/org/apache/commons/cli/AmbiguousOptionException.java
@@ -25,8 +25,7 @@ import java.util.Iterator;
*
* @since 1.3
*/
-public class AmbiguousOptionException extends UnrecognizedOptionException
-{
+public class AmbiguousOptionException extends UnrecognizedOptionException {
/**
* This exception {@code serialVersionUID}.
*/
@@ -38,21 +37,20 @@ public class AmbiguousOptionException extends UnrecognizedOptionException
/**
* Constructs a new AmbiguousOptionException.
*
- * @param option the partial option name
+ * @param option the partial option name
* @param matchingOptions the options matching the name
*/
- public AmbiguousOptionException(final String option, final Collection<String> matchingOptions)
- {
+ 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()
- {
+ public Collection<String> getMatchingOptions() {
return matchingOptions;
}
@@ -63,20 +61,17 @@ public class AmbiguousOptionException extends UnrecognizedOptionException
* @param matchingOptions
* @return
*/
- private static String createMessage(final String option, final Collection<String> matchingOptions)
- {
+ private static String createMessage(final String option, final Collection<String> matchingOptions) {
final StringBuilder buf = new StringBuilder("Ambiguous option: '");
buf.append(option);
buf.append("' (could be: ");
final Iterator<String> it = matchingOptions.iterator();
- while (it.hasNext())
- {
+ while (it.hasNext()) {
buf.append("'");
buf.append(it.next());
buf.append("'");
- if (it.hasNext())
- {
+ if (it.hasNext()) {
buf.append(", ");
}
}
diff --git a/src/main/java/org/apache/commons/cli/BasicParser.java b/src/main/java/org/apache/commons/cli/BasicParser.java
index ac4af99..57d4f65 100644
--- a/src/main/java/org/apache/commons/cli/BasicParser.java
+++ b/src/main/java/org/apache/commons/cli/BasicParser.java
@@ -18,32 +18,31 @@
package org.apache.commons.cli;
/**
- * The class BasicParser provides a very simple implementation of
- * the {@link Parser#flatten(Options,String[],boolean) flatten} method.
+ * The class BasicParser provides a very simple implementation of the {@link Parser#flatten(Options,String[],boolean)
+ * flatten} method.
*
* @deprecated since 1.3, use the {@link DefaultParser} instead
*/
@Deprecated
-public class BasicParser extends Parser
-{
+public class BasicParser extends Parser {
/**
- * <p>A simple implementation of {@link Parser}'s abstract
- * {@link Parser#flatten(Options, String[], boolean) flatten} method.</p>
+ * <p>
+ * A simple implementation of {@link Parser}'s abstract {@link Parser#flatten(Options, String[], boolean) flatten}
+ * method.
+ * </p>
*
- * <p><b>Note:</b> <code>options</code> and <code>stopAtNonOption</code>
- * are not used in this <code>flatten</code> method.</p>
+ * <p>
+ * <b>Note:</b> <code>options</code> and <code>stopAtNonOption</code> are not used in this <code>flatten</code> method.
+ * </p>
*
* @param options The command line {@link Options}
* @param arguments The command line arguments to be parsed
- * @param stopAtNonOption Specifies whether to stop flattening
- * when an non option is found.
+ * @param stopAtNonOption Specifies whether to stop flattening when an non option is found.
* @return The <code>arguments</code> String array.
*/
@Override
- protected String[] flatten(@SuppressWarnings("unused") final Options options,
- final String[] arguments,
- @SuppressWarnings("unused") final boolean stopAtNonOption)
- {
+ protected String[] flatten(@SuppressWarnings("unused") final Options options, final String[] arguments,
+ @SuppressWarnings("unused") final boolean stopAtNonOption) {
// just echo the arguments
return arguments;
}
diff --git a/src/main/java/org/apache/commons/cli/CommandLine.java b/src/main/java/org/apache/commons/cli/CommandLine.java
index 6cacd32..f0ac8b8 100644
--- a/src/main/java/org/apache/commons/cli/CommandLine.java
+++ b/src/main/java/org/apache/commons/cli/CommandLine.java
@@ -28,15 +28,12 @@ import java.util.Properties;
/**
* Represents list of arguments parsed against a {@link Options} descriptor.
* <p>
- * It allows querying of a boolean {@link #hasOption(String opt)},
- * in addition to retrieving the {@link #getOptionValue(String opt)}
- * for options requiring arguments.
+ * It allows querying of a boolean {@link #hasOption(String opt)}, in addition to retrieving the
+ * {@link #getOptionValue(String opt)} for options requiring arguments.
* <p>
- * Additionally, any left-over or unrecognized arguments,
- * are available for further processing.
+ * Additionally, any left-over or unrecognized arguments, are available for further processing.
*/
-public class CommandLine implements Serializable
-{
+public class CommandLine implements Serializable {
/** The serial version UID. */
private static final long serialVersionUID = 1L;
@@ -49,8 +46,7 @@ public class CommandLine implements Serializable
/**
* Creates a command line.
*/
- protected CommandLine()
- {
+ protected CommandLine() {
// nothing to do
}
@@ -61,8 +57,7 @@ public class CommandLine implements Serializable
* @return true if set, false if not.
* @since 1.5
*/
- public boolean hasOption(final Option opt)
- {
+ public boolean hasOption(final Option opt) {
return options.contains(opt);
}
@@ -72,8 +67,7 @@ public class CommandLine implements Serializable
* @param opt Short name of the option.
* @return true if set, false if not.
*/
- public boolean hasOption(final String opt)
- {
+ public boolean hasOption(final String opt) {
return hasOption(resolveOption(opt));
}
@@ -83,8 +77,7 @@ public class CommandLine implements Serializable
* @param opt character name of the option.
* @return true if set, false if not.
*/
- public boolean hasOption(final char opt)
- {
+ public boolean hasOption(final char opt) {
return hasOption(String.valueOf(opt));
}
@@ -96,14 +89,10 @@ public class CommandLine implements Serializable
* @deprecated due to System.err message. Instead use getParsedOptionValue(String)
*/
@Deprecated
- public Object getOptionObject(final String opt)
- {
- try
- {
+ public Object getOptionObject(final String opt) {
+ try {
return getParsedOptionValue(opt);
- }
- catch (final ParseException pe)
- {
+ } catch (final ParseException pe) {
System.err.println("Exception found converting " + opt + " to desired type: " + pe.getMessage());
return null;
}
@@ -118,15 +107,12 @@ public class CommandLine implements Serializable
* @see PatternOptionBuilder
* @since 1.5
*/
- public Object getParsedOptionValue(final Option option) throws ParseException
- {
- if (option == null)
- {
+ public Object getParsedOptionValue(final Option option) throws ParseException {
+ if (option == null) {
return null;
}
final String res = getOptionValue(option);
- if (res == null)
- {
+ if (res == null) {
return null;
}
return TypeHandler.createValue(res, option.getType());
@@ -141,8 +127,7 @@ public class CommandLine implements Serializable
* @see PatternOptionBuilder
* @since 1.2
*/
- public Object getParsedOptionValue(final String opt) throws ParseException
- {
+ public Object getParsedOptionValue(final String opt) throws ParseException {
return getParsedOptionValue(resolveOption(opt));
}
@@ -155,8 +140,7 @@ public class CommandLine implements Serializable
* @see PatternOptionBuilder
* @since 1.5
*/
- public Object getParsedOptionValue(final char opt) throws ParseException
- {
+ public Object getParsedOptionValue(final char opt) throws ParseException {
return getParsedOptionValue(String.valueOf(opt));
}
@@ -168,8 +152,7 @@ public class CommandLine implements Serializable
* @return the type of opt.
*/
@Deprecated
- public Object getOptionObject(final char opt)
- {
+ public Object getOptionObject(final char opt) {
return getOptionObject(String.valueOf(opt));
}
@@ -177,14 +160,11 @@ public class CommandLine implements Serializable
* Retrieve the first argument, if any, of this option.
*
* @param option the name of the option.
- * @return Value of the argument if option is set, and has an argument,
- * otherwise null.
+ * @return Value of the argument if option is set, and has an argument, otherwise null.
* @since 1.5
*/
- public String getOptionValue(final Option option)
- {
- if (option == null)
- {
+ public String getOptionValue(final Option option) {
+ if (option == null) {
return null;
}
final String[] values = getOptionValues(option);
@@ -195,11 +175,9 @@ public class CommandLine implements Serializable
* Retrieve the first argument, if any, of this option.
*
* @param opt the name of the option.
- * @return Value of the argument if option is set, and has an argument,
- * otherwise null.
+ * @return Value of the argument if option is set, and has an argument, otherwise null.
*/
- public String getOptionValue(final String opt)
- {
+ public String getOptionValue(final String opt) {
return getOptionValue(resolveOption(opt));
}
@@ -207,11 +185,9 @@ public class CommandLine implements Serializable
* Retrieve the first argument, if any, of this option.
*
* @param opt the character name of the option.
- * @return Value of the argument if option is set, and has an argument,
- * otherwise null.
+ * @return Value of the argument if option is set, and has an argument, otherwise null.
*/
- public String getOptionValue(final char opt)
- {
+ public String getOptionValue(final char opt) {
return getOptionValue(String.valueOf(opt));
}
@@ -219,18 +195,14 @@ public class CommandLine implements Serializable
* Retrieves the array of values, if any, of an option.
*
* @param option string name of the option.
- * @return Values of the argument if option is set, and has an argument,
- * otherwise null.
+ * @return Values of the argument if option is set, and has an argument, otherwise null.
* @since 1.5
*/
- public String[] getOptionValues(final Option option)
- {
+ public String[] getOptionValues(final Option option) {
final List<String> values = new ArrayList<>();
- for (final Option processedOption : options)
- {
- if (processedOption.equals(option))
- {
+ for (final Option processedOption : options) {
+ if (processedOption.equals(option)) {
values.addAll(processedOption.getValuesList());
}
}
@@ -242,11 +214,9 @@ public class CommandLine implements Serializable
* Retrieves the array of values, if any, of an option.
*
* @param opt string name of the option.
- * @return Values of the argument if option is set, and has an argument,
- * otherwise null.
+ * @return Values of the argument if option is set, and has an argument, otherwise null.
*/
- public String[] getOptionValues(final String opt)
- {
+ public String[] getOptionValues(final String opt) {
return getOptionValues(resolveOption(opt));
}
@@ -256,18 +226,14 @@ public class CommandLine implements Serializable
* @param opt short or long name of the option.
* @return Canonicalized option.
*/
- private Option resolveOption(String opt)
- {
+ private Option resolveOption(String opt) {
opt = Util.stripLeadingHyphens(opt);
- for (final Option option : options)
- {
- if (opt.equals(option.getOpt()))
- {
+ for (final Option option : options) {
+ if (opt.equals(option.getOpt())) {
return option;
}
- if (opt.equals(option.getLongOpt()))
- {
+ if (opt.equals(option.getLongOpt())) {
return option;
}
@@ -279,11 +245,9 @@ public class CommandLine implements Serializable
* 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.
+ * @return Values of the argument if option is set, and has an argument, otherwise null.
*/
- public String[] getOptionValues(final char opt)
- {
+ public String[] getOptionValues(final char opt) {
return getOptionValues(String.valueOf(opt));
}
@@ -291,14 +255,11 @@ 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>.
+ * @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)
- {
+ public String getOptionValue(final Option option, final String defaultValue) {
final String answer = getOptionValue(option);
return (answer != null) ? answer : defaultValue;
}
@@ -307,13 +268,10 @@ public class CommandLine implements Serializable
* 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>.
+ * @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)
- {
+ public String getOptionValue(final String opt, final String defaultValue) {
return getOptionValue(resolveOption(opt), defaultValue);
}
@@ -321,45 +279,33 @@ public class CommandLine implements Serializable
* 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>.
+ * @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)
- {
+ public String getOptionValue(final char opt, final String defaultValue) {
return getOptionValue(String.valueOf(opt), defaultValue);
}
/**
- * 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>.
+ * 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 name of the option.
- * @return The Properties mapped by the option, never <code>null</code>
- * even if the option doesn't exists.
+ * @return The Properties mapped by the option, never <code>null</code> even if the option doesn't exists.
* @since 1.5
*/
- public Properties getOptionProperties(final Option option)
- {
+ public Properties getOptionProperties(final Option option) {
final Properties props = new Properties();
- for (final Option processedOption : options)
- {
- if (processedOption.equals(option))
- {
+ for (final Option processedOption : options) {
+ if (processedOption.equals(option)) {
final List<String> values = processedOption.getValuesList();
- if (values.size() >= 2)
- {
+ 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)
- {
+ } else if (values.size() == 1) {
// no explicit value, handle it as a boolean
props.put(values.get(0), "true");
}
@@ -370,34 +316,25 @@ public class CommandLine implements Serializable
}
/**
- * 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>.
+ * 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.
+ * @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)
- {
+ 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()))
- {
+ for (final Option option : options) {
+ if (opt.equals(option.getOpt()) || opt.equals(option.getLongOpt())) {
final List<String> values = option.getValuesList();
- if (values.size() >= 2)
- {
+ 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)
- {
+ } else if (values.size() == 1) {
// no explicit value, handle it as a boolean
props.put(values.get(0), "true");
}
@@ -412,8 +349,7 @@ public class CommandLine implements Serializable
*
* @return remaining items passed in but not parsed as an array.
*/
- public String[] getArgs()
- {
+ public String[] getArgs() {
final String[] answer = new String[args.size()];
args.toArray(answer);
@@ -426,61 +362,52 @@ public class CommandLine implements Serializable
*
* @return remaining items passed in but not parsed as a <code>List</code>.
*/
- public List<String> getArgList()
- {
+ public List<String> getArgList() {
return args;
}
/**
- * jkeyes
- * - commented out until it is implemented properly
- * <p>Dump state, suitable for debugging.</p>
+ * jkeyes - commented out until it is implemented properly
+ * <p>
+ * Dump state, suitable for debugging.
+ * </p>
*
* @return Stringified form of this object.
*/
/*
- public String toString() {
- StringBuilder buf = new StringBuilder();
-
- buf.append("[ CommandLine: [ options: ");
- buf.append(options.toString());
- buf.append(" ] [ args: ");
- buf.append(args.toString());
- buf.append(" ] ]");
-
- return buf.toString();
- }
- */
+ * public String toString() { StringBuilder buf = new StringBuilder();
+ *
+ * buf.append("[ CommandLine: [ options: "); buf.append(options.toString()); buf.append(" ] [ args: ");
+ * buf.append(args.toString()); buf.append(" ] ]");
+ *
+ * return buf.toString(); }
+ */
/**
* Add left-over unrecognized option/argument.
*
* @param arg the unrecognized option/argument.
*/
- protected void addArg(final String arg)
- {
+ protected void addArg(final String arg) {
args.add(arg);
}
/**
- * Add an option to the command line. The values of the option are stored.
+ * Add an option to the command line. The values of the option are stored.
*
* @param opt the processed option.
*/
- protected void addOption(final Option opt)
- {
+ protected void addOption(final Option opt) {
options.add(opt);
}
/**
* Returns an iterator over the Option members of CommandLine.
*
- * @return an <code>Iterator</code> over the processed {@link Option}
- * members of this {@link CommandLine}.
+ * @return an <code>Iterator</code> over the processed {@link Option} members of this {@link CommandLine}.
*/
- public Iterator<Option> iterator()
- {
+ public Iterator<Option> iterator() {
return options.iterator();
}
@@ -489,8 +416,7 @@ public class CommandLine implements Serializable
*
* @return an array of the processed {@link Option}s.
*/
- public Option[] getOptions()
- {
+ public Option[] getOptions() {
final Collection<Option> processed = options;
// reinitialize array
@@ -501,13 +427,11 @@ public class CommandLine implements Serializable
}
/**
- * A nested builder class to create <code>CommandLine</code> instance
- * using descriptive methods.
+ * A nested builder class to create <code>CommandLine</code> instance using descriptive methods.
*
* @since 1.4
*/
- public static final class Builder
- {
+ public static final class Builder {
/**
* CommandLine that is being build by this Builder.
*/
@@ -520,8 +444,7 @@ public class CommandLine implements Serializable
*
* @return this Builder instance for method chaining.
*/
- public Builder addOption(final Option opt)
- {
+ public Builder addOption(final Option opt) {
commandLine.addOption(opt);
return this;
}
@@ -533,14 +456,12 @@ public class CommandLine implements Serializable
*
* @return this Builder instance for method chaining.
*/
- public Builder addArg(final String arg)
- {
+ public Builder addArg(final String arg) {
commandLine.addArg(arg);
return this;
}
- public CommandLine build()
- {
+ public CommandLine build() {
return commandLine;
}
}
diff --git a/src/main/java/org/apache/commons/cli/CommandLineParser.java b/src/main/java/org/apache/commons/cli/CommandLineParser.java
index ed743d3..c087bbe 100644
--- a/src/main/java/org/apache/commons/cli/CommandLineParser.java
+++ b/src/main/java/org/apache/commons/cli/CommandLineParser.java
@@ -18,12 +18,10 @@
package org.apache.commons.cli;
/**
- * A class that implements the <code>CommandLineParser</code> interface
- * can parse a String array according to the {@link Options} specified
- * and return a {@link CommandLine}.
+ * A class that implements the <code>CommandLineParser</code> interface can parse a String array according to the
+ * {@link Options} specified and return a {@link CommandLine}.
*/
-public interface CommandLineParser
-{
+public interface CommandLineParser {
/**
* Parse the arguments according to the specified options.
*
@@ -31,28 +29,24 @@ public interface CommandLineParser
* @param arguments the command line arguments
* @return the list of atomic option and value tokens
*
- * @throws ParseException if there are any problems encountered
- * while parsing the command line tokens.
+ * @throws ParseException if there are any problems encountered while parsing the command line tokens.
*/
CommandLine parse(Options options, String[] arguments) throws ParseException;
/**
- * Parse the arguments according to the specified options and
- * properties.
+ * 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.
+ * @throws ParseException if there are any problems encountered while parsing the command line tokens.
*/
- /* To maintain binary compatibility, this is commented out.
- It is still in the abstract Parser class, so most users will
- still reap the benefit.
- CommandLine parse(Options options, String[] arguments, Properties properties)
- throws ParseException;
+ /*
+ * To maintain binary compatibility, this is commented out. It is still in the abstract Parser class, so most users will
+ * still reap the benefit. CommandLine parse(Options options, String[] arguments, Properties properties) throws
+ * ParseException;
*/
/**
@@ -60,37 +54,31 @@ public interface CommandLineParser
*
* @param options the specified Options
* @param arguments the command line arguments
- * @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.
+ * @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.
+ * @throws ParseException if there are any problems encountered while parsing the command line tokens.
*/
CommandLine parse(Options options, String[] arguments, boolean stopAtNonOption) throws ParseException;
/**
- * Parse the arguments according to the specified options and
- * properties.
+ * 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.
+ * @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.
+ * @throws ParseException if there are any problems encountered while parsing the command line tokens.
*/
- /* To maintain binary compatibility, this is commented out.
- It is still in the abstract Parser class, so most users will
- still reap the benefit.
- CommandLine parse(Options options, String[] arguments, Properties properties, boolean stopAtNonOption)
- throws ParseException;
+ /*
+ * To maintain binary compatibility, this is commented out. It is still in the abstract Parser class, so most users will
+ * still reap the benefit. CommandLine parse(Options options, String[] arguments, Properties properties, boolean
+ * stopAtNonOption) throws ParseException;
*/
}
diff --git a/src/main/java/org/apache/commons/cli/DefaultParser.java b/src/main/java/org/apache/commons/cli/DefaultParser.java
index 64849dc..0ab58ae 100644
--- a/src/main/java/org/apache/commons/cli/DefaultParser.java
+++ b/src/main/java/org/apache/commons/cli/DefaultParser.java
@@ -27,8 +27,7 @@ import java.util.Properties;
*
* @since 1.3
*/
-public class DefaultParser implements CommandLineParser
-{
+public class DefaultParser implements CommandLineParser {
/** The command-line instance. */
protected CommandLine cmd;
@@ -36,9 +35,8 @@ public class DefaultParser implements CommandLineParser
protected Options options;
/**
- * Flag indicating how unrecognized tokens are handled. <code>true</code> to stop
- * the parsing and add the remaining tokens to the args list.
- * <code>false</code> to throw an exception.
+ * Flag indicating how unrecognized tokens are handled. <code>true</code> to stop the parsing and add the remaining
+ * tokens to the args list. <code>false</code> to throw an exception.
*/
protected boolean stopAtNonOption;
@@ -55,24 +53,26 @@ public class DefaultParser implements CommandLineParser
protected List expectedOpts;
/** Flag indicating if partial matching of long options is supported. */
- private final boolean allowPartialMatching;
+ private final boolean allowPartialMatching;
/**
* Creates a new DefaultParser instance with partial matching enabled.
*
* By "partial matching" we mean that given the following code:
+ *
* <pre>
- * {@code
- * final Options options = new Options();
- * options.addOption(new Option("d", "debug", false, "Turn on debug."));
- * options.addOption(new Option("e", "extract", false, "Turn on extract."));
- * options.addOption(new Option("o", "option", true, "Turn on option with argument."));
- * }
+ * {
+ * @code
+ * final Options options = new Options();
+ * options.addOption(new Option("d", "debug", false, "Turn on debug."));
+ * options.addOption(new Option("e", "extract", false, "Turn on extract."));
+ * options.addOption(new Option("o", "option", true, "Turn on option with argument."));
+ * }
* </pre>
- * with "partial matching" turned on, <code>-de</code> only matches the
- * <code>"debug"</code> option. However, with "partial matching" disabled,
- * <code>-de</code> would enable both <code>debug</code> as well as
- * <code>extract</code> options.
+ *
+ * with "partial matching" turned on, <code>-de</code> only matches the <code>"debug"</code> option. However, with
+ * "partial matching" disabled, <code>-de</code> would enable both <code>debug</code> as well as <code>extract</code>
+ * options.
*/
public DefaultParser() {
this.allowPartialMatching = true;
@@ -82,18 +82,20 @@ public class DefaultParser implements CommandLineParser
* Create a new DefaultParser instance with the specified partial matching policy.
*
* By "partial matching" we mean that given the following code:
+ *
* <pre>
- * {@code
- * final Options options = new Options();
- * options.addOption(new Option("d", "debug", false, "Turn on debug."));
- * options.addOption(new Option("e", "extract", false, "Turn on extract."));
- * options.addOption(new Option("o", "option", true, "Turn on option with argument."));
- * }
+ * {
+ * @code
+ * final Options options = new Options();
+ * options.addOption(new Option("d", "debug", false, "Turn on debug."));
+ * options.addOption(new Option("e", "extract", false, "Turn on extract."));
+ * options.addOption(new Option("o", "option", true, "Turn on option with argument."));
+ * }
* </pre>
- * with "partial matching" turned on, <code>-de</code> only matches the
- * <code>"debug"</code> option. However, with "partial matching" disabled,
- * <code>-de</code> would enable both <code>debug</code> as well as
- * <code>extract</code> options.
+ *
+ * with "partial matching" turned on, <code>-de</code> only matches the <code>"debug"</code> option. However, with
+ * "partial matching" disabled, <code>-de</code> would enable both <code>debug</code> as well as <code>extract</code>
+ * options.
*
* @param allowPartialMatching if partial matching of long options shall be enabled
*/
@@ -102,51 +104,44 @@ public class DefaultParser implements CommandLineParser
}
@Override
- public CommandLine parse(final Options options, final String[] arguments) throws ParseException
- {
+ 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 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.
+ * @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
- {
+ 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
- {
+ 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.
+ * @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.
+ * @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
- {
+ throws ParseException {
this.options = options;
this.stopAtNonOption = stopAtNonOption;
skipParsing = false;
@@ -154,17 +149,14 @@ public class DefaultParser implements CommandLineParser
expectedOpts = new ArrayList(options.getRequiredOptions());
// clear the data from the groups
- for (final OptionGroup group : options.getOptionGroups())
- {
+ for (final OptionGroup group : options.getOptionGroups()) {
group.setSelected(null);
}
cmd = new CommandLine();
- if (arguments != null)
- {
- for (final String argument : arguments)
- {
+ if (arguments != null) {
+ for (final String argument : arguments) {
handleToken(argument);
}
}
@@ -185,20 +177,16 @@ public class DefaultParser implements CommandLineParser
*
* @param properties The value properties to be processed.
*/
- private void handleProperties(final Properties properties) throws ParseException
- {
- if (properties == null)
- {
+ private void handleProperties(final Properties properties) throws ParseException {
+ if (properties == null) {
return;
}
- for (final Enumeration<?> e = properties.propertyNames(); e.hasMoreElements();)
- {
+ for (final Enumeration<?> e = properties.propertyNames(); e.hasMoreElements();) {
final String option = e.nextElement().toString();
final Option opt = options.getOption(option);
- if (opt == null)
- {
+ if (opt == null) {
throw new UnrecognizedOptionException("Default option wasn't defined", option);
}
@@ -206,22 +194,15 @@ public class DefaultParser implements CommandLineParser
final OptionGroup group = options.getOptionGroup(opt);
final boolean selected = group != null && group.getSelected() != null;
- if (!cmd.hasOption(option) && !selected)
- {
+ 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)
- {
+ 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)))
- {
+ } 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;
}
@@ -233,29 +214,22 @@ public class DefaultParser implements CommandLineParser
}
/**
- * Throws a {@link MissingOptionException} if all of the required options
- * are not present.
+ * Throws a {@link MissingOptionException} if all of the required options are not present.
*
- * @throws MissingOptionException if any of the required Options
- * are not present.
+ * @throws MissingOptionException if any of the required Options are not present.
*/
- protected void checkRequiredOptions() throws MissingOptionException
- {
+ protected void checkRequiredOptions() throws MissingOptionException {
// if there are required options that have not been processed
- if (!expectedOpts.isEmpty())
- {
+ if (!expectedOpts.isEmpty()) {
throw new MissingOptionException(expectedOpts);
}
}
/**
- * Throw a {@link MissingArgumentException} if the current option
- * didn't receive the number of arguments expected.
+ * 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())
- {
+ private void checkRequiredArgs() throws ParseException {
+ if (currentOption != null && currentOption.requiresArg()) {
throw new MissingArgumentException(currentOption);
}
}
@@ -266,37 +240,24 @@ public class DefaultParser implements CommandLineParser
* @param token the command line token to handle
* @throws ParseException
*/
- private void handleToken(final String token) throws ParseException
- {
+ private void handleToken(final String token) throws ParseException {
currentToken = token;
- if (skipParsing)
- {
+ if (skipParsing) {
cmd.addArg(token);
- }
- else if ("--".equals(token))
- {
+ } else if ("--".equals(token)) {
skipParsing = true;
- }
- else if (currentOption != null && currentOption.acceptsArg() && isArgument(token))
- {
+ } else if (currentOption != null && currentOption.acceptsArg() && isArgument(token)) {
currentOption.addValueForProcessing(Util.stripLeadingAndTrailingQuotes(token));
- }
- else if (token.startsWith("--"))
- {
+ } else if (token.startsWith("--")) {
handleLongOption(token);
- }
- else if (token.startsWith("-") && !"-".equals(token))
- {
+ } else if (token.startsWith("-") && !"-".equals(token)) {
handleShortAndLongOption(token);
- }
- else
- {
+ } else {
handleUnknownToken(token);
}
- if (currentOption != null && !currentOption.acceptsArg())
- {
+ if (currentOption != null && !currentOption.acceptsArg()) {
currentOption = null;
}
}
@@ -306,8 +267,7 @@ public class DefaultParser implements CommandLineParser
*
* @param token
*/
- private boolean isArgument(final String token)
- {
+ private boolean isArgument(final String token) {
return !isOption(token) || isNegativeNumber(token);
}
@@ -316,15 +276,11 @@ public class DefaultParser implements CommandLineParser
*
* @param token
*/
- private boolean isNegativeNumber(final String token)
- {
- try
- {
+ private boolean isNegativeNumber(final String token) {
+ try {
Double.parseDouble(token);
return true;
- }
- catch (final NumberFormatException e)
- {
+ } catch (final NumberFormatException e) {
return false;
}
}
@@ -334,8 +290,7 @@ public class DefaultParser implements CommandLineParser
*
* @param token
*/
- private boolean isOption(final String token)
- {
+ private boolean isOption(final String token) {
return isLongOption(token) || isShortOption(token);
}
@@ -344,19 +299,16 @@ public class DefaultParser implements CommandLineParser
*
* @param token
*/
- private boolean isShortOption(final String token)
- {
+ private boolean isShortOption(final String token) {
// short options (-S, -SV, -S=V, -SV1=V2, -S1S2)
- if (token == null || !token.startsWith("-") || token.length() == 1)
- {
+ if (token == null || !token.startsWith("-") || token.length() == 1) {
return false;
}
// 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))
- {
+ if (options.hasShortOption(optName)) {
return true;
}
// check for several concatenated short options
@@ -368,23 +320,19 @@ public class DefaultParser implements CommandLineParser
*
* @param token
*/
- private boolean isLongOption(final String token)
- {
- if (token == null || !token.startsWith("-") || token.length() == 1)
- {
+ private boolean isLongOption(final String token) {
+ if (token == null || !token.startsWith("-") || token.length() == 1) {
return false;
}
final int pos = token.indexOf("=");
final String t = pos == -1 ? token : token.substring(0, pos);
- if (!getMatchingLongOptions(t).isEmpty())
- {
+ 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("--"))
- {
+ if (getLongPrefix(token) != null && !token.startsWith("--")) {
// -LV
return true;
}
@@ -393,24 +341,19 @@ public class DefaultParser implements CommandLineParser
}
/**
- * 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 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)
- {
+ 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)
- {
+ if (stopAtNonOption) {
skipParsing = true;
}
}
@@ -418,21 +361,14 @@ public class DefaultParser implements CommandLineParser
/**
* Handles the following tokens:
*
- * --L
- * --L=V
- * --L V
- * --l
+ * --L --L=V --L V --l
*
* @param token the command line token to handle
*/
- private void handleLongOption(final String token) throws ParseException
- {
- if (token.indexOf('=') == -1)
- {
+ private void handleLongOption(final String token) throws ParseException {
+ if (token.indexOf('=') == -1) {
handleLongOptionWithoutEqual(token);
- }
- else
- {
+ } else {
handleLongOptionWithEqual(token);
}
}
@@ -440,26 +376,17 @@ public class DefaultParser implements CommandLineParser
/**
* Handles the following tokens:
*
- * --L
- * -L
- * --l
- * -l
+ * --L -L --l -l
*
* @param token the command line token to handle
*/
- private void handleLongOptionWithoutEqual(final String token) throws ParseException
- {
+ private void handleLongOptionWithoutEqual(final String token) throws ParseException {
final List<String> matchingOpts = getMatchingLongOptions(token);
- if (matchingOpts.isEmpty())
- {
+ if (matchingOpts.isEmpty()) {
handleUnknownToken(currentToken);
- }
- else if (matchingOpts.size() > 1 && !options.hasLongOption(token))
- {
+ } else if (matchingOpts.size() > 1 && !options.hasLongOption(token)) {
throw new AmbiguousOptionException(token, matchingOpts);
- }
- else
- {
+ } else {
final String key = options.hasLongOption(token) ? token : matchingOpts.get(0);
handleOption(options.getOption(key));
}
@@ -468,15 +395,11 @@ public class DefaultParser implements CommandLineParser
/**
* Handles the following tokens:
*
- * --L=V
- * -L=V
- * --l=V
- * -l=V
+ * --L=V -L=V --l=V -l=V
*
* @param token the command line token to handle
*/
- private void handleLongOptionWithEqual(final String token) throws ParseException
- {
+ private void handleLongOptionWithEqual(final String token) throws ParseException {
final int pos = token.indexOf('=');
final String value = token.substring(pos + 1);
@@ -484,27 +407,19 @@ public class DefaultParser implements CommandLineParser
final String opt = token.substring(0, pos);
final List<String> matchingOpts = getMatchingLongOptions(opt);
- if (matchingOpts.isEmpty())
- {
+ if (matchingOpts.isEmpty()) {
handleUnknownToken(currentToken);
- }
- else if (matchingOpts.size() > 1 && !options.hasLongOption(opt))
- {
+ } else if (matchingOpts.size() > 1 && !options.hasLongOption(opt)) {
throw new AmbiguousOptionException(opt, matchingOpts);
- }
- else
- {
+ } else {
final String key = options.hasLongOption(opt) ? opt : matchingOpts.get(0);
final Option option = options.getOption(key);
- if (option.acceptsArg())
- {
+ if (option.acceptsArg()) {
handleOption(option);
currentOption.addValueForProcessing(value);
currentOption = null;
- }
- else
- {
+ } else {
handleUnknownToken(currentToken);
}
}
@@ -513,108 +428,71 @@ public class DefaultParser implements CommandLineParser
/**
* Handles the following tokens:
*
- * -S
- * -SV
- * -S V
- * -S=V
- * -S1S2
- * -S1S2 V
- * -SV1=V2
+ * -S -SV -S V -S=V -S1S2 -S1S2 V -SV1=V2
*
- * -L
- * -LV
- * -L V
- * -L=V
- * -l
+ * -L -LV -L V -L=V -l
*
* @param token the command line token to handle
*/
- private void handleShortAndLongOption(final String token) throws ParseException
- {
+ private void handleShortAndLongOption(final String token) throws ParseException {
final String t = Util.stripLeadingHyphens(token);
final int pos = t.indexOf('=');
- if (t.length() == 1)
- {
+ if (t.length() == 1) {
// -S
- if (options.hasShortOption(t))
- {
+ if (options.hasShortOption(t)) {
handleOption(options.getOption(t));
- }
- else
- {
+ } else {
handleUnknownToken(token);
}
- }
- else if (pos == -1)
- {
+ } else if (pos == -1) {
// no equal sign found (-xxx)
- if (options.hasShortOption(t))
- {
+ if (options.hasShortOption(t)) {
handleOption(options.getOption(t));
- }
- else if (!getMatchingLongOptions(t).isEmpty())
- {
+ } else if (!getMatchingLongOptions(t).isEmpty()) {
// -L or -l
handleLongOptionWithoutEqual(token);
- }
- else
- {
+ } else {
// look for a long prefix (-Xmx512m)
final String opt = getLongPrefix(t);
- if (opt != null && options.getOption(opt).acceptsArg())
- {
+ if (opt != null && options.getOption(opt).acceptsArg()) {
handleOption(options.getOption(opt));
currentOption.addValueForProcessing(t.substring(opt.length()));
currentOption = null;
- }
- else if (isJavaProperty(t))
- {
+ } else if (isJavaProperty(t)) {
// -SV1 (-Dflag)
handleOption(options.getOption(t.substring(0, 1)));
currentOption.addValueForProcessing(t.substring(1));
currentOption = null;
- }
- else
- {
+ } else {
// -S1S2S3 or -S1S2V
handleConcatenatedOptions(token);
}
}
- }
- else
- {
+ } else {
// equal sign found (-xxx=yyy)
final String opt = t.substring(0, pos);
final String value = t.substring(pos + 1);
- if (opt.length() == 1)
- {
+ if (opt.length() == 1) {
// -S=V
final Option option = options.getOption(opt);
- if (option != null && option.acceptsArg())
- {
+ if (option != null && option.acceptsArg()) {
handleOption(option);
currentOption.addValueForProcessing(value);
currentOption = null;
- }
- else
- {
+ } else {
handleUnknownToken(token);
}
- }
- else if (isJavaProperty(opt))
- {
+ } else if (isJavaProperty(opt)) {
// -SV1=V2 (-Dkey=value)
handleOption(options.getOption(opt.substring(0, 1)));
currentOption.addValueForProcessing(opt.substring(1));
currentOption.addValueForProcessing(value);
currentOption = null;
- }
- else
- {
+ } else {
// -L=V or -l=V
handleLongOptionWithEqual(token);
}
@@ -626,17 +504,14 @@ public class DefaultParser implements CommandLineParser
*
* @param token
*/
- private String getLongPrefix(final String token)
- {
+ private String getLongPrefix(final String token) {
final String t = Util.stripLeadingHyphens(token);
int i;
String opt = null;
- for (i = t.length() - 2; i > 1; i--)
- {
+ for (i = t.length() - 2; i > 1; i--) {
final String prefix = t.substring(0, i);
- if (options.hasLongOption(prefix))
- {
+ if (options.hasLongOption(prefix)) {
opt = prefix;
break;
}
@@ -648,16 +523,14 @@ public class DefaultParser implements CommandLineParser
/**
* Check if the specified token is a Java-like property (-Dkey=value).
*/
- private boolean isJavaProperty(final String token)
- {
+ private boolean isJavaProperty(final String token) {
final String opt = token.substring(0, 1);
final Option option = options.getOption(opt);
return option != null && (option.getArgs() >= 2 || option.getArgs() == Option.UNLIMITED_VALUES);
}
- private void handleOption(Option option) throws ParseException
- {
+ private void handleOption(Option option) throws ParseException {
// check the previous option before handling the next one
checkRequiredArgs();
@@ -667,12 +540,9 @@ public class DefaultParser implements CommandLineParser
cmd.addOption(option);
- if (option.hasArg())
- {
+ if (option.hasArg()) {
currentOption = option;
- }
- else
- {
+ } else {
currentOption = null;
}
}
@@ -682,20 +552,16 @@ public class DefaultParser implements CommandLineParser
*
* @param option
*/
- private void updateRequiredOptions(final Option option) throws AlreadySelectedException
- {
- if (option.isRequired())
- {
+ private void updateRequiredOptions(final Option option) throws AlreadySelectedException {
+ if (option.isRequired()) {
expectedOpts.remove(option.getKey());
}
// if the option is in an OptionGroup make that option the selected option of the group
- if (options.getOptionGroup(option) != null)
- {
+ if (options.getOptionGroup(option) != null) {
final OptionGroup group = options.getOptionGroup(option);
- if (group.isRequired())
- {
+ if (group.isRequired()) {
expectedOpts.remove(group);
}
@@ -704,21 +570,17 @@ public class DefaultParser implements CommandLineParser
}
/**
- * Returns a list of matching option strings for the given token, depending
- * on the selected partial matching policy.
+ * Returns a list of matching option strings for the given token, depending on the selected partial matching policy.
*
* @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 List<String> getMatchingLongOptions(final String token)
- {
- if (allowPartialMatching)
- {
+ private List<String> getMatchingLongOptions(final String token) {
+ if (allowPartialMatching) {
return options.getMatchingOptions(token);
}
final List<String> matches = new ArrayList<>(1);
- if (options.hasLongOption(token))
- {
+ if (options.hasLongOption(token)) {
final Option option = options.getOption(token);
matches.add(option.getLongOpt());
}
@@ -727,36 +589,27 @@ public class DefaultParser implements CommandLineParser
}
/**
- * Breaks <code>token</code> into its constituent parts
- * using the following algorithm.
+ * 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>
+ * <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.
+ * @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.
*/
- protected void handleConcatenatedOptions(final String token) throws ParseException
- {
- for (int i = 1; i < token.length(); i++)
- {
+ protected void handleConcatenatedOptions(final String token) throws ParseException {
+ for (int i = 1; i < token.length(); i++) {
final String ch = String.valueOf(token.charAt(i));
if (!options.hasOption(ch)) {
@@ -765,8 +618,7 @@ public class DefaultParser implements CommandLineParser
}
handleOption(options.getOption(ch));
- if (currentOption != null && token.length() != i + 1)
- {
+ if (currentOption != null && token.length() != i + 1) {
// add the trail as an argument of the option
currentOption.addValueForProcessing(token.substring(i + 1));
break;
diff --git a/src/main/java/org/apache/commons/cli/GnuParser.java b/src/main/java/org/apache/commons/cli/GnuParser.java
index f182cae..bc80646 100644
--- a/src/main/java/org/apache/commons/cli/GnuParser.java
+++ b/src/main/java/org/apache/commons/cli/GnuParser.java
@@ -21,88 +21,64 @@ import java.util.ArrayList;
import java.util.List;
/**
- * The class GnuParser provides an implementation of the
- * {@link Parser#flatten(Options, String[], boolean) flatten} method.
+ * The class GnuParser provides an implementation of the {@link Parser#flatten(Options, String[], boolean) flatten}
+ * method.
*
* @deprecated since 1.3, use the {@link DefaultParser} instead
*/
@Deprecated
-public class GnuParser extends Parser
-{
+public class GnuParser extends Parser {
/**
* This flatten method does so using the following rules:
* <ol>
- * <li>If an {@link Option} exists for the first character of
- * the <code>arguments</code> entry <b>AND</b> an {@link Option}
- * does not exist for the whole <code>argument</code> then
- * add the first character as an option to the processed tokens
- * list e.g. "-D" and add the rest of the entry to the also.</li>
- * <li>Otherwise just add the token to the processed tokens list.</li>
+ * <li>If an {@link Option} exists for the first character of the <code>arguments</code> entry <b>AND</b> an
+ * {@link Option} does not exist for the whole <code>argument</code> then add the first character as an option to the
+ * processed tokens list e.g. "-D" and add the rest of the entry to the also.</li>
+ * <li>Otherwise just add the token to the processed tokens list.</li>
* </ol>
*
- * @param options The Options to parse the arguments by.
- * @param arguments The arguments that have to be flattened.
- * @param stopAtNonOption specifies whether to stop flattening when
- * a non option has been encountered
+ * @param options The Options to parse the arguments by.
+ * @param arguments The arguments that have to be flattened.
+ * @param stopAtNonOption specifies whether to stop flattening when a non option has been encountered
* @return a String array of the flattened arguments
*/
@Override
- protected String[] flatten(final Options options, final String[] arguments, final boolean stopAtNonOption)
- {
+ protected String[] flatten(final Options options, final String[] arguments, final boolean stopAtNonOption) {
final List<String> tokens = new ArrayList<>();
boolean eatTheRest = false;
- for (int i = 0; i < arguments.length; i++)
- {
+ for (int i = 0; i < arguments.length; i++) {
final String arg = arguments[i];
- if ("--".equals(arg))
- {
+ if ("--".equals(arg)) {
eatTheRest = true;
tokens.add("--");
- }
- else if ("-".equals(arg))
- {
+ } else if ("-".equals(arg)) {
tokens.add("-");
- }
- else if (arg.startsWith("-"))
- {
+ } else if (arg.startsWith("-")) {
final String opt = Util.stripLeadingHyphens(arg);
- if (options.hasOption(opt))
- {
+ if (options.hasOption(opt)) {
+ tokens.add(arg);
+ } else if (opt.indexOf('=') != -1 && options.hasOption(opt.substring(0, opt.indexOf('=')))) {
+ // the format is --foo=value or -foo=value
+ tokens.add(arg.substring(0, arg.indexOf('='))); // --foo
+ tokens.add(arg.substring(arg.indexOf('=') + 1)); // value
+ } else if (options.hasOption(arg.substring(0, 2))) {
+ // the format is a special properties option (-Dproperty=value)
+ tokens.add(arg.substring(0, 2)); // -D
+ tokens.add(arg.substring(2)); // property=value
+ } else {
+ eatTheRest = stopAtNonOption;
tokens.add(arg);
}
- else
- {
- if (opt.indexOf('=') != -1 && options.hasOption(opt.substring(0, opt.indexOf('='))))
- {
- // the format is --foo=value or -foo=value
- tokens.add(arg.substring(0, arg.indexOf('='))); // --foo
- tokens.add(arg.substring(arg.indexOf('=') + 1)); // value
- }
- else if (options.hasOption(arg.substring(0, 2)))
- {
- // the format is a special properties option (-Dproperty=value)
- tokens.add(arg.substring(0, 2)); // -D
- tokens.add(arg.substring(2)); // property=value
- }
- else
- {
- eatTheRest = stopAtNonOption;
- tokens.add(arg);
- }
- }
- }
- else
- {
+ } else {
tokens.add(arg);
}
- if (eatTheRest)
- {
- for (i++; i < arguments.length; i++) //NOPMD
+ if (eatTheRest) {
+ for (i++; i < arguments.length; i++) // NOPMD
{
tokens.add(arguments[i]);
}
diff --git a/src/main/java/org/apache/commons/cli/HelpFormatter.java b/src/main/java/org/apache/commons/cli/HelpFormatter.java
index d159793..d177860 100644
--- a/src/main/java/org/apache/commons/cli/HelpFormatter.java
+++ b/src/main/java/org/apache/commons/cli/HelpFormatter.java
@@ -33,19 +33,14 @@ import java.util.List;
/**
* A formatter of help messages for command line options.
*
- * <p>Example:</p>
+ * <p>
+ * Example:
+ * </p>
*
* <pre>
* Options options = new Options();
- * options.addOption(OptionBuilder.withLongOpt("file")
- * .withDescription("The file to be processed")
- * .hasArg()
- * .withArgName("FILE")
- * .isRequired()
- * .create('f'));
- * options.addOption(OptionBuilder.withLongOpt("version")
- * .withDescription("Print the version of the application")
- * .create('v'));
+ * options.addOption(OptionBuilder.withLongOpt("file").withDescription("The file to be processed").hasArg().withArgName("FILE").isRequired().create('f'));
+ * options.addOption(OptionBuilder.withLongOpt("version").withDescription("Print the version of the application").create('v'));
* options.addOption(OptionBuilder.withLongOpt("help").create('h'));
*
* String header = "Do something useful with an input file\n\n";
@@ -68,8 +63,7 @@ import java.util.List;
* Please report issues at http://example.com/issues
* </pre>
*/
-public class HelpFormatter
-{
+public class HelpFormatter {
// --------------------------------------------------------------- Constants
/** default number of characters per line */
@@ -100,13 +94,10 @@ public class HelpFormatter
/** default name for an argument */
public static final String DEFAULT_ARG_NAME = "arg";
- // -------------------------------------------------------------- Attributes
-
/**
* number of characters per line
*
- * @deprecated Scope will be made private for next major version
- * - use get/setWidth methods instead.
+ * @deprecated Scope will be made private for next major version - use get/setWidth methods instead.
*/
@Deprecated
public int defaultWidth = DEFAULT_WIDTH;
@@ -114,18 +105,15 @@ public class HelpFormatter
/**
* amount of padding to the left of each line
*
- * @deprecated Scope will be made private for next major version
- * - use get/setLeftPadding methods instead.
+ * @deprecated Scope will be made private for next major version - use get/setLeftPadding methods instead.
*/
@Deprecated
public int defaultLeftPad = DEFAULT_LEFT_PAD;
/**
- * the number of characters of padding to be prefixed
- * to each description line
+ * the number of characters of padding to be prefixed to each description line
*
- * @deprecated Scope will be made private for next major version
- * - use get/setDescPadding methods instead.
+ * @deprecated Scope will be made private for next major version - use get/setDescPadding methods instead.
*/
@Deprecated
public int defaultDescPad = DEFAULT_DESC_PAD;
@@ -133,8 +121,7 @@ public class HelpFormatter
/**
* the string to display at the beginning of the usage statement
*
- * @deprecated Scope will be made private for next major version
- * - use get/setSyntaxPrefix methods instead.
+ * @deprecated Scope will be made private for next major version - use get/setSyntaxPrefix methods instead.
*/
@Deprecated
public String defaultSyntaxPrefix = DEFAULT_SYNTAX_PREFIX;
@@ -142,8 +129,7 @@ public class HelpFormatter
/**
* the new line string
*
- * @deprecated Scope will be made private for next major version
- * - use get/setNewLine methods instead.
+ * @deprecated Scope will be made private for next major version - use get/setNewLine methods instead.
*/
@Deprecated
public String defaultNewLine = System.getProperty("line.separator");
@@ -151,8 +137,7 @@ public class HelpFormatter
/**
* the shortOpt prefix
*
- * @deprecated Scope will be made private for next major version
- * - use get/setOptPrefix methods instead.
+ * @deprecated Scope will be made private for next major version - use get/setOptPrefix methods instead.
*/
@Deprecated
public String defaultOptPrefix = DEFAULT_OPT_PREFIX;
@@ -160,8 +145,7 @@ public class HelpFormatter
/**
* the long Opt prefix
*
- * @deprecated Scope will be made private for next major version
- * - use get/setLongOptPrefix methods instead.
+ * @deprecated Scope will be made private for next major version - use get/setLongOptPrefix methods instead.
*/
@Deprecated
public String defaultLongOptPrefix = DEFAULT_LONG_OPT_PREFIX;
@@ -169,8 +153,7 @@ public class HelpFormatter
/**
* the name of the argument
*
- * @deprecated Scope will be made private for next major version
- * - use get/setArgName methods instead.
+ * @deprecated Scope will be made private for next major version - use get/setArgName methods instead.
*/
@Deprecated
public String defaultArgName = DEFAULT_ARG_NAME;
@@ -190,8 +173,7 @@ public class HelpFormatter
*
* @param width the new value of 'width'
*/
- public void setWidth(final int width)
- {
+ public void setWidth(final int width) {
this.defaultWidth = width;
}
@@ -200,8 +182,7 @@ public class HelpFormatter
*
* @return the 'width'
*/
- public int getWidth()
- {
+ public int getWidth() {
return defaultWidth;
}
@@ -210,8 +191,7 @@ public class HelpFormatter
*
* @param padding the new value of 'leftPadding'
*/
- public void setLeftPadding(final int padding)
- {
+ public void setLeftPadding(final int padding) {
this.defaultLeftPad = padding;
}
@@ -220,8 +200,7 @@ public class HelpFormatter
*
* @return the 'leftPadding'
*/
- public int getLeftPadding()
- {
+ public int getLeftPadding() {
return defaultLeftPad;
}
@@ -230,8 +209,7 @@ public class HelpFormatter
*
* @param padding the new value of 'descPadding'
*/
- public void setDescPadding(final int padding)
- {
+ public void setDescPadding(final int padding) {
this.defaultDescPad = padding;
}
@@ -240,8 +218,7 @@ public class HelpFormatter
*
* @return the 'descPadding'
*/
- public int getDescPadding()
- {
+ public int getDescPadding() {
return defaultDescPad;
}
@@ -250,8 +227,7 @@ public class HelpFormatter
*
* @param prefix the new value of 'syntaxPrefix'
*/
- public void setSyntaxPrefix(final String prefix)
- {
+ public void setSyntaxPrefix(final String prefix) {
this.defaultSyntaxPrefix = prefix;
}
@@ -260,8 +236,7 @@ public class HelpFormatter
*
* @return the 'syntaxPrefix'
*/
- public String getSyntaxPrefix()
- {
+ public String getSyntaxPrefix() {
return defaultSyntaxPrefix;
}
@@ -270,8 +245,7 @@ public class HelpFormatter
*
* @param newline the new value of 'newLine'
*/
- public void setNewLine(final String newline)
- {
+ public void setNewLine(final String newline) {
this.defaultNewLine = newline;
}
@@ -280,8 +254,7 @@ public class HelpFormatter
*
* @return the 'newLine'
*/
- public String getNewLine()
- {
+ public String getNewLine() {
return defaultNewLine;
}
@@ -290,8 +263,7 @@ public class HelpFormatter
*
* @param prefix the new value of 'optPrefix'
*/
- public void setOptPrefix(final String prefix)
- {
+ public void setOptPrefix(final String prefix) {
this.defaultOptPrefix = prefix;
}
@@ -300,8 +272,7 @@ public class HelpFormatter
*
* @return the 'optPrefix'
*/
- public String getOptPrefix()
- {
+ public String getOptPrefix() {
return defaultOptPrefix;
}
@@ -310,8 +281,7 @@ public class HelpFormatter
*
* @param prefix the new value of 'longOptPrefix'
*/
- public void setLongOptPrefix(final String prefix)
- {
+ public void setLongOptPrefix(final String prefix) {
this.defaultLongOptPrefix = prefix;
}
@@ -320,21 +290,18 @@ public class HelpFormatter
*
* @return the 'longOptPrefix'
*/
- public String getLongOptPrefix()
- {
+ public String getLongOptPrefix() {
return defaultLongOptPrefix;
}
/**
- * Set the separator displayed between a long option and its value.
- * Ensure that the separator specified is supported by the parser used,
- * typically ' ' or '='.
+ * 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)
- {
+ public void setLongOptSeparator(final String longOptSeparator) {
this.longOptSeparator = longOptSeparator;
}
@@ -344,8 +311,7 @@ public class HelpFormatter
* @return the separator
* @since 1.3
*/
- public String getLongOptSeparator()
- {
+ public String getLongOptSeparator() {
return longOptSeparator;
}
@@ -354,8 +320,7 @@ public class HelpFormatter
*
* @param name the new value of 'argName'
*/
- public void setArgName(final String name)
- {
+ public void setArgName(final String name) {
this.defaultArgName = name;
}
@@ -364,99 +329,85 @@ public class HelpFormatter
*
* @return the 'argName'
*/
- public String getArgName()
- {
+ public String getArgName() {
return defaultArgName;
}
/**
- * Comparator used to sort the options when they output in help text.
- * Defaults to case-insensitive alphabetical sorting by option key.
+ * Comparator used to sort the options when they output in help text. Defaults to case-insensitive alphabetical sorting
+ * by option key.
*
* @return the {@link Comparator} currently in use to sort the options
* @since 1.2
*/
- public Comparator<Option> getOptionComparator()
- {
+ public Comparator<Option> getOptionComparator() {
return optionComparator;
}
/**
- * 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.
+ * 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)
- {
+ 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.
+ * 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)
- {
+ 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.
+ * 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
- * @param autoUsage whether to print an automatically generated
- * usage statement
+ * @param autoUsage whether to print an automatically generated usage statement
*/
- public void printHelp(final String cmdLineSyntax, final Options options, final boolean autoUsage)
- {
+ public void printHelp(final String cmdLineSyntax, final Options options, final boolean autoUsage) {
printHelp(getWidth(), cmdLineSyntax, null, options, null, autoUsage);
}
/**
- * Print the help for <code>options</code> with the specified
- * command line syntax. This method prints help information to
- * System.out.
+ * 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 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)
- {
+ public void printHelp(final String cmdLineSyntax, final String header, final Options options, final String footer) {
printHelp(cmdLineSyntax, header, options, footer, false);
}
/**
- * Print the help for <code>options</code> with the specified
- * command line syntax. This method prints help information to
- * System.out.
+ * 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 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
+ * @param autoUsage whether to print an automatically generated usage statement
*/
- public void printHelp(final String cmdLineSyntax, final String header, final Options options, final String footer, final boolean autoUsage)
- {
+ 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);
}
/**
- * Print the help for <code>options</code> with the specified
- * command line syntax. This method prints help information to
- * System.out.
+ * Print the help for <code>options</code> with the specified command line syntax. This method prints help information
+ * to System.out.
*
* @param width the number of characters to be displayed on each line
* @param cmdLineSyntax the syntax for this application
@@ -464,27 +415,23 @@ public class HelpFormatter
* @param options the Options instance
* @param footer the banner to display at the end of the help
*/
- public void printHelp(final int width, final String cmdLineSyntax, final String header, final Options options, final String footer)
- {
+ public void printHelp(final int width, final String cmdLineSyntax, final String header, final Options options, final String footer) {
printHelp(width, cmdLineSyntax, header, options, footer, false);
}
/**
- * Print the help for <code>options</code> with the specified
- * command line syntax. This method prints help information to
- * System.out.
+ * Print the help for <code>options</code> with the specified command line syntax. This method prints help information
+ * to System.out.
*
* @param width the number of characters to be displayed on each line
* @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
+ * @param autoUsage whether to print an automatically generated usage statement
*/
- public void printHelp(final int width, final String cmdLineSyntax, final String header,
- final Options options, final String footer, final boolean autoUsage)
- {
+ public void printHelp(final int width, final String cmdLineSyntax, final String header, final Options options, final String footer,
+ final boolean autoUsage) {
final PrintWriter pw = new PrintWriter(System.out);
printHelp(pw, width, cmdLineSyntax, header, options, getLeftPadding(), getDescPadding(), footer, autoUsage);
@@ -492,76 +439,58 @@ public class HelpFormatter
}
/**
- * Print the help for <code>options</code> with the specified
- * command line syntax.
+ * Print the help for <code>options</code> with the specified command line syntax.
*
* @param pw the writer to which the help will be written
* @param width the number of characters to be displayed on each line
* @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 leftPad the number of characters of padding to be prefixed
- * to each line
- * @param descPad the number of characters of padding to be prefixed
- * to each description line
+ * @param leftPad the number of characters of padding to be prefixed to each line
+ * @param descPad the number of characters of padding to be prefixed to each description line
* @param footer the banner to display at the end of the help
*
* @throws IllegalStateException if there is no room to print a line
*/
- public void printHelp(final PrintWriter pw, final int width, final String cmdLineSyntax,
- final String header, final Options options, final int leftPad,
- final int descPad, final String footer)
- {
+ public void printHelp(final PrintWriter pw, final int width, final String cmdLineSyntax, final String header, final Options options, final int leftPad,
+ final int descPad, final String footer) {
printHelp(pw, width, cmdLineSyntax, header, options, leftPad, descPad, footer, false);
}
-
/**
- * Print the help for <code>options</code> with the specified
- * command line syntax.
+ * Print the help for <code>options</code> with the specified command line syntax.
*
* @param pw the writer to which the help will be written
* @param width the number of characters to be displayed on each line
* @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 leftPad the number of characters of padding to be prefixed
- * to each line
- * @param descPad the number of characters of padding to be prefixed
- * to each description line
+ * @param leftPad the number of characters of padding to be prefixed to each line
+ * @param descPad the number of characters of padding to be prefixed to each description line
* @param footer the banner to display at the end of the help
- * @param autoUsage whether to print an automatically generated
- * usage statement
+ * @param autoUsage whether to print an automatically generated usage statement
*
* @throws IllegalStateException if there is no room to print a line
*/
- public void printHelp(final PrintWriter pw, final int width, final String cmdLineSyntax,
- final String header, final Options options, final int leftPad,
- final int descPad, final String footer, final boolean autoUsage)
- {
- if (cmdLineSyntax == null || cmdLineSyntax.isEmpty())
- {
+ public void printHelp(final PrintWriter pw, final int width, final String cmdLineSyntax, final String header, final Options options, final int leftPad,
+ final int descPad, final String footer, final boolean autoUsage) {
+ if (cmdLineSyntax == null || cmdLineSyntax.isEmpty()) {
throw new IllegalArgumentException("cmdLineSyntax not provided");
}
- if (autoUsage)
- {
+ if (autoUsage) {
printUsage(pw, width, cmdLineSyntax, options);
- }
- else
- {
+ } else {
printUsage(pw, width, cmdLineSyntax);
}
- if (header != null && !header.trim().isEmpty())
- {
+ if (header != null && !header.trim().isEmpty()) {
printWrapped(pw, width, header);
}
printOptions(pw, width, options, leftPad, descPad);
- if (footer != null && !footer.trim().isEmpty())
- {
+ if (footer != null && !footer.trim().isEmpty()) {
printWrapped(pw, width, footer);
}
}
@@ -574,8 +503,7 @@ public class HelpFormatter
* @param app The application name
* @param options The command line Options
*/
- public void printUsage(final PrintWriter pw, final int width, final String app, final Options options)
- {
+ 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(" ");
@@ -583,13 +511,11 @@ public class HelpFormatter
final Collection<OptionGroup> processedGroups = new ArrayList<>();
final List<Option> optList = new ArrayList<>(options.getOptions());
- if (getOptionComparator() != null)
- {
+ if (getOptionComparator() != null) {
Collections.sort(optList, getOptionComparator());
}
// iterate over the options
- for (final Iterator<Option> it = optList.iterator(); it.hasNext();)
- {
+ for (final Iterator<Option> it = optList.iterator(); it.hasNext();) {
// get the next Option
final Option option = it.next();
@@ -597,15 +523,12 @@ public class HelpFormatter
final OptionGroup group = options.getOptionGroup(option);
// if the option is part of a group
- if (group != null)
- {
+ if (group != null) {
// and if the group has not already been processed
- if (!processedGroups.contains(group))
- {
+ if (!processedGroups.contains(group)) {
// add the group to the processed list
processedGroups.add(group);
-
// add the usage clause
appendOptionGroup(buff, group);
}
@@ -615,56 +538,47 @@ public class HelpFormatter
}
// if the Option is not part of an OptionGroup
- else
- {
+ else {
appendOption(buff, option, option.isRequired());
}
- if (it.hasNext())
- {
+ if (it.hasNext()) {
buff.append(" ");
}
}
-
// call printWrapped
printWrapped(pw, width, buff.toString().indexOf(' ') + 1, buff.toString());
}
/**
- * 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
+ * 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 buff the StringBuffer to append to
* @param group the group to append
* @see #appendOption(StringBuffer,Option,boolean)
*/
- private void appendOptionGroup(final StringBuffer buff, final OptionGroup group)
- {
- if (!group.isRequired())
- {
+ 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)
- {
+ if (getOptionComparator() != null) {
Collections.sort(optList, getOptionComparator());
}
// for each option in the OptionGroup
- for (final Iterator<Option> it = optList.iterator(); it.hasNext();)
- {
+ 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())
- {
+ if (it.hasNext()) {
buff.append(" | ");
}
}
- if (!group.isRequired())
- {
+ if (!group.isRequired()) {
buff.append("]");
}
}
@@ -676,66 +590,53 @@ public class HelpFormatter
* @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)
- {
+ private void appendOption(final StringBuffer buff, final Option option, final boolean required) {
+ if (!required) {
buff.append("[");
}
- if (option.getOpt() != null)
- {
+ if (option.getOpt() != null) {
buff.append("-").append(option.getOpt());
- }
- else
- {
+ } 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()))
- {
+ 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)
- {
+ if (!required) {
buff.append("]");
}
}
/**
- * Print the cmdLineSyntax to the specified writer, using the
- * specified width.
+ * 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)
- {
+ 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);
}
/**
- * Print the help for the specified Options to the specified writer,
- * using the specified width, left padding and description padding.
+ * Print the help for the specified Options to the specified writer, using the specified width, left padding and
+ * description padding.
*
* @param pw The printWriter to write the help to
* @param width The number of characters to display per line
* @param options The command line Options
- * @param leftPad the number of characters of padding to be prefixed
- * to each line
- * @param descPad the number of characters of padding to be prefixed
- * to each description line
+ * @param leftPad the number of characters of padding to be prefixed to each line
+ * @param descPad the number of characters of padding to be prefixed to each description line
*/
- public void printOptions(final PrintWriter pw, final int width, final Options options,
- final int leftPad, final int descPad)
- {
+ public void printOptions(final PrintWriter pw, final int width, final Options options, final int leftPad, final int descPad) {
final StringBuffer sb = new StringBuffer();
renderOptions(sb, width, options, leftPad, descPad);
@@ -749,8 +650,7 @@ public class HelpFormatter
* @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)
- {
+ public void printWrapped(final PrintWriter pw, final int width, final String text) {
printWrapped(pw, width, 0, text);
}
@@ -762,8 +662,7 @@ public class HelpFormatter
* @param nextLineTabStop The position on the next line for the first tab.
* @param text The text to be written to the PrintWriter
*/
- public void printWrapped(final PrintWriter pw, final int width, final int nextLineTabStop, final String text)
- {
+ public void printWrapped(final PrintWriter pw, final int width, final int nextLineTabStop, final String text) {
final StringBuffer sb = new StringBuffer(text.length());
renderWrappedTextBlock(sb, width, nextLineTabStop, text);
@@ -773,21 +672,17 @@ public class HelpFormatter
// --------------------------------------------------------------- Protected
/**
- * Render the specified Options and return the rendered Options
- * in a StringBuffer.
+ * Render the specified Options and return the rendered Options in a StringBuffer.
*
* @param sb The StringBuffer to place the rendered Options into.
* @param width The number of characters to display per line
* @param options The command line Options
- * @param leftPad the number of characters of padding to be prefixed
- * to each line
- * @param descPad the number of characters of padding to be prefixed
- * to each description line
+ * @param leftPad the number of characters of padding to be prefixed to each line
+ * @param descPad the number of characters of padding to be prefixed to each description line
*
* @return the StringBuffer with the rendered Options contents.
*/
- protected StringBuffer renderOptions(final StringBuffer sb, final int width, final Options options, final int leftPad, final int descPad)
- {
+ protected StringBuffer renderOptions(final StringBuffer sb, final int width, final Options options, final int leftPad, final int descPad) {
final String lpad = createPadding(leftPad);
final String dpad = createPadding(descPad);
@@ -800,39 +695,29 @@ public class HelpFormatter
final List<Option> optList = options.helpOptions();
- if (getOptionComparator() != null)
- {
+ if (getOptionComparator() != null) {
Collections.sort(optList, getOptionComparator());
}
- for (final Option option : optList)
- {
+ for (final Option option : optList) {
final StringBuffer optBuf = new StringBuffer();
- if (option.getOpt() == null)
- {
+ if (option.getOpt() == null) {
optBuf.append(lpad).append(" ").append(getLongOptPrefix()).append(option.getLongOpt());
- }
- else
- {
+ } else {
optBuf.append(lpad).append(getOptPrefix()).append(option.getOpt());
- if (option.hasLongOpt())
- {
+ if (option.hasLongOpt()) {
optBuf.append(',').append(getLongOptPrefix()).append(option.getLongOpt());
}
}
- if (option.hasArg())
- {
+ if (option.hasArg()) {
final String argName = option.getArgName();
- if (argName != null && argName.isEmpty())
- {
+ if (argName != null && argName.isEmpty()) {
// if the option has a blank argname
optBuf.append(' ');
- }
- else
- {
+ } else {
optBuf.append(option.hasLongOpt() ? longOptSeparator : " ");
optBuf.append("<").append(argName != null ? option.getArgName() : getArgName()).append(">");
}
@@ -844,13 +729,11 @@ public class HelpFormatter
int x = 0;
- for (final Iterator<Option> it = optList.iterator(); it.hasNext();)
- {
+ for (final Iterator<Option> it = optList.iterator(); it.hasNext();) {
final Option option = it.next();
final StringBuilder optBuf = new StringBuilder(prefixList.get(x++).toString());
- if (optBuf.length() < max)
- {
+ if (optBuf.length() < max) {
optBuf.append(createPadding(max - optBuf.length()));
}
@@ -858,15 +741,13 @@ public class HelpFormatter
final int nextLineTabStop = max + descPad;
- if (option.getDescription() != null)
- {
+ if (option.getDescription() != null) {
optBuf.append(option.getDescription());
}
renderWrappedText(sb, width, nextLineTabStop, optBuf.toString());
- if (it.hasNext())
- {
+ if (it.hasNext()) {
sb.append(getNewLine());
}
}
@@ -875,8 +756,7 @@ public class HelpFormatter
}
/**
- * Render the specified text and return the rendered Options
- * in a StringBuffer.
+ * Render the specified text and return the rendered Options in a StringBuffer.
*
* @param sb The StringBuffer to place the rendered text into.
* @param width The number of characters to display per line
@@ -885,21 +765,17 @@ public class HelpFormatter
*
* @return the StringBuffer with the rendered Options contents.
*/
- protected StringBuffer renderWrappedText(final StringBuffer sb, final int width,
- int nextLineTabStop, String text)
- {
+ protected StringBuffer renderWrappedText(final StringBuffer sb, final int width, int nextLineTabStop, String text) {
int pos = findWrapPos(text, width, 0);
- if (pos == -1)
- {
+ if (pos == -1) {
sb.append(rtrim(text));
return sb;
}
sb.append(rtrim(text.substring(0, pos))).append(getNewLine());
- if (nextLineTabStop >= width)
- {
+ if (nextLineTabStop >= width) {
// stops infinite loop happening
nextLineTabStop = 1;
}
@@ -907,20 +783,17 @@ public class HelpFormatter
// all following lines must be padded with nextLineTabStop space characters
final String padding = createPadding(nextLineTabStop);
- while (true)
- {
+ while (true) {
text = padding + text.substring(pos).trim();
pos = findWrapPos(text, width, 0);
- if (pos == -1)
- {
+ if (pos == -1) {
sb.append(text);
return sb;
}
- if (text.length() > width && pos == nextLineTabStop - 1)
- {
+ if (text.length() > width && pos == nextLineTabStop - 1) {
pos = width;
}
@@ -929,35 +802,28 @@ public class HelpFormatter
}
/**
- * Render the specified text width a maximum width. This method differs
- * from renderWrappedText by not removing leading spaces after a new line.
+ * Render the specified text width a maximum width. This method differs from renderWrappedText by not removing leading
+ * spaces after a new line.
*
* @param sb The StringBuffer to place the rendered text into.
* @param width The number of characters to display per line
* @param nextLineTabStop The position on the next line for the first tab.
* @param text The text to be rendered.
*/
- private Appendable renderWrappedTextBlock(final StringBuffer sb, final int width, final int nextLineTabStop, final String text)
- {
- try
- {
+ private Appendable renderWrappedTextBlock(final StringBuffer sb, final int width, final int nextLineTabStop, final String text) {
+ try {
final BufferedReader in = new BufferedReader(new StringReader(text));
String line;
boolean firstLine = true;
- while ((line = in.readLine()) != null)
- {
- if (!firstLine)
- {
+ while ((line = in.readLine()) != null) {
+ if (!firstLine) {
sb.append(getNewLine());
- }
- else
- {
+ } else {
firstLine = false;
}
renderWrappedText(sb, width, nextLineTabStop, line);
}
- }
- catch (final IOException e) //NOPMD
+ } catch (final IOException e) // NOPMD
{
// cannot happen
}
@@ -966,52 +832,41 @@ 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.
+ * 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.
*
* @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 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
*/
- protected int findWrapPos(final String text, final int width, final int startPos)
- {
+ 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)
- {
+ if (pos != -1 && pos <= width) {
return pos + 1;
}
pos = text.indexOf('\t', startPos);
- if (pos != -1 && pos <= width)
- {
+ if (pos != -1 && pos <= width) {
return pos + 1;
}
- if (startPos + width >= text.length())
- {
+ if (startPos + width >= text.length()) {
return -1;
}
// look for the last whitespace character before startPos+width
- for (pos = startPos + width; pos >= startPos; --pos)
- {
+ for (pos = startPos + width; pos >= startPos; --pos) {
final char c = text.charAt(pos);
- if (c == ' ' || c == '\n' || c == '\r')
- {
+ if (c == ' ' || c == '\n' || c == '\r') {
break;
}
}
// if we found it - just return
- if (pos > startPos)
- {
+ if (pos > startPos) {
return pos;
}
@@ -1028,8 +883,7 @@ public class HelpFormatter
*
* @return The String of padding
*/
- protected String createPadding(final int len)
- {
+ protected String createPadding(final int len) {
final char[] padding = new char[len];
Arrays.fill(padding, ' ');
@@ -1043,49 +897,38 @@ public class HelpFormatter
*
* @return The String of without the trailing padding
*/
- protected String rtrim(final String s)
- {
- if (s == null || s.isEmpty())
- {
+ protected String rtrim(final String s) {
+ if (s == null || s.isEmpty()) {
return s;
}
int pos = s.length();
- while (pos > 0 && Character.isWhitespace(s.charAt(pos - 1)))
- {
+ while (pos > 0 && Character.isWhitespace(s.charAt(pos - 1))) {
--pos;
}
return s.substring(0, pos);
}
- // ------------------------------------------------------ Package protected
- // ---------------------------------------------------------------- Private
- // ---------------------------------------------------------- Inner classes
/**
- * This class implements the <code>Comparator</code> interface
- * for comparing Options.
+ * This class implements the <code>Comparator</code> interface for comparing Options.
*/
- private static class OptionComparator implements Comparator<Option>, Serializable
- {
+ 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
+ * 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.
+ * @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)
- {
+ public int compare(final Option opt1, final Option opt2) {
return opt1.getKey().compareToIgnoreCase(opt2.getKey());
}
}
diff --git a/src/main/java/org/apache/commons/cli/MissingArgumentException.java b/src/main/java/org/apache/commons/cli/MissingArgumentException.java
index 75af8f0..8e98e79 100644
--- a/src/main/java/org/apache/commons/cli/MissingArgumentException.java
+++ b/src/main/java/org/apache/commons/cli/MissingArgumentException.java
@@ -18,11 +18,9 @@
package org.apache.commons.cli;
/**
- * Thrown when an option requiring an argument
- * is not provided with an argument.
+ * Thrown when an option requiring an argument is not provided with an argument.
*/
-public class MissingArgumentException extends ParseException
-{
+public class MissingArgumentException extends ParseException {
/**
* This exception {@code serialVersionUID}.
*/
@@ -32,38 +30,32 @@ public class MissingArgumentException extends ParseException
private Option option;
/**
- * Construct a new <code>MissingArgumentException</code>
- * with the specified detail message.
+ * Construct a new <code>MissingArgumentException</code> with the specified detail message.
*
* @param message the detail message
*/
- public MissingArgumentException(final String message)
- {
+ public MissingArgumentException(final String message) {
super(message);
}
/**
- * Construct a new <code>MissingArgumentException</code>
- * with the specified detail message.
+ * Construct a new <code>MissingArgumentException</code> with the specified detail message.
*
* @param option the option requiring an argument
* @since 1.2
*/
- public MissingArgumentException(final Option option)
- {
+ public MissingArgumentException(final Option option) {
this("Missing argument for option: " + option.getKey());
this.option = option;
}
/**
- * Return the option requiring an argument that wasn't provided
- * on the command line.
+ * Return the option requiring an argument that wasn't provided on the command line.
*
* @return the related option
* @since 1.2
*/
- public Option getOption()
- {
+ public Option getOption() {
return option;
}
}
diff --git a/src/main/java/org/apache/commons/cli/MissingOptionException.java b/src/main/java/org/apache/commons/cli/MissingOptionException.java
index 9c66678..c18cb2c 100644
--- a/src/main/java/org/apache/commons/cli/MissingOptionException.java
+++ b/src/main/java/org/apache/commons/cli/MissingOptionException.java
@@ -17,14 +17,13 @@
package org.apache.commons.cli;
-import java.util.List;
import java.util.Iterator;
+import java.util.List;
/**
* Thrown when a required option has not been provided.
*/
-public class MissingOptionException extends ParseException
-{
+public class MissingOptionException extends ParseException {
/** This exception {@code serialVersionUID}. */
private static final long serialVersionUID = 8161889051578563249L;
@@ -32,25 +31,21 @@ public class MissingOptionException extends ParseException
private List missingOptions;
/**
- * Construct a new <code>MissingSelectedException</code>
- * with the specified detail message.
+ * Construct a new <code>MissingSelectedException</code> with the specified detail message.
*
* @param message the detail message
*/
- public MissingOptionException(final String message)
- {
+ public MissingOptionException(final String message) {
super(message);
}
/**
- * Constructs a new <code>MissingSelectedException</code> with the
- * specified list of missing options.
+ * Constructs a new <code>MissingSelectedException</code> with the specified list of missing options.
*
* @param missingOptions the list of missing options and groups
* @since 1.2
*/
- public MissingOptionException(final List missingOptions)
- {
+ public MissingOptionException(final List missingOptions) {
this(createMessage(missingOptions));
this.missingOptions = missingOptions;
}
@@ -58,12 +53,11 @@ public class MissingOptionException extends ParseException
/**
* Returns the list of options or option groups missing in the command line parsed.
*
- * @return the missing options, consisting of String instances for simple
- * options, and OptionGroup instances for required option groups.
+ * @return the missing options, consisting of String instances for simple options, and OptionGroup instances for
+ * required option groups.
* @since 1.2
*/
- public List getMissingOptions()
- {
+ public List getMissingOptions() {
return missingOptions;
}
@@ -73,18 +67,15 @@ public class MissingOptionException extends ParseException
* @param missingOptions the list of missing options and groups
* @since 1.2
*/
- private static String createMessage(final List<?> missingOptions)
- {
+ 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())
- {
+ while (it.hasNext()) {
buf.append(it.next());
- if (it.hasNext())
- {
+ if (it.hasNext()) {
buf.append(", ");
}
}
diff --git a/src/main/java/org/apache/commons/cli/Option.java b/src/main/java/org/apache/commons/cli/Option.java
index 7687e6f..d61878d 100644
--- a/src/main/java/org/apache/commons/cli/Option.java
+++ b/src/main/java/org/apache/commons/cli/Option.java
@@ -22,23 +22,20 @@ import java.util.ArrayList;
import java.util.List;
/**
- * Describes a single command-line option. It maintains
- * information regarding the short-name of the option, the long-name,
- * if any exists, a flag indicating if an argument is required for
- * this option, and a self-documenting description of the option.
+ * Describes a single command-line option. It maintains information regarding the short-name of the option, the
+ * long-name, if any exists, a flag indicating if an argument is required for this option, and a self-documenting
+ * description of the option.
* <p>
- * An Option is not created independently, but is created through
- * an instance of {@link Options}. An Option is required to have
- * at least a short or a long-name.
+ * An Option is not created independently, but is created through an instance of {@link Options}. An Option is required
+ * to have at least a short or a long-name.
* <p>
- * <b>Note:</b> once an {@link Option} has been added to an instance
- * of {@link Options}, its required flag cannot be changed.
+ * <b>Note:</b> once an {@link Option} has been added to an instance of {@link Options}, its required flag cannot be
+ * changed.
*
* @see org.apache.commons.cli.Options
* @see org.apache.commons.cli.CommandLine
*/
-public class Option implements Cloneable, Serializable
-{
+public class Option implements Cloneable, Serializable {
/** constant that specifies the number of argument values has not been specified */
public static final int UNINITIALIZED = -1;
@@ -83,8 +80,7 @@ public class Option implements Cloneable, Serializable
*
* @param builder builder used to create this option
*/
- private Option(final Builder builder)
- {
+ private Option(final Builder builder) {
this.argName = builder.argName;
this.description = builder.description;
this.longOpt = builder.longOpt;
@@ -97,17 +93,14 @@ 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. The option does not take an argument.
*
* @param opt short representation of the option
* @param description describes the function of the option
*
- * @throws IllegalArgumentException if there are any non valid
- * Option characters in <code>opt</code>.
+ * @throws IllegalArgumentException if there are any non valid Option characters in <code>opt</code>.
*/
- public Option(final String opt, final String description) throws IllegalArgumentException
- {
+ public Option(final String opt, final String description) throws IllegalArgumentException {
this(opt, null, false, description);
}
@@ -118,11 +111,9 @@ public class Option implements Cloneable, Serializable
* @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>.
+ * @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
- {
+ public Option(final String opt, final boolean hasArg, final String description) throws IllegalArgumentException {
this(opt, null, hasArg, description);
}
@@ -134,12 +125,9 @@ public class Option implements Cloneable, Serializable
* @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>.
+ * @throws IllegalArgumentException if there are any non valid Option characters in <code>opt</code>.
*/
- public Option(final String opt, final String longOpt, final boolean hasArg, final String description)
- throws IllegalArgumentException
- {
+ public Option(final String opt, final String longOpt, final boolean hasArg, final String description) throws IllegalArgumentException {
// ensure that the option is valid
OptionValidator.validateOption(opt);
@@ -147,8 +135,7 @@ public class Option implements Cloneable, Serializable
this.longOpt = longOpt;
// if hasArg is set then the number of arguments is 1
- if (hasArg)
- {
+ if (hasArg) {
this.numberOfArgs = 1;
}
@@ -156,14 +143,12 @@ 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.
+ * Returns the id of this Option. This is only set when the Option shortOpt is a single character. This is used for
+ * switch statements.
*
* @return the id of this Option
*/
- public int getId()
- {
+ public int getId() {
return getKey().charAt(0);
}
@@ -172,8 +157,7 @@ public class Option implements Cloneable, Serializable
*
* @return the 'unique' Option identifier
*/
- String getKey()
- {
+ String getKey() {
// if 'opt' is null, then it is a 'long' option
return (opt == null) ? longOpt : opt;
}
@@ -181,15 +165,12 @@ public class Option implements Cloneable, Serializable
/**
* Retrieve the name of this Option.
*
- * 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.
+ * 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 String getOpt()
- {
+ public String getOpt() {
return opt;
}
@@ -198,23 +179,21 @@ public class Option implements Cloneable, Serializable
*
* @return The type of this option
*/
- public Object getType()
- {
+ public Object getType() {
return type;
}
/**
* 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.
+ * <b>Note:</b> this method is kept for binary compatibility and the input type is supposed to be a {@link Class}
+ * object.
*
* @param type the type of this Option
* @deprecated since 1.3, use {@link #setType(Class)} instead
*/
@Deprecated
- public void setType(final Object type)
- {
+ public void setType(final Object type) {
setType((Class<?>) type);
}
@@ -224,8 +203,7 @@ public class Option implements Cloneable, Serializable
* @param type the type of this Option
* @since 1.3
*/
- public void setType(final Class<?> type)
- {
+ public void setType(final Class<?> type) {
this.type = type;
}
@@ -234,8 +212,7 @@ public class Option implements Cloneable, Serializable
*
* @return Long name of this option, or null, if there is no long name
*/
- public String getLongOpt()
- {
+ public String getLongOpt() {
return longOpt;
}
@@ -244,27 +221,23 @@ public class Option implements Cloneable, Serializable
*
* @param longOpt the long name of this Option
*/
- public void setLongOpt(final String longOpt)
- {
+ public void setLongOpt(final String longOpt) {
this.longOpt = longOpt;
}
/**
* Sets whether this Option can have an optional argument.
*
- * @param optionalArg specifies whether the Option can have
- * an optional argument.
+ * @param optionalArg specifies whether the Option can have an optional argument.
*/
- public void setOptionalArg(final boolean optionalArg)
- {
+ public void setOptionalArg(final boolean optionalArg) {
this.optionalArg = optionalArg;
}
/**
* @return whether this Option can have an optional argument
*/
- public boolean hasOptionalArg()
- {
+ public boolean hasOptionalArg() {
return optionalArg;
}
@@ -273,8 +246,7 @@ public class Option implements Cloneable, Serializable
*
* @return boolean flag indicating existence of a long name
*/
- public boolean hasLongOpt()
- {
+ public boolean hasLongOpt() {
return longOpt != null;
}
@@ -283,8 +255,7 @@ public class Option implements Cloneable, Serializable
*
* @return boolean flag indicating if an argument is required
*/
- public boolean hasArg()
- {
+ public boolean hasArg() {
return numberOfArgs > 0 || numberOfArgs == UNLIMITED_VALUES;
}
@@ -293,8 +264,7 @@ public class Option implements Cloneable, Serializable
*
* @return The string description of this option
*/
- public String getDescription()
- {
+ public String getDescription() {
return description;
}
@@ -304,8 +274,7 @@ public class Option implements Cloneable, Serializable
* @param description The description of this option
* @since 1.1
*/
- public void setDescription(final String description)
- {
+ public void setDescription(final String description) {
this.description = description;
}
@@ -314,8 +283,7 @@ public class Option implements Cloneable, Serializable
*
* @return boolean flag indicating whether this Option is mandatory
*/
- public boolean isRequired()
- {
+ public boolean isRequired() {
return required;
}
@@ -324,8 +292,7 @@ public class Option implements Cloneable, Serializable
*
* @param required specifies whether this Option is mandatory
*/
- public void setRequired(final boolean required)
- {
+ public void setRequired(final boolean required) {
this.required = required;
}
@@ -334,8 +301,7 @@ public class Option implements Cloneable, Serializable
*
* @param argName the display name for the argument value.
*/
- public void setArgName(final String argName)
- {
+ public void setArgName(final String argName) {
this.argName = argName;
}
@@ -344,8 +310,7 @@ public class Option implements Cloneable, Serializable
*
* @return the display name for the argument value.
*/
- public String getArgName()
- {
+ public String getArgName() {
return argName;
}
@@ -354,8 +319,7 @@ public class Option implements Cloneable, Serializable
*
* @return if the display name for the argument value has been set.
*/
- public boolean hasArgName()
- {
+ public boolean hasArgName() {
return argName != null && !argName.isEmpty();
}
@@ -364,8 +328,7 @@ public class Option implements Cloneable, Serializable
*
* @return boolean flag indicating if multiple values are allowed
*/
- public boolean hasArgs()
- {
+ public boolean hasArgs() {
return numberOfArgs > 1 || numberOfArgs == UNLIMITED_VALUES;
}
@@ -374,19 +337,16 @@ public class Option implements Cloneable, Serializable
*
* @param num the number of argument values
*/
- public void setArgs(final int num)
- {
+ public void setArgs(final int num) {
this.numberOfArgs = num;
}
/**
- * Sets the value separator. For example if the argument value
- * was a Java property, the value separator would be '='.
+ * 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 void setValueSeparator(final char sep)
- {
+ public void setValueSeparator(final char sep) {
this.valuesep = sep;
}
@@ -395,8 +355,7 @@ public class Option implements Cloneable, Serializable
*
* @return the value separator character.
*/
- public char getValueSeparator()
- {
+ public char getValueSeparator() {
return valuesep;
}
@@ -406,8 +365,7 @@ public class Option implements Cloneable, Serializable
* @return whether this Option has specified a value separator.
* @since 1.1
*/
- public boolean hasValueSeparator()
- {
+ public boolean hasValueSeparator() {
return valuesep > 0;
}
@@ -415,18 +373,16 @@ public class Option implements Cloneable, Serializable
* Returns the number of argument values this Option can take.
*
* <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.
+ * 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 int getArgs()
- {
+ public int getArgs() {
return numberOfArgs;
}
@@ -435,31 +391,25 @@ public class Option implements Cloneable, Serializable
*
* @param value is a/the value of this Option
*/
- void addValueForProcessing(final String value)
- {
- if (numberOfArgs == UNINITIALIZED)
- {
+ void addValueForProcessing(final String value) {
+ if (numberOfArgs == UNINITIALIZED) {
throw new RuntimeException("NO_ARGS_ALLOWED");
}
processValue(value);
}
/**
- * Processes the value. If this Option has a value separator
- * the value will have to be parsed into individual tokens. When
- * n-1 tokens have been processed and there are more value separators
- * in the value, parsing is ceased and the remaining characters are
- * added as a single token.
+ * Processes the value. If this Option has a value separator the value will have to be parsed into individual tokens.
+ * When n-1 tokens have been processed and there are more value separators in the value, parsing is ceased and the
+ * remaining characters are added as a single token.
*
* @param value The String to be processed.
*
* @since 1.0.1
*/
- private void processValue(String value)
- {
+ private void processValue(String value) {
// this Option has a separator character
- if (hasValueSeparator())
- {
+ if (hasValueSeparator()) {
// get the separator character
final char sep = getValueSeparator();
@@ -467,11 +417,9 @@ public class Option implements Cloneable, Serializable
int index = value.indexOf(sep);
// while there are more value separators
- while (index != -1)
- {
+ while (index != -1) {
// next value to be added
- if (values.size() == numberOfArgs - 1)
- {
+ if (values.size() == numberOfArgs - 1) {
break;
}
@@ -491,18 +439,15 @@ 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.
+ * 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
*
* @since 1.0.1
*/
- private void add(final String value)
- {
- if (!acceptsArg())
- {
+ private void add(final String value) {
+ if (!acceptsArg()) {
throw new RuntimeException("Cannot add value, list full.");
}
@@ -511,69 +456,53 @@ public class Option implements Cloneable, Serializable
}
/**
- * Returns the specified value of this Option or
- * <code>null</code> if there is no value.
+ * Returns the specified value of this Option or <code>null</code> if there is no value.
*
- * @return the value/first value of this Option or
- * <code>null</code> if there is no value.
+ * @return the value/first value of this Option or <code>null</code> if there is no value.
*/
- public String getValue()
- {
+ public String getValue() {
return hasNoValues() ? null : values.get(0);
}
/**
- * Returns the specified value of this Option or
- * <code>null</code> if there is no value.
+ * Returns the specified value of this Option or <code>null</code> if there is no value.
*
* @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.
+ * @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.
+ * @throws IndexOutOfBoundsException if index is less than 1 or greater than the number of the values for this Option.
*/
- public String getValue(final int index) throws IndexOutOfBoundsException
- {
+ public String getValue(final int index) throws IndexOutOfBoundsException {
return hasNoValues() ? null : values.get(index);
}
/**
- * Returns the value/first value of this Option or the
- * <code>defaultValue</code> if there is no value.
+ * Returns the value/first value of this Option or the <code>defaultValue</code> if there is no value.
*
- * @param defaultValue The value to be returned if there
- * is no value.
+ * @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.
+ * @return the value/first value of this Option or the <code>defaultValue</code> if there are no values.
*/
- public String getValue(final String defaultValue)
- {
+ public String getValue(final String defaultValue) {
final String value = getValue();
return (value != null) ? value : defaultValue;
}
/**
- * Return the values of this Option as a String array
- * or null if there are no values
+ * Return the values of this Option as a String array or null if there are no values
*
- * @return the values of this Option as a String array
- * or null if there are no values
+ * @return the values of this Option as a String array or null if there are no values
*/
- public String[] getValues()
- {
+ public String[] getValues() {
return hasNoValues() ? null : values.toArray(new String[values.size()]);
}
/**
- * @return the values of this Option as a List
- * or null if there are no values
+ * @return the values of this Option as a List or null if there are no values
*/
- public List<String> getValuesList()
- {
+ public List<String> getValuesList() {
return values;
}
@@ -583,32 +512,26 @@ public class Option implements Cloneable, Serializable
* @return Stringified form of this object
*/
@Override
- public String toString()
- {
+ public String toString() {
final StringBuilder buf = new StringBuilder().append("[ option: ");
buf.append(opt);
- if (longOpt != null)
- {
+ if (longOpt != null) {
buf.append(" ").append(longOpt);
}
buf.append(" ");
- if (hasArgs())
- {
+ if (hasArgs()) {
buf.append("[ARG...]");
- }
- else if (hasArg())
- {
+ } else if (hasArg()) {
buf.append(" [ARG]");
}
buf.append(" :: ").append(description);
- if (type != null)
- {
+ if (type != null) {
buf.append(" :: ").append(type);
}
@@ -622,31 +545,25 @@ public class Option implements Cloneable, Serializable
*
* @return whether this Option has any values.
*/
- private boolean hasNoValues()
- {
+ private boolean hasNoValues() {
return values.isEmpty();
}
@Override
- public boolean equals(final Object o)
- {
- if (this == o)
- {
+ public boolean equals(final Object o) {
+ if (this == o) {
return true;
}
- if (o == null || getClass() != o.getClass())
- {
+ if (o == null || getClass() != o.getClass()) {
return false;
}
final Option option = (Option) o;
- if (opt != null ? !opt.equals(option.opt) : option.opt != null)
- {
+ if (opt != null ? !opt.equals(option.opt) : option.opt != null) {
return false;
}
- if (longOpt != null ? !longOpt.equals(option.longOpt) : option.longOpt != null)
- {
+ if (longOpt != null ? !longOpt.equals(option.longOpt) : option.longOpt != null) {
return false;
}
@@ -654,8 +571,7 @@ public class Option implements Cloneable, Serializable
}
@Override
- public int hashCode()
- {
+ public int hashCode() {
int result;
result = opt != null ? opt.hashCode() : 0;
result = 31 * result + (longOpt != null ? longOpt.hashCode() : 0);
@@ -663,46 +579,38 @@ public class Option implements Cloneable, Serializable
}
/**
- * 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.
+ * 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().
+ * 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()}
+ * @throws RuntimeException if a {@link CloneNotSupportedException} has been thrown by {@code super.clone()}
*/
@Override
- public Object clone()
- {
- try
- {
+ public Object clone() {
+ try {
final Option option = (Option) super.clone();
option.values = new ArrayList<>(values);
return option;
- }
- catch (final CloneNotSupportedException cnse)
- {
+ } 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.
+ * 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()
- {
+ 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.
+ * 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}
@@ -710,10 +618,9 @@ public class Option implements Cloneable, Serializable
* @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. ");
+ 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. ");
}
/**
@@ -722,8 +629,7 @@ public class Option implements Cloneable, Serializable
* @return false if the maximum number of arguments is reached
* @since 1.3
*/
- boolean acceptsArg()
- {
+ boolean acceptsArg() {
return (hasArg() || hasArgs() || hasOptionalArg()) && (numberOfArgs <= 0 || values.size() < numberOfArgs);
}
@@ -733,61 +639,50 @@ public class Option implements Cloneable, Serializable
* @return false if the option doesn't require more arguments
* @since 1.3
*/
- boolean requiresArg()
- {
- if (optionalArg)
- {
+ boolean requiresArg() {
+ if (optionalArg) {
return false;
}
- if (numberOfArgs == UNLIMITED_VALUES)
- {
+ if (numberOfArgs == UNLIMITED_VALUES) {
return values.isEmpty();
}
return acceptsArg();
}
/**
- * Returns a {@link Builder} to create an {@link Option} using descriptive
- * methods.
+ * 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()
- {
+ public static Builder builder() {
return builder(null);
}
/**
- * Returns a {@link Builder} to create an {@link Option} using descriptive
- * methods.
+ * 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)
- {
+ public static Builder builder(final String opt) {
return new Builder(opt);
}
/**
- * A nested builder class to create <code>Option</code> instances
- * using descriptive methods.
+ * 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();
+ * Option option = Option.builder("a").required(true).longOpt("arg-name").build();
* </pre>
*
* @since 1.3
*/
- public static final class Builder
- {
+ public static final class Builder {
/** the name of the option */
private final String opt;
@@ -816,14 +711,12 @@ public class Option implements Cloneable, Serializable
private char valuesep;
/**
- * Constructs a new <code>Builder</code> with the minimum
- * required parameters for an <code>Option</code> instance.
+ * 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
- {
+ private Builder(final String opt) throws IllegalArgumentException {
OptionValidator.validateOption(opt);
this.opt = opt;
}
@@ -834,8 +727,7 @@ public class Option implements Cloneable, Serializable
* @param argName the display name for the argument value.
* @return this builder, to allow method chaining
*/
- public Builder argName(final String argName)
- {
+ public Builder argName(final String argName) {
this.argName = argName;
return this;
}
@@ -846,8 +738,7 @@ public class Option implements Cloneable, Serializable
* @param description the description of the option.
* @return this builder, to allow method chaining
*/
- public Builder desc(final String description)
- {
+ public Builder desc(final String description) {
this.description = description;
return this;
}
@@ -858,8 +749,7 @@ public class Option implements Cloneable, Serializable
* @param longOpt the long name of the Option
* @return this builder, to allow method chaining
*/
- public Builder longOpt(final String longOpt)
- {
+ public Builder longOpt(final String longOpt) {
this.longOpt = longOpt;
return this;
}
@@ -870,8 +760,7 @@ public class Option implements Cloneable, Serializable
* @param numberOfArgs the number of argument values
* @return this builder, to allow method chaining
*/
- public Builder numberOfArgs(final int numberOfArgs)
- {
+ public Builder numberOfArgs(final int numberOfArgs) {
this.numberOfArgs = numberOfArgs;
return this;
}
@@ -879,12 +768,10 @@ public class Option implements Cloneable, Serializable
/**
* Sets whether the Option can have an optional argument.
*
- * @param isOptional specifies 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)
- {
+ public Builder optionalArg(final boolean isOptional) {
this.optionalArg = isOptional;
return this;
}
@@ -894,8 +781,7 @@ public class Option implements Cloneable, Serializable
*
* @return this builder, to allow method chaining
*/
- public Builder required()
- {
+ public Builder required() {
return required(true);
}
@@ -905,8 +791,7 @@ public class Option implements Cloneable, Serializable
* @param required specifies whether the Option is mandatory
* @return this builder, to allow method chaining
*/
- public Builder required(final boolean required)
- {
+ public Builder required(final boolean required) {
this.required = required;
return this;
}
@@ -917,8 +802,7 @@ public class Option implements Cloneable, Serializable
* @param type the type of the Option
* @return this builder, to allow method chaining
*/
- public Builder type(final Class<?> type)
- {
+ public Builder type(final Class<?> type) {
this.type = type;
return this;
}
@@ -928,34 +812,30 @@ public class Option implements Cloneable, Serializable
*
* @return this builder, to allow method chaining
*/
- public Builder valueSeparator()
- {
+ public Builder valueSeparator() {
return valueSeparator('=');
}
/**
- * The Option will use <code>sep</code> as a means to
- * separate argument values.
+ * 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();
+ * 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 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)
- {
+ public Builder valueSeparator(final char sep) {
valuesep = sep;
return this;
}
@@ -965,8 +845,7 @@ public class Option implements Cloneable, Serializable
*
* @return this builder, to allow method chaining
*/
- public Builder hasArg()
- {
+ public Builder hasArg() {
return hasArg(true);
}
@@ -976,8 +855,7 @@ public class Option implements Cloneable, Serializable
* @param hasArg specifies whether the Option takes an argument or not
* @return this builder, to allow method chaining
*/
- public Builder hasArg(final boolean hasArg)
- {
+ 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;
@@ -988,8 +866,7 @@ public class Option implements Cloneable, Serializable
*
* @return this builder, to allow method chaining
*/
- public Builder hasArgs()
- {
+ public Builder hasArgs() {
numberOfArgs = Option.UNLIMITED_VALUES;
return this;
}
@@ -1000,10 +877,8 @@ public class Option implements Cloneable, Serializable
* @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)
- {
+ 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 2ae6703..7bcab4f 100644
--- a/src/main/java/org/apache/commons/cli/OptionBuilder.java
+++ b/src/main/java/org/apache/commons/cli/OptionBuilder.java
@@ -29,8 +29,7 @@ package org.apache.commons.cli;
* @deprecated since 1.3, use {@link Option#builder(String)} instead
*/
@Deprecated
-public final class OptionBuilder
-{
+public final class OptionBuilder {
/** long option */
private static String longopt;
@@ -58,8 +57,7 @@ public final class OptionBuilder
/** option builder instance */
private static final OptionBuilder INSTANCE = new OptionBuilder();
- static
- {
+ static {
// ensure the consistency of the initial values
reset();
}
@@ -67,16 +65,14 @@ public final class OptionBuilder
/**
* private constructor to prevent instances being created
*/
- private OptionBuilder()
- {
+ private OptionBuilder() {
// hide the constructor
}
/**
* Resets the member variables to their default values.
*/
- private static void reset()
- {
+ private static void reset() {
description = null;
argName = null;
longopt = null;
@@ -93,8 +89,7 @@ public final class OptionBuilder
* @param newLongopt the long option value
* @return the OptionBuilder instance
*/
- public static OptionBuilder withLongOpt(final String newLongopt)
- {
+ public static OptionBuilder withLongOpt(final String newLongopt) {
OptionBuilder.longopt = newLongopt;
return INSTANCE;
@@ -105,22 +100,19 @@ public final class OptionBuilder
*
* @return the OptionBuilder instance
*/
- public static OptionBuilder hasArg()
- {
+ public static OptionBuilder hasArg() {
OptionBuilder.numberOfArgs = 1;
return INSTANCE;
}
/**
- * The next Option created will require an argument value if
- * <code>hasArg</code> is true.
+ * The next Option created will require an argument value if <code>hasArg</code> is true.
*
* @param hasArg if true then the Option has an argument value
* @return the OptionBuilder instance
*/
- public static OptionBuilder hasArg(final boolean hasArg)
- {
+ public static OptionBuilder hasArg(final boolean hasArg) {
OptionBuilder.numberOfArgs = hasArg ? 1 : Option.UNINITIALIZED;
return INSTANCE;
@@ -132,8 +124,7 @@ public final class OptionBuilder
* @param name the name for the argument value
* @return the OptionBuilder instance
*/
- public static OptionBuilder withArgName(final String name)
- {
+ public static OptionBuilder withArgName(final String name) {
OptionBuilder.argName = name;
return INSTANCE;
@@ -144,25 +135,23 @@ public final class OptionBuilder
*
* @return the OptionBuilder instance
*/
- public static OptionBuilder isRequired()
- {
+ public static OptionBuilder isRequired() {
OptionBuilder.required = true;
return INSTANCE;
}
/**
- * The next Option created uses <code>sep</code> as a means to
- * separate argument values.
+ * 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');
+ * Option opt = OptionBuilder.withValueSeparator('=').create('D');
*
* String args = "-Dkey=value";
* CommandLine line = parser.parse(args);
- * String propertyName = opt.getValue(0); // will be "key"
+ * String propertyName = opt.getValue(0); // will be "key"
* String propertyValue = opt.getValue(1); // will be "value"
* </pre>
*
@@ -170,21 +159,19 @@ public final class OptionBuilder
*
* @return the OptionBuilder instance
*/
- public static OptionBuilder withValueSeparator(final char sep)
- {
+ public static OptionBuilder withValueSeparator(final char sep) {
OptionBuilder.valuesep = sep;
return INSTANCE;
}
/**
- * The next Option created uses '<code>=</code>' as a means to
- * separate argument values.
+ * The next Option created uses '<code>=</code>' as a means to separate argument values.
*
* <b>Example:</b>
+ *
* <pre>
- * Option opt = OptionBuilder.withValueSeparator()
- * .create('D');
+ * Option opt = OptionBuilder.withValueSeparator().create('D');
*
* CommandLine line = parser.parse(args);
* String propertyName = opt.getValue(0);
@@ -193,22 +180,19 @@ public final class OptionBuilder
*
* @return the OptionBuilder instance
*/
- public static OptionBuilder withValueSeparator()
- {
+ public static OptionBuilder withValueSeparator() {
OptionBuilder.valuesep = '=';
return INSTANCE;
}
/**
- * The next Option created will be required if <code>required</code>
- * is true.
+ * The next Option created will be required if <code>required</code> is true.
*
* @param newRequired if true then the Option is required
* @return the OptionBuilder instance
*/
- public static OptionBuilder isRequired(final boolean newRequired)
- {
+ public static OptionBuilder isRequired(final boolean newRequired) {
OptionBuilder.required = newRequired;
return INSTANCE;
@@ -219,8 +203,7 @@ public final class OptionBuilder
*
* @return the OptionBuilder instance
*/
- public static OptionBuilder hasArgs()
- {
+ public static OptionBuilder hasArgs() {
OptionBuilder.numberOfArgs = Option.UNLIMITED_VALUES;
return INSTANCE;
@@ -232,8 +215,7 @@ public final class OptionBuilder
* @param num the number of args that the option can have
* @return the OptionBuilder instance
*/
- public static OptionBuilder hasArgs(final int num)
- {
+ public static OptionBuilder hasArgs(final int num) {
OptionBuilder.numberOfArgs = num;
return INSTANCE;
@@ -244,8 +226,7 @@ public final class OptionBuilder
*
* @return the OptionBuilder instance
*/
- public static OptionBuilder hasOptionalArg()
- {
+ public static OptionBuilder hasOptionalArg() {
OptionBuilder.numberOfArgs = 1;
OptionBuilder.optionalArg = true;
@@ -257,8 +238,7 @@ public final class OptionBuilder
*
* @return the OptionBuilder instance
*/
- public static OptionBuilder hasOptionalArgs()
- {
+ public static OptionBuilder hasOptionalArgs() {
OptionBuilder.numberOfArgs = Option.UNLIMITED_VALUES;
OptionBuilder.optionalArg = true;
@@ -268,12 +248,10 @@ public final class OptionBuilder
/**
* The next Option can have the specified number of optional arguments.
*
- * @param numArgs - the maximum number of optional arguments
- * the next Option created can have.
+ * @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)
- {
+ public static OptionBuilder hasOptionalArgs(final int numArgs) {
OptionBuilder.numberOfArgs = numArgs;
OptionBuilder.optionalArg = true;
@@ -281,32 +259,28 @@ 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 will have a value that will be an instance of <code>type</code>.
* <p>
- * <b>Note:</b> this method is kept for binary compatibility and the
- * input type is supposed to be a {@link Class} object.
+ * <b>Note:</b> this method is kept for binary compatibility and the input type is supposed to be a {@link Class}
+ * object.
*
* @param newType the type of the Options argument value
* @return the OptionBuilder instance
* @deprecated since 1.3, use {@link #withType(Class)} instead
*/
@Deprecated
- public static OptionBuilder withType(final Object newType)
- {
+ public static OptionBuilder withType(final Object newType) {
return withType((Class<?>) newType);
}
/**
- * The next Option created will have a value that will be an instance
- * of <code>type</code>.
+ * The next Option created will have a value that will be an instance of <code>type</code>.
*
* @param newType the type of the Options argument value
* @return the OptionBuilder instance
* @since 1.3
*/
- public static OptionBuilder withType(final Class<?> newType)
- {
+ public static OptionBuilder withType(final Class<?> newType) {
OptionBuilder.type = newType;
return INSTANCE;
@@ -318,24 +292,20 @@ public final class OptionBuilder
* @param newDescription a description of the Option's purpose
* @return the OptionBuilder instance
*/
- public static OptionBuilder withDescription(final String newDescription)
- {
+ public static OptionBuilder withDescription(final String newDescription) {
OptionBuilder.description = newDescription;
return INSTANCE;
}
/**
- * Create an Option using the current settings and with
- * the specified Option <code>char</code>.
+ * 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.
+ * @throws IllegalArgumentException if <code>opt</code> is not a valid character. See Option.
*/
- public static Option create(final char opt) throws IllegalArgumentException
- {
+ public static Option create(final char opt) throws IllegalArgumentException {
return create(String.valueOf(opt));
}
@@ -345,10 +315,8 @@ public final class OptionBuilder
* @return the Option instance
* @throws IllegalArgumentException if <code>longOpt</code> has not been set.
*/
- public static Option create() throws IllegalArgumentException
- {
- if (longopt == null)
- {
+ public static Option create() throws IllegalArgumentException {
+ if (longopt == null) {
OptionBuilder.reset();
throw new IllegalArgumentException("must specify longopt");
}
@@ -357,20 +325,15 @@ public final class OptionBuilder
}
/**
- * Create an Option using the current settings and with
- * the specified Option <code>char</code>.
+ * 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
+ * @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.
+ * @throws IllegalArgumentException if <code>opt</code> is not a valid character. See Option.
*/
- public static Option create(final String opt) throws IllegalArgumentException
- {
+ public static Option create(final String opt) throws IllegalArgumentException {
Option option = null;
- try
- {
+ try {
// create the option
option = new Option(opt, description);
@@ -382,9 +345,7 @@ public final class OptionBuilder
option.setType(type);
option.setValueSeparator(valuesep);
option.setArgName(argName);
- }
- finally
- {
+ } finally {
// reset the OptionBuilder properties
OptionBuilder.reset();
}
diff --git a/src/main/java/org/apache/commons/cli/OptionGroup.java b/src/main/java/org/apache/commons/cli/OptionGroup.java
index ce390ee..5bf5c8f 100644
--- a/src/main/java/org/apache/commons/cli/OptionGroup.java
+++ b/src/main/java/org/apache/commons/cli/OptionGroup.java
@@ -26,8 +26,7 @@ import java.util.Map;
/**
* A group of mutually exclusive options.
*/
-public class OptionGroup implements Serializable
-{
+public class OptionGroup implements Serializable {
/** The serial version UID. */
private static final long serialVersionUID = 1L;
@@ -46,9 +45,8 @@ public class OptionGroup implements Serializable
* @param option the option to add to this group
* @return this option group with the option added
*/
- public OptionGroup addOption(final Option option)
- {
- // key - option name
+ public OptionGroup addOption(final Option option) {
+ // key - option name
// value - the option
optionMap.put(option.getKey(), option);
@@ -56,11 +54,9 @@ public class OptionGroup implements Serializable
}
/**
- * @return the names of the options in this group as a
- * <code>Collection</code>
+ * @return the names of the options in this group as a <code>Collection</code>
*/
- public Collection<String> getNames()
- {
+ public Collection<String> getNames() {
// the key set is the collection of names
return optionMap.keySet();
}
@@ -68,8 +64,7 @@ public class OptionGroup implements Serializable
/**
* @return the options in this group as a <code>Collection</code>
*/
- public Collection<Option> getOptions()
- {
+ public Collection<Option> getOptions() {
// the values are the collection of options
return optionMap.values();
}
@@ -78,13 +73,10 @@ public class OptionGroup implements Serializable
* Set the selected option of this group to <code>name</code>.
*
* @param option the option that is selected
- * @throws AlreadySelectedException if an option from this group has
- * already been selected.
+ * @throws AlreadySelectedException if an option from this group has already been selected.
*/
- public void setSelected(final Option option) throws AlreadySelectedException
- {
- if (option == null)
- {
+ public void setSelected(final Option option) throws AlreadySelectedException {
+ if (option == null) {
// reset the option previously selected
selected = null;
return;
@@ -93,7 +85,7 @@ public class OptionGroup implements Serializable
// if no option has already been selected or the
// same option is being reselected then set the
// selected member variable
- if ((selected != null) && !selected.equals(option.getKey())) {
+ if (selected != null && !selected.equals(option.getKey())) {
throw new AlreadySelectedException(this, option);
}
selected = option.getKey();
@@ -102,16 +94,14 @@ public class OptionGroup implements Serializable
/**
* @return the selected option name
*/
- public String getSelected()
- {
+ public String getSelected() {
return selected;
}
/**
* @param required specifies if this group is required
*/
- public void setRequired(final boolean required)
- {
+ public void setRequired(final boolean required) {
this.required = required;
}
@@ -120,8 +110,7 @@ public class OptionGroup implements Serializable
*
* @return whether this option group is required
*/
- public boolean isRequired()
- {
+ public boolean isRequired() {
return required;
}
@@ -131,37 +120,30 @@ public class OptionGroup implements Serializable
* @return the stringified representation of this group
*/
@Override
- public String toString()
- {
+ public String toString() {
final StringBuilder buff = new StringBuilder();
final Iterator<Option> iter = getOptions().iterator();
buff.append("[");
- while (iter.hasNext())
- {
+ while (iter.hasNext()) {
final Option option = iter.next();
- if (option.getOpt() != null)
- {
+ if (option.getOpt() != null) {
buff.append("-");
buff.append(option.getOpt());
- }
- else
- {
+ } else {
buff.append("--");
buff.append(option.getLongOpt());
}
- if (option.getDescription() != null)
- {
+ if (option.getDescription() != null) {
buff.append(" ");
buff.append(option.getDescription());
}
- if (iter.hasNext())
- {
+ if (iter.hasNext()) {
buff.append(", ");
}
}
diff --git a/src/main/java/org/apache/commons/cli/OptionValidator.java b/src/main/java/org/apache/commons/cli/OptionValidator.java
index 5c29bdc..3525378 100644
--- a/src/main/java/org/apache/commons/cli/OptionValidator.java
+++ b/src/main/java/org/apache/commons/cli/OptionValidator.java
@@ -22,18 +22,14 @@ package org.apache.commons.cli;
*
* @since 1.1
*/
-final class OptionValidator
-{
+final class OptionValidator {
/**
- * Validates whether <code>opt</code> is a permissible Option
- * shortOpt. The rules that specify if the <code>opt</code>
+ * Validates whether <code>opt</code> is a permissible Option shortOpt. The rules that specify if the <code>opt</code>
* is valid are:
*
* <ul>
- * <li>a single character <code>opt</code> that is either
- * ' '(special case), '?', '@' or a letter</li>
- * <li>a multi character <code>opt</code> that only contains
- * letters.</li>
+ * <li>a single character <code>opt</code> that is either ' '(special case), '?', '@' or a letter</li>
+ * <li>a multi character <code>opt</code> that only contains letters.</li>
* </ul>
* <p>
* In case {@code opt} is {@code null} no further validation is performed.
@@ -41,34 +37,26 @@ final class OptionValidator
* @param opt The option string to validate, may be null
* @throws IllegalArgumentException if the Option is not valid.
*/
- static void validateOption(final String opt) throws IllegalArgumentException
- {
+ static void validateOption(final String opt) throws IllegalArgumentException {
// if opt is NULL do not check further
- if (opt == null)
- {
+ if (opt == null) {
return;
}
// handle the single character opt
- if (opt.length() == 1)
- {
+ if (opt.length() == 1) {
final char ch = opt.charAt(0);
- if (!isValidOpt(ch))
- {
+ if (!isValidOpt(ch)) {
throw new IllegalArgumentException("Illegal option name '" + ch + "'");
}
}
// handle the multi character opt
- else
- {
- for (final char ch : opt.toCharArray())
- {
- if (!isValidChar(ch))
- {
- throw new IllegalArgumentException("The option '" + opt + "' contains an illegal "
- + "character : '" + ch + "'");
+ else {
+ for (final char ch : opt.toCharArray()) {
+ if (!isValidChar(ch)) {
+ throw new IllegalArgumentException("The option '" + opt + "' contains an illegal " + "character : '" + ch + "'");
}
}
}
@@ -80,8 +68,7 @@ final class OptionValidator
* @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)
- {
+ private static boolean isValidOpt(final char c) {
return isValidChar(c) || c == '?' || c == '@';
}
@@ -91,8 +78,7 @@ final class OptionValidator
* @param c the character to validate
* @return true if <code>c</code> is a letter.
*/
- private static boolean isValidChar(final char c)
- {
+ 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 65f5343..5b86571 100644
--- a/src/main/java/org/apache/commons/cli/Options.java
+++ b/src/main/java/org/apache/commons/cli/Options.java
@@ -29,17 +29,14 @@ import java.util.Map;
/**
* Main entry-point into the library.
* <p>
- * Options represents a collection of {@link Option} objects, which
- * describe the possible options for a command-line.
+ * Options represents a collection of {@link Option} objects, which describe the possible options for a command-line.
* <p>
- * It may flexibly parse long and short options, with or without
- * values. Additionally, it may parse only a portion of a commandline,
- * allowing for flexible multi-stage parsing.
+ * It may flexibly parse long and short options, with or without values. Additionally, it may parse only a portion of a
+ * commandline, allowing for flexible multi-stage parsing.
*
* @see org.apache.commons.cli.CommandLine
*/
-public class Options implements Serializable
-{
+public class Options implements Serializable {
/** The serial version UID. */
private static final long serialVersionUID = 1L;
@@ -63,15 +60,12 @@ public class Options implements Serializable
* @param group the OptionGroup that is to be added
* @return the resulting Options instance
*/
- public Options addOptionGroup(final OptionGroup group)
- {
- if (group.isRequired())
- {
+ public Options addOptionGroup(final OptionGroup group) {
+ if (group.isRequired()) {
requiredOpts.add(group);
}
- for (final Option option : group.getOptions())
- {
+ 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
@@ -89,8 +83,7 @@ public class Options implements Serializable
*
* @return a Collection of OptionGroup instances.
*/
- Collection<OptionGroup> getOptionGroups()
- {
+ Collection<OptionGroup> getOptionGroups() {
return new HashSet<>(optionGroups.values());
}
@@ -106,8 +99,7 @@ public class Options implements Serializable
* @return the resulting Options instance
* @since 1.3
*/
- public Options addOption(final String opt, final String description)
- {
+ public Options addOption(final String opt, final String description) {
addOption(opt, null, false, description);
return this;
}
@@ -124,8 +116,7 @@ public class Options implements Serializable
* @param description Self-documenting description
* @return the resulting Options instance
*/
- public Options addOption(final String opt, final boolean hasArg, final String description)
- {
+ public Options addOption(final String opt, final boolean hasArg, final String description) {
addOption(opt, null, hasArg, description);
return this;
}
@@ -143,8 +134,7 @@ public class Options implements Serializable
* @param description Self-documenting description
* @return the resulting Options instance
*/
- public Options addOption(final String opt, final String longOpt, final boolean hasArg, final String 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;
}
@@ -171,8 +161,7 @@ public class Options implements Serializable
* @return the resulting Options instance
* @since 1.4
*/
- public Options addRequiredOption(final String opt, final String longOpt, final boolean hasArg, final String description)
- {
+ public Options addRequiredOption(final String opt, final String longOpt, final boolean hasArg, final String description) {
final Option option = new Option(opt, longOpt, hasArg, description);
option.setRequired(true);
addOption(option);
@@ -185,21 +174,17 @@ public class Options implements Serializable
* @param opt the option that is to be added
* @return the resulting Options instance
*/
- public Options addOption(final Option opt)
- {
+ public Options addOption(final Option opt) {
final String key = opt.getKey();
// add it to the long option list
- if (opt.hasLongOpt())
- {
+ if (opt.hasLongOpt()) {
longOpts.put(opt.getLongOpt(), opt);
}
// if the option is required add it to the required list
- if (opt.isRequired())
- {
- if (requiredOpts.contains(key))
- {
+ if (opt.isRequired()) {
+ if (requiredOpts.contains(key)) {
requiredOpts.remove(requiredOpts.indexOf(key));
}
requiredOpts.add(key);
@@ -215,8 +200,7 @@ public class Options implements Serializable
*
* @return read-only Collection of {@link Option} objects in this descriptor
*/
- public Collection<Option> getOptions()
- {
+ public Collection<Option> getOptions() {
return Collections.unmodifiableCollection(helpOptions());
}
@@ -225,8 +209,7 @@ public class Options implements Serializable
*
* @return the List of Options
*/
- List<Option> helpOptions()
- {
+ List<Option> helpOptions() {
return new ArrayList<>(shortOpts.values());
}
@@ -235,8 +218,7 @@ public class Options implements Serializable
*
* @return read-only List of required options
*/
- public List getRequiredOptions()
- {
+ public List getRequiredOptions() {
return Collections.unmodifiableList(requiredOpts);
}
@@ -250,12 +232,10 @@ public class Options implements Serializable
* @param opt short or long name of the {@link Option}
* @return the option represented by opt
*/
- public Option getOption(String opt)
- {
+ public Option getOption(String opt) {
opt = Util.stripLeadingHyphens(opt);
- if (shortOpts.containsKey(opt))
- {
+ if (shortOpts.containsKey(opt)) {
return shortOpts.get(opt);
}
@@ -269,22 +249,18 @@ public class Options implements Serializable
* @return the options matching the partial name specified, or an empty list if none matches
* @since 1.3
*/
- public List<String> getMatchingOptions(String opt)
- {
+ public List<String> getMatchingOptions(String opt) {
opt = Util.stripLeadingHyphens(opt);
final List<String> matchingOpts = new ArrayList<>();
// for a perfect match return the single option only
- if (longOpts.containsKey(opt))
- {
+ if (longOpts.containsKey(opt)) {
return Collections.singletonList(opt);
}
- for (final String longOpt : longOpts.keySet())
- {
- if (longOpt.startsWith(opt))
- {
+ for (final String longOpt : longOpts.keySet()) {
+ if (longOpt.startsWith(opt)) {
matchingOpts.add(longOpt);
}
}
@@ -298,8 +274,7 @@ public class Options implements Serializable
* @param opt short or long name of the {@link Option}
* @return true if the named {@link Option} is a member of this {@link Options}
*/
- public boolean hasOption(String opt)
- {
+ public boolean hasOption(String opt) {
opt = Util.stripLeadingHyphens(opt);
return shortOpts.containsKey(opt) || longOpts.containsKey(opt);
@@ -312,8 +287,7 @@ public class Options implements Serializable
* @return true if the named {@link Option} is a member of this {@link Options}
* @since 1.3
*/
- public boolean hasLongOption(String opt)
- {
+ public boolean hasLongOption(String opt) {
opt = Util.stripLeadingHyphens(opt);
return longOpts.containsKey(opt);
@@ -326,8 +300,7 @@ public class Options implements Serializable
* @return true if the named {@link Option} is a member of this {@link Options}
* @since 1.3
*/
- public boolean hasShortOption(String opt)
- {
+ public boolean hasShortOption(String opt) {
opt = Util.stripLeadingHyphens(opt);
return shortOpts.containsKey(opt);
@@ -339,8 +312,7 @@ public class Options implements Serializable
* @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 OptionGroup getOptionGroup(final Option opt)
- {
+ public OptionGroup getOptionGroup(final Option opt) {
return optionGroups.get(opt.getKey());
}
@@ -350,8 +322,7 @@ public class Options implements Serializable
* @return Stringified form of this object
*/
@Override
- public String toString()
- {
+ public String toString() {
final StringBuilder buf = new StringBuilder();
buf.append("[ Options: [ short ");
diff --git a/src/main/java/org/apache/commons/cli/ParseException.java b/src/main/java/org/apache/commons/cli/ParseException.java
index 498801f..93843e6 100644
--- a/src/main/java/org/apache/commons/cli/ParseException.java
+++ b/src/main/java/org/apache/commons/cli/ParseException.java
@@ -20,21 +20,18 @@ package org.apache.commons.cli;
/**
* Base for Exceptions thrown during parsing of a command-line.
*/
-public class ParseException extends Exception
-{
+public class ParseException extends Exception {
/**
* This exception {@code serialVersionUID}.
*/
private static final long serialVersionUID = 9112808380089253192L;
/**
- * Construct a new <code>ParseException</code>
- * with the specified detail message.
+ * Construct a new <code>ParseException</code> with the specified detail message.
*
* @param message the detail message
*/
- public ParseException(final String message)
- {
+ public ParseException(final String message) {
super(message);
}
}
diff --git a/src/main/java/org/apache/commons/cli/Parser.java b/src/main/java/org/apache/commons/cli/Parser.java
index 33fa5c2..cf16848 100644
--- a/src/main/java/org/apache/commons/cli/Parser.java
+++ b/src/main/java/org/apache/commons/cli/Parser.java
@@ -30,8 +30,7 @@ import java.util.Properties;
* @deprecated since 1.3, the two-pass parsing with the flatten method is not enough flexible to handle complex cases
*/
@Deprecated
-public abstract class Parser implements CommandLineParser
-{
+public abstract class Parser implements CommandLineParser {
/** commandline instance */
protected CommandLine cmd;
@@ -41,120 +40,98 @@ public abstract class Parser implements CommandLineParser
/** list of required options strings */
private List requiredOptions;
- protected void setOptions(final Options options)
- {
+ protected void setOptions(final Options options) {
this.options = options;
this.requiredOptions = new ArrayList(options.getRequiredOptions());
}
- protected Options getOptions()
- {
+ protected Options getOptions() {
return options;
}
- protected List getRequiredOptions()
- {
+ protected List getRequiredOptions() {
return requiredOptions;
}
/**
- * Subclasses must implement this method to reduce
- * the <code>arguments</code> that have been passed to the parse method.
+ * Subclasses must implement this method to reduce the <code>arguments</code> that have been passed to the parse method.
*
* @param opts The Options to parse the arguments by.
* @param arguments The arguments that have to be flattened.
- * @param stopAtNonOption specifies whether to stop
- * flattening when a non option has been encountered
+ * @param stopAtNonOption specifies whether to stop flattening when a non option has been encountered
* @return a String array of the flattened arguments
- * @throws ParseException if there are any problems encountered
- * while parsing the command line tokens.
+ * @throws ParseException if there are any problems encountered while parsing the command line tokens.
*/
- protected abstract String[] flatten(Options opts, String[] arguments, boolean stopAtNonOption)
- throws ParseException;
+ protected abstract String[] flatten(Options opts, String[] arguments, boolean stopAtNonOption) throws ParseException;
/**
- * Parses the specified <code>arguments</code> based
- * on the specified {@link Options}.
+ * Parses the specified <code>arguments</code> based on the specified {@link Options}.
*
* @param options the <code>Options</code>
* @param arguments the <code>arguments</code>
* @return the <code>CommandLine</code>
- * @throws ParseException if there are any problems encountered
- * while parsing the command line tokens.
+ * @throws ParseException if there are any problems encountered while parsing the command line tokens.
*/
@Override
- public CommandLine parse(final Options options, final String[] arguments) throws ParseException
- {
+ public CommandLine parse(final Options options, final String[] arguments) throws ParseException {
return parse(options, arguments, null, false);
}
/**
* Parse the arguments according to the specified options and properties.
*
- * @param options the specified Options
- * @param arguments the command line arguments
+ * @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.
+ * @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
- {
+ 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}.
+ * Parses the specified <code>arguments</code> based on the specified {@link Options}.
*
- * @param options the <code>Options</code>
- * @param arguments the <code>arguments</code>
- * @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.
+ * @param options the <code>Options</code>
+ * @param arguments the <code>arguments</code>
+ * @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 <code>CommandLine</code>
* @throws ParseException if an error occurs when parsing the arguments.
*/
@Override
- public CommandLine parse(final Options options, final String[] arguments, final boolean stopAtNonOption) throws ParseException
- {
+ 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.
+ * 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.
+ * @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.
+ * @throws ParseException if there are any problems encountered while parsing the command line tokens.
*
* @since 1.1
*/
- public CommandLine parse(final Options options, String[] arguments, final Properties properties, final boolean stopAtNonOption)
- throws ParseException
- {
+ public CommandLine parse(final Options options, String[] arguments, final Properties properties, final boolean stopAtNonOption) throws ParseException {
// clear out the data in options in case it's been used before (CLI-71)
- for (final Option opt : options.helpOptions())
- {
+ for (final Option opt : options.helpOptions()) {
opt.clearValues();
}
// clear the data from the groups
- for (final OptionGroup group : options.getOptionGroups())
- {
+ for (final OptionGroup group : options.getOptionGroups()) {
group.setSelected(null);
}
@@ -165,8 +142,7 @@ public abstract class Parser implements CommandLineParser
boolean eatTheRest = false;
- if (arguments == null)
- {
+ if (arguments == null) {
arguments = new String[0];
}
@@ -175,64 +151,49 @@ public abstract class Parser implements CommandLineParser
final ListIterator<String> iterator = tokenList.listIterator();
// process each flattened token
- while (iterator.hasNext())
- {
+ while (iterator.hasNext()) {
final String t = iterator.next();
// the value is the double-dash
- if ("--".equals(t))
- {
+ if ("--".equals(t)) {
eatTheRest = true;
}
// the value is a single dash
- else if ("-".equals(t))
- {
- if (stopAtNonOption)
- {
+ else if ("-".equals(t)) {
+ if (stopAtNonOption) {
eatTheRest = true;
- }
- else
- {
+ } else {
cmd.addArg(t);
}
}
// the value is an option
- else if (t.startsWith("-"))
- {
- if (stopAtNonOption && !getOptions().hasOption(t))
- {
+ else if (t.startsWith("-")) {
+ if (stopAtNonOption && !getOptions().hasOption(t)) {
eatTheRest = true;
cmd.addArg(t);
- }
- else
- {
+ } else {
processOption(t, iterator);
}
}
// the value is an argument
- else
- {
+ else {
cmd.addArg(t);
- if (stopAtNonOption)
- {
+ if (stopAtNonOption) {
eatTheRest = true;
}
}
// eat the remaining tokens
- if (eatTheRest)
- {
- while (iterator.hasNext())
- {
+ if (eatTheRest) {
+ while (iterator.hasNext()) {
final String str = iterator.next();
// ensure only one double-dash is added
- if (!"--".equals(str))
- {
+ if (!"--".equals(str)) {
cmd.addArg(str);
}
}
@@ -249,23 +210,18 @@ 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.
+ * @throws ParseException if there are any problems encountered while processing the properties.
*/
- protected void processProperties(final Properties properties) throws ParseException
- {
- if (properties == null)
- {
+ protected void processProperties(final Properties properties) throws ParseException {
+ if (properties == null) {
return;
}
- for (final Enumeration<?> e = properties.propertyNames(); e.hasMoreElements();)
- {
+ for (final Enumeration<?> e = properties.propertyNames(); e.hasMoreElements();) {
final String option = e.nextElement().toString();
final Option opt = options.getOption(option);
- if (opt == null)
- {
+ if (opt == null) {
throw new UnrecognizedOptionException("Default option wasn't defined", option);
}
@@ -273,29 +229,20 @@ public abstract class Parser implements CommandLineParser
final OptionGroup group = options.getOptionGroup(opt);
final boolean selected = group != null && group.getSelected() != null;
- if (!cmd.hasOption(option) && !selected)
- {
+ 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
- {
+ if (opt.hasArg()) {
+ if (opt.getValues() == null || opt.getValues().length == 0) {
+ try {
opt.addValueForProcessing(value);
- }
- catch (final RuntimeException exp) //NOPMD
+ } 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)))
- {
+ } 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;
@@ -308,79 +255,65 @@ public abstract class Parser implements CommandLineParser
}
/**
- * Throws a {@link MissingOptionException} if all of the required options
- * are not present.
+ * 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
- {
+ protected void checkRequiredOptions() throws MissingOptionException {
// if there are required options that have not been processed
- if (!getRequiredOptions().isEmpty())
- {
+ 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>.
+ * Process the argument values for the specified Option <code>opt</code> using the values retrieved from the specified
+ * iterator <code>iter</code>.
*
* @param opt The current Option
* @param iter The iterator over the flattened command line Options.
*
- * @throws ParseException if an argument value is required
- * and it is has not been found.
+ * @throws ParseException if an argument value is required and it is has not been found.
*/
- public void processArgs(final Option opt, final ListIterator<String> iter) throws ParseException
- {
+ public void processArgs(final Option opt, final ListIterator<String> iter) throws ParseException {
// loop until an option is found
- while (iter.hasNext())
- {
+ while (iter.hasNext()) {
final String str = iter.next();
// found an Option, not an argument
- if (getOptions().hasOption(str) && str.startsWith("-"))
- {
+ if (getOptions().hasOption(str) && str.startsWith("-")) {
iter.previous();
break;
}
// found a value
- try
- {
+ try {
opt.addValueForProcessing(Util.stripLeadingAndTrailingQuotes(str));
- }
- catch (final RuntimeException exp)
- {
+ } catch (final RuntimeException exp) {
iter.previous();
break;
}
}
- if (opt.getValues() == null && !opt.hasOptionalArg())
- {
+ if (opt.getValues() == null && !opt.hasOptionalArg()) {
throw new MissingArgumentException(opt);
}
}
/**
- * Process the Option specified by <code>arg</code> using the values
- * retrieved from the specified iterator <code>iter</code>.
+ * Process the Option specified by <code>arg</code> using the values retrieved from the specified iterator
+ * <code>iter</code>.
*
* @param arg The String value representing an Option
* @param iter The iterator over the flattened command line arguments.
*
* @throws ParseException if <code>arg</code> does not represent an Option
*/
- protected void processOption(final String arg, final ListIterator<String> iter) throws ParseException
- {
+ protected void processOption(final String arg, final ListIterator<String> iter) throws ParseException {
final boolean hasOption = getOptions().hasOption(arg);
// if there is no option throw an UnrecognizedOptionException
- if (!hasOption)
- {
+ if (!hasOption) {
throw new UnrecognizedOptionException("Unrecognized option: " + arg, arg);
}
@@ -391,8 +324,7 @@ public abstract class Parser implements CommandLineParser
updateRequiredOptions(opt);
// if the option takes an argument value
- if (opt.hasArg())
- {
+ if (opt.hasArg()) {
processArgs(opt, iter);
}
@@ -405,23 +337,19 @@ public abstract class Parser implements CommandLineParser
*
* @param opt
*/
- private void updateRequiredOptions(final Option opt) throws ParseException
- {
+ private void updateRequiredOptions(final Option opt) throws ParseException {
// if the option is a required option remove the option from
// the requiredOptions list
- if (opt.isRequired())
- {
+ if (opt.isRequired()) {
getRequiredOptions().remove(opt.getKey());
}
// if the option is in an OptionGroup make that option the selected
// option of the group
- if (getOptions().getOptionGroup(opt) != null)
- {
+ if (getOptions().getOptionGroup(opt) != null) {
final OptionGroup group = getOptions().getOptionGroup(opt);
- if (group.isRequired())
- {
+ if (group.isRequired()) {
getRequiredOptions().remove(group);
}
diff --git a/src/main/java/org/apache/commons/cli/PatternOptionBuilder.java b/src/main/java/org/apache/commons/cli/PatternOptionBuilder.java
index 37421ba..81b637f 100644
--- a/src/main/java/org/apache/commons/cli/PatternOptionBuilder.java
+++ b/src/main/java/org/apache/commons/cli/PatternOptionBuilder.java
@@ -23,37 +23,55 @@ import java.net.URL;
import java.util.Date;
/**
- * <p>Allows Options to be created from a single String.
- * The pattern contains various single character flags and via
- * an optional punctuation character, their expected type.
- * </p>
+ * Allows Options to be created from a single String. The pattern contains various single character flags and via an
+ * optional punctuation character, their expected type.
*
* <table border="1">
- * <caption>Overview of PatternOptionBuilder patterns</caption>
- * <tr><td>a</td><td>-a flag</td></tr>
- * <tr><td>b@</td><td>-b [classname]</td></tr>
- * <tr><td>c></td><td>-c [filename]</td></tr>
- * <tr><td>d+</td><td>-d [classname] (creates object via empty constructor)</td></tr>
- * <tr><td>e%</td><td>-e [number] (creates Double/Long instance depending on existing of a '.')</td></tr>
- * <tr><td>f/</td><td>-f [url]</td></tr>
- * <tr><td>g:</td><td>-g [string]</td></tr>
+ * <caption>Overview of PatternOptionBuilder patterns</caption>
+ * <tr>
+ * <td>a</td>
+ * <td>-a flag</td>
+ * </tr>
+ * <tr>
+ * <td>b@</td>
+ * <td>-b [classname]</td>
+ * </tr>
+ * <tr>
+ * <td>c></td>
+ * <td>-c [filename]</td>
+ * </tr>
+ * <tr>
+ * <td>d+</td>
+ * <td>-d [classname] (creates object via empty constructor)</td>
+ * </tr>
+ * <tr>
+ * <td>e%</td>
+ * <td>-e [number] (creates Double/Long instance depending on existing of a '.')</td>
+ * </tr>
+ * <tr>
+ * <td>f/</td>
+ * <td>-f [url]</td>
+ * </tr>
+ * <tr>
+ * <td>g:</td>
+ * <td>-g [string]</td>
+ * </tr>
* </table>
*
* <p>
- * For example, the following allows command line flags of '-v -p string-value -f /dir/file'.
- * The exclamation mark precede a mandatory option.
+ * For example, the following allows command line flags of '-v -p string-value -f /dir/file'. The exclamation mark
+ * precede a mandatory option.
* </p>
*
* <pre>
- * Options options = PatternOptionBuilder.parsePattern("vp:!f/");
+ * Options options = PatternOptionBuilder.parsePattern("vp:!f/");
* </pre>
*
* <p>
- * TODO: These need to break out to OptionType and also to be pluggable.
+ * TODO These need to break out to OptionType and also to be pluggable.
* </p>
*/
-public class PatternOptionBuilder
-{
+public class PatternOptionBuilder {
/** String class */
public static final Class<String> STRING_VALUE = String.class;
@@ -91,52 +109,39 @@ public class PatternOptionBuilder
* @param ch the specified character
* @return The class that <code>ch</code> represents
*/
- public static Object getValueClass(final char ch)
- {
- switch (ch)
- {
- case '@':
- return PatternOptionBuilder.OBJECT_VALUE;
- case ':':
- return PatternOptionBuilder.STRING_VALUE;
- case '%':
- return PatternOptionBuilder.NUMBER_VALUE;
- case '+':
- return PatternOptionBuilder.CLASS_VALUE;
- case '#':
- return PatternOptionBuilder.DATE_VALUE;
- case '<':
- return PatternOptionBuilder.EXISTING_FILE_VALUE;
- case '>':
- return PatternOptionBuilder.FILE_VALUE;
- case '*':
- return PatternOptionBuilder.FILES_VALUE;
- case '/':
- return PatternOptionBuilder.URL_VALUE;
+ public static Object getValueClass(final char ch) {
+ switch (ch) {
+ case '@':
+ return PatternOptionBuilder.OBJECT_VALUE;
+ case ':':
+ return PatternOptionBuilder.STRING_VALUE;
+ case '%':
+ return PatternOptionBuilder.NUMBER_VALUE;
+ case '+':
+ return PatternOptionBuilder.CLASS_VALUE;
+ case '#':
+ return PatternOptionBuilder.DATE_VALUE;
+ case '<':
+ return PatternOptionBuilder.EXISTING_FILE_VALUE;
+ case '>':
+ return PatternOptionBuilder.FILE_VALUE;
+ case '*':
+ return PatternOptionBuilder.FILES_VALUE;
+ case '/':
+ return PatternOptionBuilder.URL_VALUE;
}
return null;
}
/**
- * Returns whether <code>ch</code> is a value code, i.e.
- * whether it represents a class in a pattern.
+ * Returns whether <code>ch</code> is a value code, i.e. whether it represents a class in a pattern.
*
* @param ch the specified character
* @return true if <code>ch</code> is a value code, otherwise false.
*/
- public static boolean isValueCode(final char ch)
- {
- return ch == '@'
- || ch == ':'
- || ch == '%'
- || ch == '+'
- || ch == '#'
- || ch == '<'
- || ch == '>'
- || ch == '*'
- || ch == '/'
- || ch == '!';
+ public static boolean isValueCode(final char ch) {
+ return ch == '@' || ch == ':' || ch == '%' || ch == '+' || ch == '#' || ch == '<' || ch == '>' || ch == '*' || ch == '/' || ch == '!';
}
/**
@@ -145,29 +150,21 @@ public class PatternOptionBuilder
* @param pattern the pattern string
* @return The {@link Options} instance
*/
- public static Options parsePattern(final String pattern)
- {
+ public static Options parsePattern(final String pattern) {
char opt = ' ';
boolean required = false;
Class<?> type = null;
final Options options = new Options();
- for (int i = 0; i < pattern.length(); i++)
- {
+ for (int i = 0; i < pattern.length(); i++) {
final char ch = pattern.charAt(i);
// a value code comes after an option and specifies
// details about it
- if (!isValueCode(ch))
- {
- if (opt != ' ')
- {
- final Option option = Option.builder(String.valueOf(opt))
- .hasArg(type != null)
- .required(required)
- .type(type)
- .build();
+ if (!isValueCode(ch)) {
+ if (opt != ' ') {
+ final Option option = Option.builder(String.valueOf(opt)).hasArg(type != null).required(required).type(type).build();
// we have a previous one to deal with
options.addOption(option);
@@ -177,24 +174,15 @@ public class PatternOptionBuilder
}
opt = ch;
- }
- else if (ch == '!')
- {
+ } else if (ch == '!') {
required = true;
- }
- else
- {
+ } else {
type = (Class<?>) getValueClass(ch);
}
}
- if (opt != ' ')
- {
- final Option option = Option.builder(String.valueOf(opt))
- .hasArg(type != null)
- .required(required)
- .type(type)
- .build();
+ if (opt != ' ') {
+ final Option option = Option.builder(String.valueOf(opt)).hasArg(type != null).required(required).type(type).build();
// we have a final one to deal with
options.addOption(option);
diff --git a/src/main/java/org/apache/commons/cli/PosixParser.java b/src/main/java/org/apache/commons/cli/PosixParser.java
index 98b93bf..a1bcb43 100644
--- a/src/main/java/org/apache/commons/cli/PosixParser.java
+++ b/src/main/java/org/apache/commons/cli/PosixParser.java
@@ -23,14 +23,13 @@ import java.util.Iterator;
import java.util.List;
/**
- * The class PosixParser provides an implementation of the
- * {@link Parser#flatten(Options,String[],boolean) flatten} method.
+ * The class PosixParser provides an implementation of the {@link Parser#flatten(Options,String[],boolean) flatten}
+ * method.
*
* @deprecated since 1.3, use the {@link DefaultParser} instead
*/
@Deprecated
-public class PosixParser extends Parser
-{
+public class PosixParser extends Parser {
/** holder for flattened tokens */
private final List<String> tokens = new ArrayList<>();
@@ -44,56 +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.
+ * 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()
- {
+ private void init() {
eatTheRest = false;
tokens.clear();
}
/**
- * <p>An implementation of {@link Parser}'s abstract
- * {@link Parser#flatten(Options,String[],boolean) flatten} method.</p>
+ * <p>
+ * An implementation of {@link Parser}'s abstract {@link Parser#flatten(Options,String[],boolean) flatten} method.
+ * </p>
*
- * <p>The following are the rules used by this flatten method.</p>
+ * <p>
+ * The following are the rules used by this flatten method.
+ * </p>
* <ol>
- * <li>if <code>stopAtNonOption</code> is <b>true</b> then do not
- * burst anymore of <code>arguments</code> entries, just add each
- * successive entry without further processing. Otherwise, ignore
- * <code>stopAtNonOption</code>.</li>
- * <li>if the current <code>arguments</code> entry is "<b>--</b>"
- * just add the entry to the list of processed tokens</li>
- * <li>if the current <code>arguments</code> entry is "<b>-</b>"
- * just add the entry to the list of processed tokens</li>
- * <li>if the current <code>arguments</code> entry is two characters
- * in length and the first character is "<b>-</b>" then check if this
- * is a valid {@link Option} id. If it is a valid id, then add the
- * entry to the list of processed tokens and set the current {@link Option}
- * member. If it is not a valid id and <code>stopAtNonOption</code>
- * is true, then the remaining entries are copied to the list of
- * processed tokens. Otherwise, the current entry is ignored.</li>
- * <li>if the current <code>arguments</code> entry is more than two
- * characters in length and the first character is "<b>-</b>" then
- * we need to burst the entry to determine its constituents. For more
- * information on the bursting algorithm see
- * {@link PosixParser#burstToken(String, boolean) burstToken}.</li>
- * <li>if the current <code>arguments</code> entry is not handled
- * by any of the previous rules, then the entry is added to the list
- * of processed tokens.</li>
+ * <li>if <code>stopAtNonOption</code> is <b>true</b> then do not burst anymore of <code>arguments</code> entries, just
+ * add each successive entry without further processing. Otherwise, ignore <code>stopAtNonOption</code>.</li>
+ * <li>if the current <code>arguments</code> entry is "<b>--</b>" just add the entry to the list of processed
+ * tokens</li>
+ * <li>if the current <code>arguments</code> entry is "<b>-</b>" just add the entry to the list of processed tokens</li>
+ * <li>if the current <code>arguments</code> entry is two characters in length and the first character is "<b>-</b>"
+ * then check if this is a valid {@link Option} id. If it is a valid id, then add the entry to the list of processed
+ * tokens and set the current {@link Option} member. If it is not a valid id and <code>stopAtNonOption</code> is true,
+ * then the remaining entries are copied to the list of processed tokens. Otherwise, the current entry is ignored.</li>
+ * <li>if the current <code>arguments</code> entry is more than two characters in length and the first character is
+ * "<b>-</b>" then we need to burst the entry to determine its constituents. For more information on the bursting
+ * algorithm see {@link PosixParser#burstToken(String, boolean) burstToken}.</li>
+ * <li>if the current <code>arguments</code> entry is not handled by any of the previous rules, then the entry is added
+ * to the list of processed tokens.</li>
* </ol>
*
* @param options The command line {@link Options}
* @param arguments The command line arguments to be parsed
- * @param stopAtNonOption Specifies whether to stop flattening
- * when an non option is found.
+ * @param stopAtNonOption Specifies whether to stop flattening when an non option is found.
* @return The flattened <code>arguments</code> String array.
*/
@Override
- protected String[] flatten(final Options options, final String[] arguments, final boolean stopAtNonOption) throws ParseException
- {
+ protected String[] flatten(final Options options, final String[] arguments, final boolean stopAtNonOption) throws ParseException {
init();
this.options = options;
@@ -101,69 +90,52 @@ public class PosixParser extends Parser
final Iterator<String> iter = Arrays.asList(arguments).iterator();
// process each command line token
- while (iter.hasNext())
- {
+ while (iter.hasNext()) {
// get the next command line token
final String token = iter.next();
// single or double hyphen
- if ("-".equals(token) || "--".equals(token))
- {
+ if ("-".equals(token) || "--".equals(token)) {
tokens.add(token);
}
// handle long option --foo or --foo=bar
- else if (token.startsWith("--"))
- {
+ else if (token.startsWith("--")) {
final int pos = token.indexOf('=');
final String opt = pos == -1 ? token : token.substring(0, pos); // --foo
final List<String> matchingOpts = options.getMatchingOptions(opt);
- if (matchingOpts.isEmpty())
- {
+ if (matchingOpts.isEmpty()) {
processNonOptionToken(token, stopAtNonOption);
- }
- else if (matchingOpts.size() > 1)
- {
+ } else if (matchingOpts.size() > 1) {
throw new AmbiguousOptionException(opt, matchingOpts);
- }
- else
- {
+ } else {
currentOption = options.getOption(matchingOpts.get(0));
tokens.add("--" + currentOption.getLongOpt());
- if (pos != -1)
- {
+ if (pos != -1) {
tokens.add(token.substring(pos + 1));
}
}
}
- else if (token.startsWith("-"))
- {
- if (token.length() == 2 || options.hasOption(token))
- {
+ else if (token.startsWith("-")) {
+ if (token.length() == 2 || options.hasOption(token)) {
processOptionToken(token, stopAtNonOption);
- }
- else if (!options.getMatchingOptions(token).isEmpty())
- {
+ } else if (!options.getMatchingOptions(token).isEmpty()) {
final List<String> matchingOpts = options.getMatchingOptions(token);
- if (matchingOpts.size() > 1)
- {
+ if (matchingOpts.size() > 1) {
throw new AmbiguousOptionException(token, matchingOpts);
}
final Option opt = options.getOption(matchingOpts.get(0));
processOptionToken("-" + opt.getLongOpt(), stopAtNonOption);
}
// requires bursting
- else
- {
+ else {
burstToken(token, stopAtNonOption);
}
- }
- else
- {
+ } else {
processNonOptionToken(token, stopAtNonOption);
}
@@ -178,28 +150,22 @@ public class PosixParser extends Parser
*
* @param iter An iterator over the remaining tokens
*/
- private void gobble(final Iterator<String> iter)
- {
- if (eatTheRest)
- {
- while (iter.hasNext())
- {
+ private void gobble(final Iterator<String> iter) {
+ if (eatTheRest) {
+ while (iter.hasNext()) {
tokens.add(iter.next());
}
}
}
/**
- * 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.
+ * 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.
*
* @param value The current token
*/
- private void processNonOptionToken(final String value, final boolean stopAtNonOption)
- {
- if (stopAtNonOption && (currentOption == null || !currentOption.hasArg()))
- {
+ private void processNonOptionToken(final String value, final boolean stopAtNonOption) {
+ if (stopAtNonOption && (currentOption == null || !currentOption.hasArg())) {
eatTheRest = true;
tokens.add("--");
}
@@ -208,26 +174,24 @@ public class PosixParser extends Parser
}
/**
- * <p>If an {@link Option} exists for <code>token</code> then
- * add the token to the processed list.</p>
+ * <p>
+ * If an {@link Option} exists for <code>token</code> then add the token to the processed list.
+ * </p>
*
- * <p>If an {@link Option} does not exist and <code>stopAtNonOption</code>
- * is set then add the remaining tokens to the processed tokens list
- * directly.</p>
+ * <p>
+ * If an {@link Option} does not exist and <code>stopAtNonOption</code> is set then add the remaining tokens to the
+ * processed tokens list directly.
+ * </p>
*
* @param token The current option token
- * @param stopAtNonOption Specifies whether flattening should halt
- * at the first non option.
+ * @param stopAtNonOption Specifies whether flattening should halt at the first non option.
*/
- private void processOptionToken(final String token, final boolean stopAtNonOption)
- {
- if (stopAtNonOption && !options.hasOption(token))
- {
+ private void processOptionToken(final String token, final boolean stopAtNonOption) {
+ if (stopAtNonOption && !options.hasOption(token)) {
eatTheRest = true;
}
- if (options.hasOption(token))
- {
+ if (options.hasOption(token)) {
currentOption = options.getOption(token);
}
@@ -235,56 +199,42 @@ public class PosixParser extends Parser
}
/**
- * Breaks <code>token</code> into its constituent parts
- * using the following algorithm.
+ * 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>
+ * <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.
+ * @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++)
- {
+ 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))
- {
+ if (options.hasOption(ch)) {
tokens.add("-" + ch);
currentOption = options.getOption(ch);
- if (currentOption.hasArg() && token.length() != i + 1)
- {
+ if (currentOption.hasArg() && token.length() != i + 1) {
tokens.add(token.substring(i + 1));
break;
}
- }
- else if (stopAtNonOption)
- {
+ } else if (stopAtNonOption) {
processNonOptionToken(token.substring(i), true);
break;
- }
- else
- {
+ } 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 768536a..c306594 100644
--- a/src/main/java/org/apache/commons/cli/TypeHandler.java
+++ b/src/main/java/org/apache/commons/cli/TypeHandler.java
@@ -20,138 +20,105 @@ package org.apache.commons.cli;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
-
import java.net.MalformedURLException;
import java.net.URL;
-
import java.util.Date;
/**
- * This is a temporary implementation. TypeHandler will handle the
- * pluggableness of OptionTypes and it will direct all of these types
- * of conversion functionalities to ConvertUtils component in Commons
- * already. BeanUtils I think.
+ * This is a temporary implementation. TypeHandler will handle the pluggableness of OptionTypes and it will direct all
+ * of these types of conversion functionalities to ConvertUtils component in Commons already. BeanUtils I think.
*/
-public class TypeHandler
-{
+public class TypeHandler {
/**
- * Returns the <code>Object</code> of type <code>obj</code>
- * with the value of <code>str</code>.
+ * 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>.
+ * @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
- {
+ public static Object createValue(final String str, final Object obj) throws ParseException {
return createValue(str, (Class<?>) obj);
}
/**
- * Returns the <code>Object</code> of type <code>clazz</code>
- * with the value of <code>str</code>.
+ * Returns the <code>Object</code> of type <code>clazz</code> with the value of <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>.
+ * @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
*/
@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)
- {
+ 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)
- {
+ if (PatternOptionBuilder.OBJECT_VALUE == clazz) {
return (T) createObject(str);
}
- if (PatternOptionBuilder.NUMBER_VALUE == clazz)
- {
+ if (PatternOptionBuilder.NUMBER_VALUE == clazz) {
return (T) createNumber(str);
}
- if (PatternOptionBuilder.DATE_VALUE == clazz)
- {
+ if (PatternOptionBuilder.DATE_VALUE == clazz) {
return (T) createDate(str);
}
- if (PatternOptionBuilder.CLASS_VALUE == clazz)
- {
+ if (PatternOptionBuilder.CLASS_VALUE == clazz) {
return (T) createClass(str);
}
- if (PatternOptionBuilder.FILE_VALUE == clazz)
- {
+ if (PatternOptionBuilder.FILE_VALUE == clazz) {
return (T) createFile(str);
}
- if (PatternOptionBuilder.EXISTING_FILE_VALUE == clazz)
- {
+ if (PatternOptionBuilder.EXISTING_FILE_VALUE == clazz) {
return (T) openFile(str);
}
- if (PatternOptionBuilder.FILES_VALUE == clazz)
- {
+ if (PatternOptionBuilder.FILES_VALUE == clazz) {
return (T) createFiles(str);
}
- if (PatternOptionBuilder.URL_VALUE == clazz)
- {
+ if (PatternOptionBuilder.URL_VALUE == clazz) {
return (T) createURL(str);
}
throw new ParseException("Unable to handle the class: " + clazz);
}
/**
- * Create an Object from the classname and empty constructor.
- *
- * @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 Object createObject(final String classname) throws ParseException
- {
+ * Create an Object from the classname and empty constructor.
+ *
+ * @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 Object createObject(final String classname) throws ParseException {
final Class<?> cl;
- try
- {
+ try {
cl = Class.forName(classname);
- }
- catch (final ClassNotFoundException cnfe)
- {
+ } catch (final ClassNotFoundException cnfe) {
throw new ParseException("Unable to find the class: " + classname);
}
- try
- {
+ try {
return cl.newInstance();
- }
- catch (final Exception e)
- {
+ } catch (final Exception e) {
throw new ParseException(e.getClass().getName() + "; Unable to create an instance of: " + classname);
}
}
/**
- * Create a number from a String. If a . is present, it creates a
- * Double, otherwise a Long.
+ * Create a number from a String. If a . is present, it creates a Double, otherwise a Long.
*
* @param str the value
* @return the number represented by <code>str</code>
* @throws ParseException if <code>str</code> is not a number
*/
- public static Number createNumber(final String str) throws ParseException
- {
- try
- {
- if (str.indexOf('.') != -1)
- {
+ public static Number createNumber(final String str) throws ParseException {
+ try {
+ if (str.indexOf('.') != -1) {
return Double.valueOf(str);
}
return Long.valueOf(str);
- }
- catch (final NumberFormatException e)
- {
+ } catch (final NumberFormatException e) {
throw new ParseException(e.getMessage());
}
}
@@ -163,14 +130,10 @@ public class TypeHandler
* @return The class if it is found
* @throws ParseException if the class could not be found
*/
- public static Class<?> createClass(final String classname) throws ParseException
- {
- try
- {
+ public static Class<?> createClass(final String classname) throws ParseException {
+ try {
return Class.forName(classname);
- }
- catch (final ClassNotFoundException e)
- {
+ } catch (final ClassNotFoundException e) {
throw new ParseException("Unable to find the class: " + classname);
}
}
@@ -178,16 +141,13 @@ public class TypeHandler
/**
* Returns the date represented by <code>str</code>.
* <p>
- * This method is not yet implemented and always throws an
- * {@link UnsupportedOperationException}.
+ * 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.
+ * @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)
- {
+ public static Date createDate(final String str) {
throw new UnsupportedOperationException("Not yet implemented");
}
@@ -198,14 +158,10 @@ public class TypeHandler
* @return The URL in <code>str</code> is well-formed
* @throws ParseException if the URL in <code>str</code> is not well-formed
*/
- public static URL createURL(final String str) throws ParseException
- {
- try
- {
+ public static URL createURL(final String str) throws ParseException {
+ try {
return new URL(str);
- }
- catch (final MalformedURLException e)
- {
+ } catch (final MalformedURLException e) {
throw new ParseException("Unable to parse the URL: " + str);
}
}
@@ -216,8 +172,7 @@ public class TypeHandler
* @param str the File location
* @return The file represented by <code>str</code>.
*/
- public static File createFile(final String str)
- {
+ public static File createFile(final String str) {
return new File(str);
}
@@ -228,14 +183,10 @@ public class TypeHandler
* @return The file input stream represented by <code>str</code>.
* @throws ParseException if the file is not exist or not readable
*/
- public static FileInputStream openFile(final String str) throws ParseException
- {
- try
- {
+ public static FileInputStream openFile(final String str) throws ParseException {
+ try {
return new FileInputStream(str);
- }
- catch (final FileNotFoundException e)
- {
+ } catch (final FileNotFoundException e) {
throw new ParseException("Unable to find file: " + str);
}
}
@@ -243,17 +194,15 @@ public class TypeHandler
/**
* Returns the File[] represented by <code>str</code>.
* <p>
- * This method is not yet implemented and always throws an
- * {@link UnsupportedOperationException}.
+ * 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)
- {
+ public static File[] createFiles(final String str) {
// to implement/port:
- // return FileW.findFiles(str);
+ // return FileW.findFiles(str);
throw new UnsupportedOperationException("Not yet implemented");
}
}
diff --git a/src/main/java/org/apache/commons/cli/UnrecognizedOptionException.java b/src/main/java/org/apache/commons/cli/UnrecognizedOptionException.java
index 33515e4..49df554 100644
--- a/src/main/java/org/apache/commons/cli/UnrecognizedOptionException.java
+++ b/src/main/java/org/apache/commons/cli/UnrecognizedOptionException.java
@@ -18,40 +18,34 @@
package org.apache.commons.cli;
/**
- * Exception thrown during parsing signalling an unrecognized
- * option was seen.
+ * Exception thrown during parsing signalling an unrecognized option was seen.
*/
-public class UnrecognizedOptionException extends ParseException
-{
+public class UnrecognizedOptionException extends ParseException {
/**
* This exception {@code serialVersionUID}.
*/
private static final long serialVersionUID = -252504690284625623L;
- /** The unrecognized option */
+ /** The unrecognized option */
private String option;
/**
- * Construct a new <code>UnrecognizedArgumentException</code>
- * with the specified detail message.
+ * Construct a new <code>UnrecognizedArgumentException</code> with the specified detail message.
*
* @param message the detail message
*/
- public UnrecognizedOptionException(final String message)
- {
+ public UnrecognizedOptionException(final String message) {
super(message);
}
/**
- * Construct a new <code>UnrecognizedArgumentException</code>
- * with the specified option and detail message.
+ * Construct a new <code>UnrecognizedArgumentException</code> with the specified option and detail message.
*
* @param message the detail message
- * @param option the unrecognized option
+ * @param option the unrecognized option
* @since 1.2
*/
- public UnrecognizedOptionException(final String message, final String option)
- {
+ public UnrecognizedOptionException(final String message, final String option) {
this(message);
this.option = option;
}
@@ -62,8 +56,7 @@ public class UnrecognizedOptionException extends ParseException
* @return the related option
* @since 1.2
*/
- public String getOption()
- {
+ public String getOption() {
return option;
}
}
diff --git a/src/main/java/org/apache/commons/cli/Util.java b/src/main/java/org/apache/commons/cli/Util.java
index cfcdd58..47257c0 100644
--- a/src/main/java/org/apache/commons/cli/Util.java
+++ b/src/main/java/org/apache/commons/cli/Util.java
@@ -20,28 +20,22 @@ package org.apache.commons.cli;
/**
* Contains useful helper methods for classes within this package.
*/
-final class Util
-{
+final class Util {
/**
- * Remove the hyphens from the beginning of <code>str</code> and
- * return the new String.
+ * 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.
*
* @return the new String.
*/
- static String stripLeadingHyphens(final String str)
- {
- if (str == null)
- {
+ static String stripLeadingHyphens(final String str) {
+ if (str == null) {
return null;
}
- if (str.startsWith("--"))
- {
+ if (str.startsWith("--")) {
return str.substring(2);
}
- if (str.startsWith("-"))
- {
+ if (str.startsWith("-")) {
return str.substring(1);
}
@@ -49,19 +43,15 @@ 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.
+ * 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.
+ * @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)
- {
+ static String stripLeadingAndTrailingQuotes(String str) {
final int length = str.length();
- if (length > 1 && str.startsWith("\"") && str.endsWith("\"") && str.substring(1, length - 1).indexOf('"') == -1)
- {
+ if (length > 1 && str.startsWith("\"") && str.endsWith("\"") && str.substring(1, length - 1).indexOf('"') == -1) {
str = str.substring(1, length - 1);
}
diff --git a/src/test/java/org/apache/commons/cli/ApplicationTest.java b/src/test/java/org/apache/commons/cli/ApplicationTest.java
index d0c510b..8abdfbe 100644
--- a/src/test/java/org/apache/commons/cli/ApplicationTest.java
+++ b/src/test/java/org/apache/commons/cli/ApplicationTest.java
@@ -31,38 +31,40 @@ import org.junit.Test;
* <p>
* The following applications are tested:
* <ul>
- * <li>ls</li>
- * <li>Ant</li>
- * <li>Groovy</li>
- * <li>man</li>
+ * <li>ls</li>
+ * <li>Ant</li>
+ * <li>Groovy</li>
+ * <li>man</li>
* </ul>
* </p>
*/
@SuppressWarnings("deprecation") // tests some deprecated classes
-public class ApplicationTest
-{
+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" );
- options.addOption( OptionBuilder.withLongOpt( "block-size" )
- .withDescription( "use SIZE-byte blocks" )
+ 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() );
- 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" );
+ .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 = new String[]{ "--block-size=10" };
+ final String[] args = {"--block-size=10"};
- final CommandLine line = parser.parse( options, args );
- assertTrue( line.hasOption( "block-size" ) );
- assertEquals( line.getOptionValue( "block-size" ), "10" );
+ final CommandLine line = parser.parse(options, args);
+ assertTrue(line.hasOption("block-size"));
+ assertEquals(line.getOptionValue("block-size"), "10");
}
/**
@@ -71,49 +73,50 @@ public class ApplicationTest
@Test
public void testAnt() throws Exception {
// use the GNU parser
- final CommandLineParser parser = new GnuParser( );
+ final CommandLineParser parser = new GnuParser();
final Options options = new Options();
- options.addOption( "help", false, "print this message" );
- options.addOption( "projecthelp", false, "print project help information" );
- options.addOption( "version", false, "print the version information and exit" );
- options.addOption( "quiet", false, "be extra quiet" );
- options.addOption( "verbose", false, "be extra verbose" );
- options.addOption( "debug", false, "print debug information" );
- options.addOption( "logfile", true, "use given file for log" );
- options.addOption( "logger", true, "the class which is to perform the logging" );
- options.addOption( "listener", true, "add an instance of a class as a project listener" );
- options.addOption( "buildfile", true, "use given buildfile" );
- options.addOption( OptionBuilder.withDescription( "use value for given property" )
+ options.addOption("help", false, "print this message");
+ options.addOption("projecthelp", false, "print project help information");
+ options.addOption("version", false, "print the version information and exit");
+ options.addOption("quiet", false, "be extra quiet");
+ options.addOption("verbose", false, "be extra verbose");
+ options.addOption("debug", false, "print debug information");
+ options.addOption("logfile", true, "use given file for log");
+ options.addOption("logger", true, "the class which is to perform the logging");
+ options.addOption("listener", true, "add an instance of a class as a project listener");
+ options.addOption("buildfile", true, "use given buildfile");
+ //@formatter:off
+ options.addOption(OptionBuilder.withDescription("use value for given property")
.hasArgs()
.withValueSeparator()
- .create( 'D' ) );
- //, null, true, , false, true );
- options.addOption( "find", true, "search for buildfile towards the root of the filesystem and use it" );
+ .create('D'));
+ //, null, true, , false, true);
+ //@formatter:on
+ options.addOption("find", true, "search for buildfile towards the root of the filesystem and use it");
- final String[] args = new String[]{ "-buildfile", "mybuild.xml",
- "-Dproperty=value", "-Dproperty1=value1",
- "-projecthelp" };
+ final String[] args = {"-buildfile", "mybuild.xml", "-Dproperty=value", "-Dproperty1=value1", "-projecthelp"};
- final CommandLine line = parser.parse( options, args );
+ final CommandLine line = parser.parse(options, args);
// check multiple values
- final String[] opts = line.getOptionValues( "D" );
- assertEquals( "property", opts[0] );
- assertEquals( "value", opts[1] );
- assertEquals( "property1", opts[2] );
- assertEquals( "value1", opts[3] );
+ final String[] opts = line.getOptionValues("D");
+ assertEquals("property", opts[0]);
+ assertEquals("value", opts[1]);
+ assertEquals("property1", opts[2]);
+ assertEquals("value1", opts[3]);
// check single value
- assertEquals( line.getOptionValue( "buildfile"), "mybuild.xml" );
+ assertEquals(line.getOptionValue("buildfile"), "mybuild.xml");
// check option
- assertTrue( line.hasOption( "projecthelp") );
+ assertTrue(line.hasOption("projecthelp"));
}
@Test
public void testGroovy() throws Exception {
final Options options = new Options();
+ //@formatter:off
options.addOption(
OptionBuilder.withLongOpt("define").
withDescription("define a system property").
@@ -122,57 +125,58 @@ public class ApplicationTest
create('D'));
options.addOption(
OptionBuilder.hasArg(false)
- .withDescription("usage information")
- .withLongOpt("help")
- .create('h'));
+ .withDescription("usage information")
+ .withLongOpt("help")
+ .create('h'));
options.addOption(
OptionBuilder.hasArg(false)
- .withDescription("debug mode will print out full stack traces")
- .withLongOpt("debug")
- .create('d'));
+ .withDescription("debug mode will print out full stack traces")
+ .withLongOpt("debug")
+ .create('d'));
options.addOption(
OptionBuilder.hasArg(false)
- .withDescription("display the Groovy and JVM versions")
- .withLongOpt("version")
- .create('v'));
+ .withDescription("display the Groovy and JVM versions")
+ .withLongOpt("version")
+ .create('v'));
options.addOption(
OptionBuilder.withArgName("charset")
- .hasArg()
- .withDescription("specify the encoding of the files")
- .withLongOpt("encoding")
- .create('c'));
+ .hasArg()
+ .withDescription("specify the encoding of the files")
+ .withLongOpt("encoding")
+ .create('c'));
options.addOption(
OptionBuilder.withArgName("script")
- .hasArg()
- .withDescription("specify a command line script")
- .create('e'));
+ .hasArg()
+ .withDescription("specify a command line script")
+ .create('e'));
options.addOption(
OptionBuilder.withArgName("extension")
- .hasOptionalArg()
- .withDescription("modify files in place; create backup if extension is given (e.g. \'.bak\')")
- .create('i'));
+ .hasOptionalArg()
+ .withDescription("modify files in place; create backup if extension is given (e.g. \'.bak\')")
+ .create('i'));
options.addOption(
OptionBuilder.hasArg(false)
- .withDescription("process files line by line using implicit 'line' variable")
- .create('n'));
+ .withDescription("process files line by line using implicit 'line' variable")
+ .create('n'));
options.addOption(
OptionBuilder.hasArg(false)
- .withDescription("process files line by line and print result (see also -n)")
- .create('p'));
+ .withDescription("process files line by line and print result (see also -n)")
+ .create('p'));
options.addOption(
OptionBuilder.withArgName("port")
- .hasOptionalArg()
- .withDescription("listen on a port and process inbound lines")
- .create('l'));
+ .hasOptionalArg()
+ .withDescription("listen on a port and process inbound lines")
+ .create('l'));
options.addOption(
OptionBuilder.withArgName("splitPattern")
- .hasOptionalArg()
- .withDescription("split lines using splitPattern (default '\\s') using implicit 'split' variable")
- .withLongOpt("autosplit")
- .create('a'));
+ .hasOptionalArg()
+ .withDescription("split lines using splitPattern (default '\\s') using implicit 'split' variable")
+ .withLongOpt("autosplit")
+ .create('a'));
+ //@formatter:on
final Parser parser = new PosixParser();
- final CommandLine line = parser.parse(options, new String[] { "-e", "println 'hello'" }, true);
+ final CommandLine line = parser.parse(options, new String[] {"-e", "println 'hello'"}, true);
assertTrue(line.hasOption('e'));
assertEquals("println 'hello'", line.getOptionValue('e'));
@@ -182,11 +186,10 @@ public class ApplicationTest
* author Slawek Zachcial
*/
@Test
- public void testMan()
- {
- final String cmdLine =
- "man [-c|-f|-k|-w|-tZT device] [-adlhu7V] [-Mpath] [-Ppager] [-Slist] " +
- "[-msystem] [-pstring] [-Llocale] [-eextension] [section] page ...";
+ public void testMan() {
+ final String cmdLine = "man [-c|-f|-k|-w|-tZT device] [-adlhu7V] [-Mpath] [-Ppager] [-Slist] [-msystem] [-pstring] [-Llocale] [-eextension] [section]"
+ + " page ...";
+ //@formatter:off
final Options options = new Options().
addOption("a", "all", false, "find all matching manual pages.").
addOption("d", "debug", false, "emit debugging messages.").
@@ -221,55 +224,57 @@ public class ApplicationTest
" g - grap r - refer v - vgrind").
addOption("V", "version", false, "show version.").
addOption("h", "help", false, "show this usage message.");
+ //@formatter:on
final HelpFormatter hf = new HelpFormatter();
- final String EOL = System.getProperty("line.separator");
+ final String eol = System.getProperty("line.separator");
final StringWriter out = new StringWriter();
hf.printHelp(new PrintWriter(out), 60, cmdLine, null, options, HelpFormatter.DEFAULT_LEFT_PAD, HelpFormatter.DEFAULT_DESC_PAD, null, false);
- assertEquals("usage: man [-c|-f|-k|-w|-tZT device] [-adlhu7V] [-Mpath]" + EOL +
- " [-Ppager] [-Slist] [-msystem] [-pstring]" + EOL +
- " [-Llocale] [-eextension] [section] page ..." + EOL +
- " -7,--ascii display ASCII translation or" + EOL +
- " certain latin1 chars." + EOL +
- " -a,--all find all matching manual pages." + EOL +
- " -c,--catman used by catman to reformat out of" + EOL +
- " date cat pages." + EOL +
- " -d,--debug emit debugging messages." + EOL +
- " -D,--default reset all options to their" + EOL +
- " default values." + EOL +
- " -e,--extension limit search to extension type" + EOL +
- " 'extension'." + EOL +
- " -f,--whatis equivalent to whatis." + EOL +
- " -h,--help show this usage message." + EOL +
- " -k,--apropos equivalent to apropos." + EOL +
- " -l,--local-file interpret 'page' argument(s) as" + EOL +
- " local filename(s)" + EOL +
- " -L,--locale <arg> define the locale for this" + EOL +
- " particular man search." + EOL +
- " -M,--manpath <arg> set search path for manual pages" + EOL +
- " to 'path'." + EOL +
- " -m,--systems <arg> search for man pages from other" + EOL +
- " unix system(s)." + EOL +
- " -P,--pager <arg> use program 'pager' to display" + EOL +
- " output." + EOL +
- " -p,--preprocessor <arg> string indicates which" + EOL +
- " preprocessor to run." + EOL +
- " e - [n]eqn p - pic t - tbl" + EOL +
- " g - grap r - refer v -" + EOL +
- " vgrind" + EOL +
- " -r,--prompt <arg> provide 'less' pager with prompt." + EOL +
- " -S,--sections <arg> use colon separated section list." + EOL +
- " -t,--troff use troff format pages." + EOL +
- " -T,--troff-device <arg> use groff with selected device." + EOL +
- " -u,--update force a cache consistency check." + EOL +
- " -V,--version show version." + EOL +
- " -w,--location print physical location of man" + EOL +
- " page(s)." + EOL +
- " -Z,--ditroff use groff with selected device." + EOL,
+ //@formatter:off
+ assertEquals("usage: man [-c|-f|-k|-w|-tZT device] [-adlhu7V] [-Mpath]" + eol +
+ " [-Ppager] [-Slist] [-msystem] [-pstring]" + eol +
+ " [-Llocale] [-eextension] [section] page ..." + eol +
+ " -7,--ascii display ASCII translation or" + eol +
+ " certain latin1 chars." + eol +
+ " -a,--all find all matching manual pages." + eol +
+ " -c,--catman used by catman to reformat out of" + eol +
+ " date cat pages." + eol +
+ " -d,--debug emit debugging messages." + eol +
+ " -D,--default reset all options to their" + eol +
+ " default values." + eol +
+ " -e,--extension limit search to extension type" + eol +
+ " 'extension'." + eol +
+ " -f,--whatis equivalent to whatis." + eol +
+ " -h,--help show this usage message." + eol +
+ " -k,--apropos equivalent to apropos." + eol +
+ " -l,--local-file interpret 'page' argument(s) as" + eol +
+ " local filename(s)" + eol +
+ " -L,--locale <arg> define the locale for this" + eol +
+ " particular man search." + eol +
+ " -M,--manpath <arg> set search path for manual pages" + eol +
+ " to 'path'." + eol +
+ " -m,--systems <arg> search for man pages from other" + eol +
+ " unix system(s)." + eol +
+ " -P,--pager <arg> use program 'pager' to display" + eol +
+ " output." + eol +
+ " -p,--preprocessor <arg> string indicates which" + eol +
+ " preprocessor to run." + eol +
+ " e - [n]eqn p - pic t - tbl" + eol +
+ " g - grap r - refer v -" + eol +
+ " vgrind" + eol +
+ " -r,--prompt <arg> provide 'less' pager with prompt." + eol +
+ " -S,--sections <arg> use colon separated section list." + eol +
+ " -t,--troff use troff format pages." + eol +
+ " -T,--troff-device <arg> use groff with selected device." + eol +
+ " -u,--update force a cache consistency check." + eol +
+ " -V,--version show version." + eol +
+ " -w,--location print physical location of man" + eol +
+ " page(s)." + eol +
+ " -Z,--ditroff use groff with selected device." + eol,
out.toString());
+ //@formatter:on
}
-
/**
* Real world test with long and short options.
*/
@@ -280,6 +285,7 @@ public class ApplicationTest
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 = OptionBuilder.withLongOpt("limit").hasArg()
.withValueSeparator()
.withDescription("Set time limit for execution, in minutes")
@@ -304,6 +310,7 @@ public class ApplicationTest
.withValueSeparator()
.withDescription("Use the specified configuration file")
.create();
+ //@formatter:on
final Options options = new Options();
options.addOption(help);
@@ -319,15 +326,7 @@ public class ApplicationTest
// create the command line parser
final CommandLineParser parser = new PosixParser();
- final String[] args = new String[] {
- "-v",
- "-l",
- "10",
- "-age",
- "5",
- "-file",
- "filename"
- };
+ final String[] args = {"-v", "-l", "10", "-age", "5", "-file", "filename"};
final CommandLine line = parser.parse(options, args);
assertTrue(line.hasOption("v"));
diff --git a/src/test/java/org/apache/commons/cli/ArgumentIsOptionTest.java b/src/test/java/org/apache/commons/cli/ArgumentIsOptionTest.java
index 3f7be55..4da03f5 100644
--- a/src/test/java/org/apache/commons/cli/ArgumentIsOptionTest.java
+++ b/src/test/java/org/apache/commons/cli/ArgumentIsOptionTest.java
@@ -24,27 +24,20 @@ import org.junit.Before;
import org.junit.Test;
@SuppressWarnings("deprecation") // tests some deprecated classes
-public class ArgumentIsOptionTest
-{
- private Options options = null;
- private CommandLineParser parser = null;
+public class ArgumentIsOptionTest {
+
+ private Options options;
+ private CommandLineParser parser;
@Before
- public void setUp()
- {
+ public void setUp() {
options = new Options().addOption("p", false, "Option p").addOption("attr", true, "Option accepts argument");
-
parser = new PosixParser();
}
@Test
- public void testOptionAndOptionWithArgument() throws Exception
- {
- final String[] args = new String[]{
- "-p",
- "-attr",
- "p"
- };
+ public void testOptionAndOptionWithArgument() throws Exception {
+ final String[] args = {"-p", "-attr", "p"};
final CommandLine cl = parser.parse(options, args);
assertTrue("Confirm -p is set", cl.hasOption("p"));
@@ -54,27 +47,19 @@ public class ArgumentIsOptionTest
}
@Test
- public void testOptionWithArgument() throws Exception
- {
- final String[] args = new String[]{
- "-attr",
- "p"
- };
+ public void testOptionWithArgument() throws Exception {
+ final String[] args = {"-attr", "p"};
final CommandLine cl = parser.parse(options, args);
assertFalse("Confirm -p is set", cl.hasOption("p"));
assertTrue("Confirm -attr is set", cl.hasOption("attr"));
- assertTrue("Confirm arg of -attr",
- cl.getOptionValue("attr").equals("p"));
+ 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 = new String[]{
- "-p"
- };
+ public void testOption() throws Exception {
+ final String[] args = {"-p"};
final CommandLine cl = parser.parse(options, args);
assertTrue("Confirm -p is set", cl.hasOption("p"));
diff --git a/src/test/java/org/apache/commons/cli/BasicParserTest.java b/src/test/java/org/apache/commons/cli/BasicParserTest.java
index 0a3b3c0..c6d06f0 100644
--- a/src/test/java/org/apache/commons/cli/BasicParserTest.java
+++ b/src/test/java/org/apache/commons/cli/BasicParserTest.java
@@ -22,133 +22,155 @@ import org.junit.Ignore;
import org.junit.Test;
@SuppressWarnings("deprecation") // tests some deprecated classes
-public class BasicParserTest extends ParserTestCase
-{
+public class BasicParserTest extends ParserTestCase {
@Override
@Before
- public void setUp()
- {
+ public void setUp() {
super.setUp();
parser = new BasicParser();
}
- @Override @Test @Ignore("not supported by the BasicParser")
- public void testDoubleDash2() throws Exception
- {
+ @Override
+ @Test
+ @Ignore("not supported by the BasicParser")
+ public void testDoubleDash2() throws Exception {
}
- @Override @Test @Ignore("not supported by the BasicParser")
- public void testLongWithoutEqualSingleDash() throws Exception
- {
+ @Override
+ @Test
+ @Ignore("not supported by the BasicParser")
+ public void testLongWithoutEqualSingleDash() throws Exception {
}
- @Override @Test @Ignore("not supported by the BasicParser")
- public void testAmbiguousLongWithoutEqualSingleDash() throws Exception
- {
+ @Override
+ @Test
+ @Ignore("not supported by the BasicParser")
+ public void testAmbiguousLongWithoutEqualSingleDash() throws Exception {
}
- @Override @Test @Ignore("not supported by the BasicParser (CLI-184)")
- public void testNegativeOption() throws Exception
- {
+ @Override
+ @Test
+ @Ignore("not supported by the BasicParser (CLI-184)")
+ public void testNegativeOption() throws Exception {
}
- @Override @Test @Ignore("not supported by the BasicParser")
- public void testPropertiesOption1() throws Exception
- {
+ @Override
+ @Test
+ @Ignore("not supported by the BasicParser")
+ public void testPropertiesOption1() throws Exception {
}
- @Override @Test @Ignore("not supported by the BasicParser")
- public void testPropertiesOption2() throws Exception
- {
+ @Override
+ @Test
+ @Ignore("not supported by the BasicParser")
+ public void testPropertiesOption2() throws Exception {
}
- @Override @Test @Ignore("not supported by the BasicParser")
- public void testShortWithEqual() throws Exception
- {
+ @Override
+ @Test
+ @Ignore("not supported by the BasicParser")
+ public void testShortWithEqual() throws Exception {
}
- @Override @Test @Ignore("not supported by the BasicParser")
- public void testShortWithoutEqual() throws Exception
- {
+ @Override
+ @Test
+ @Ignore("not supported by the BasicParser")
+ public void testShortWithoutEqual() throws Exception {
}
- @Override @Test @Ignore("not supported by the BasicParser")
- public void testLongWithEqualDoubleDash() throws Exception
- {
+ @Override
+ @Test
+ @Ignore("not supported by the BasicParser")
+ public void testLongWithEqualDoubleDash() throws Exception {
}
- @Override @Test @Ignore("not supported by the BasicParser")
- public void testLongWithEqualSingleDash() throws Exception
- {
+ @Override
+ @Test
+ @Ignore("not supported by the BasicParser")
+ public void testLongWithEqualSingleDash() throws Exception {
}
- @Override @Test @Ignore("not supported by the BasicParser")
- public void testUnambiguousPartialLongOption1() throws Exception
- {
+ @Override
+ @Test
+ @Ignore("not supported by the BasicParser")
+ public void testUnambiguousPartialLongOption1() throws Exception {
}
- @Override @Test @Ignore("not supported by the BasicParser")
- public void testUnambiguousPartialLongOption2() throws Exception
- {
+ @Override
+ @Test
+ @Ignore("not supported by the BasicParser")
+ public void testUnambiguousPartialLongOption2() throws Exception {
}
- @Override @Test @Ignore("not supported by the BasicParser")
- public void testUnambiguousPartialLongOption3() throws Exception
- {
+ @Override
+ @Test
+ @Ignore("not supported by the BasicParser")
+ public void testUnambiguousPartialLongOption3() throws Exception {
}
- @Override @Test @Ignore("not supported by the BasicParser")
- public void testUnambiguousPartialLongOption4() throws Exception
- {
+ @Override
+ @Test
+ @Ignore("not supported by the BasicParser")
+ public void testUnambiguousPartialLongOption4() throws Exception {
}
- @Override @Test @Ignore("not supported by the BasicParser")
- public void testAmbiguousPartialLongOption1() throws Exception
- {
+ @Override
+ @Test
+ @Ignore("not supported by the BasicParser")
+ public void testAmbiguousPartialLongOption1() throws Exception {
}
- @Override @Test @Ignore("not supported by the BasicParser")
- public void testAmbiguousPartialLongOption2() throws Exception
- {
+ @Override
+ @Test
+ @Ignore("not supported by the BasicParser")
+ public void testAmbiguousPartialLongOption2() throws Exception {
}
- @Override @Test @Ignore("not supported by the BasicParser")
- public void testAmbiguousPartialLongOption3() throws Exception
- {
+ @Override
+ @Test
+ @Ignore("not supported by the BasicParser")
+ public void testAmbiguousPartialLongOption3() throws Exception {
}
- @Override @Test @Ignore("not supported by the BasicParser")
- public void testAmbiguousPartialLongOption4() throws Exception
- {
+ @Override
+ @Test
+ @Ignore("not supported by the BasicParser")
+ public void testAmbiguousPartialLongOption4() throws Exception {
}
- @Override @Test @Ignore("not supported by the BasicParser")
- public void testPartialLongOptionSingleDash() throws Exception
- {
+ @Override
+ @Test
+ @Ignore("not supported by the BasicParser")
+ public void testPartialLongOptionSingleDash() throws Exception {
}
- @Override @Test @Ignore("not supported by the BasicParser")
- public void testBursting() throws Exception
- {
+ @Override
+ @Test
+ @Ignore("not supported by the BasicParser")
+ public void testBursting() throws Exception {
}
- @Override @Test @Ignore("not supported by the BasicParser")
- public void testUnrecognizedOptionWithBursting() throws Exception
- {
+ @Override
+ @Test
+ @Ignore("not supported by the BasicParser")
+ public void testUnrecognizedOptionWithBursting() throws Exception {
}
- @Override @Test @Ignore("not supported by the BasicParser")
- public void testMissingArgWithBursting() throws Exception
- {
+ @Override
+ @Test
+ @Ignore("not supported by the BasicParser")
+ public void testMissingArgWithBursting() throws Exception {
}
- @Override @Test @Ignore("not supported by the BasicParser")
- public void testStopBursting() throws Exception
- {
+ @Override
+ @Test
+ @Ignore("not supported by the BasicParser")
+ public void testStopBursting() throws Exception {
}
- @Override @Test @Ignore("not supported by the BasicParser")
- public void testStopBursting2() throws Exception
- {
+ @Override
+ @Test
+ @Ignore("not supported by the BasicParser")
+ public void testStopBursting2() 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 0f9fa30..7056cd2 100644
--- a/src/test/java/org/apache/commons/cli/CommandLineTest.java
+++ b/src/test/java/org/apache/commons/cli/CommandLineTest.java
@@ -26,12 +26,11 @@ import java.util.Properties;
import org.junit.Test;
@SuppressWarnings("deprecation") // tests some deprecated classes
-public class CommandLineTest
-{
+public class CommandLineTest {
+
@Test
- public void testGetOptionProperties() throws Exception
- {
- final String[] args = new String[] { "-Dparam1=value1", "-Dparam2=value2", "-Dparam3", "-Dparam4=value4", "-D", "--property", "foo=bar" };
+ public void testGetOptionProperties() throws Exception {
+ final String[] args = {"-Dparam1=value1", "-Dparam2=value2", "-Dparam3", "-Dparam4=value4", "-D", "--property", "foo=bar"};
final Options options = new Options();
options.addOption(OptionBuilder.withValueSeparator().hasOptionalArgs(2).create('D'));
@@ -52,20 +51,19 @@ public class CommandLineTest
}
@Test
- public void testGetOptionPropertiesWithOption() throws Exception
- {
- final String[] args = new String[] { "-Dparam1=value1", "-Dparam2=value2", "-Dparam3", "-Dparam4=value4", "-D", "--property", "foo=bar" };
+ public void testGetOptionPropertiesWithOption() throws Exception {
+ final String[] args = {"-Dparam1=value1", "-Dparam2=value2", "-Dparam3", "-Dparam4=value4", "-D", "--property", "foo=bar"};
final Options options = new Options();
- final Option option_D = OptionBuilder.withValueSeparator().hasOptionalArgs(2).create('D');
- final Option option_property = OptionBuilder.withValueSeparator().hasArgs(2).withLongOpt("property").create();
- options.addOption(option_D);
- options.addOption(option_property);
+ final Option optionD = OptionBuilder.withValueSeparator().hasOptionalArgs(2).create('D');
+ final Option optionProperty = OptionBuilder.withValueSeparator().hasArgs(2).withLongOpt("property").create();
+ options.addOption(optionD);
+ options.addOption(optionProperty);
final Parser parser = new GnuParser();
final CommandLine cl = parser.parse(options, args);
- final Properties props = cl.getOptionProperties(option_D);
+ final Properties props = cl.getOptionProperties(optionD);
assertNotNull("null properties", props);
assertEquals("number of properties in " + props, 4, props.size());
assertEquals("property 1", "value1", props.getProperty("param1"));
@@ -73,12 +71,11 @@ public class CommandLineTest
assertEquals("property 3", "true", props.getProperty("param3"));
assertEquals("property 4", "value4", props.getProperty("param4"));
- assertEquals("property with long format", "bar", cl.getOptionProperties(option_property).getProperty("foo"));
+ assertEquals("property with long format", "bar", cl.getOptionProperties(optionProperty).getProperty("foo"));
}
@Test
- public void testGetOptions()
- {
+ public void testGetOptions() {
final CommandLine cmd = new CommandLine();
assertNotNull(cmd.getOptions());
assertEquals(0, cmd.getOptions().length);
@@ -97,7 +94,7 @@ public class CommandLineTest
options.addOption(OptionBuilder.hasArg().create("f"));
final CommandLineParser parser = new DefaultParser();
- final CommandLine cmd = parser.parse(options, new String[] { "-i", "123", "-f", "foo" });
+ final CommandLine cmd = parser.parse(options, new String[] {"-i", "123", "-f", "foo"});
assertEquals(123, ((Number) cmd.getParsedOptionValue("i")).intValue());
assertEquals("foo", cmd.getParsedOptionValue("f"));
@@ -110,7 +107,7 @@ public class CommandLineTest
options.addOption(Option.builder("f").hasArg().build());
final CommandLineParser parser = new DefaultParser();
- final CommandLine cmd = parser.parse(options, new String[] { "-i", "123", "-f", "foo" });
+ final CommandLine cmd = parser.parse(options, new String[] {"-i", "123", "-f", "foo"});
assertEquals(123, ((Number) cmd.getParsedOptionValue('i')).intValue());
assertEquals("foo", cmd.getParsedOptionValue('f'));
@@ -119,42 +116,40 @@ public class CommandLineTest
@Test
public void testGetParsedOptionValueWithOption() throws Exception {
final Options options = new Options();
- final Option opt_i = Option.builder("i").hasArg().type(Number.class).build();
- final Option opt_f = Option.builder("f").hasArg().build();
- options.addOption(opt_i);
- options.addOption(opt_f);
+ final Option optI = Option.builder("i").hasArg().type(Number.class).build();
+ final Option optF = Option.builder("f").hasArg().build();
+ options.addOption(optI);
+ options.addOption(optF);
final CommandLineParser parser = new DefaultParser();
- final CommandLine cmd = parser.parse(options, new String[] { "-i", "123", "-f", "foo" });
+ final CommandLine cmd = parser.parse(options, new String[] {"-i", "123", "-f", "foo"});
- assertEquals(123, ((Number) cmd.getParsedOptionValue(opt_i)).intValue());
- assertEquals("foo", cmd.getParsedOptionValue(opt_f));
+ assertEquals(123, ((Number) cmd.getParsedOptionValue(optI)).intValue());
+ assertEquals("foo", cmd.getParsedOptionValue(optF));
}
@Test
public void testNullhOption() throws Exception {
final Options options = new Options();
- final Option opt_i = Option.builder("i").hasArg().type(Number.class).build();
- final Option opt_f = Option.builder("f").hasArg().build();
- options.addOption(opt_i);
- options.addOption(opt_f);
+ final Option optI = Option.builder("i").hasArg().type(Number.class).build();
+ final Option optF = Option.builder("f").hasArg().build();
+ options.addOption(optI);
+ options.addOption(optF);
final CommandLineParser parser = new DefaultParser();
- final CommandLine cmd = parser.parse(options, new String[] { "-i", "123", "-f", "foo" });
- assertNull(cmd.getOptionValue((Option)null));
- assertNull(cmd.getParsedOptionValue((Option)null));
+ final CommandLine cmd = parser.parse(options, new String[] {"-i", "123", "-f", "foo"});
+ assertNull(cmd.getOptionValue((Option) null));
+ assertNull(cmd.getParsedOptionValue((Option) null));
}
@Test
- public void testBuilder()
- throws Exception
- {
+ public void testBuilder() throws Exception {
final CommandLine.Builder builder = new CommandLine.Builder();
- builder.addArg( "foo" ).addArg( "bar" );
- builder.addOption( Option.builder( "T" ).build() );
+ 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() );
+ 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/DisablePartialMatchingTest.java b/src/test/java/org/apache/commons/cli/DisablePartialMatchingTest.java
index 521b702..a71b5bf 100644
--- a/src/test/java/org/apache/commons/cli/DisablePartialMatchingTest.java
+++ b/src/test/java/org/apache/commons/cli/DisablePartialMatchingTest.java
@@ -17,15 +17,14 @@
package org.apache.commons.cli;
-import org.junit.Test;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.*;
+import org.junit.Test;
-public class DisablePartialMatchingTest
-{
+public class DisablePartialMatchingTest {
@Test
- public void testDisablePartialMatching() throws Exception
- {
+ public void testDisablePartialMatching() throws Exception {
final CommandLineParser parser = new DefaultParser(false);
final Options options = new Options();
@@ -34,7 +33,7 @@ public class DisablePartialMatchingTest
options.addOption(new Option("e", "extract", false, "Turn on extract."));
options.addOption(new Option("o", "option", true, "Turn on option with argument."));
- final CommandLine line = parser.parse(options, new String[]{"-de", "--option=foobar"});
+ final CommandLine line = parser.parse(options, new String[] {"-de", "--option=foobar"});
assertTrue("There should be an option debug in any case...", line.hasOption("debug"));
assertTrue("There should be an extract option because partial matching is off", line.hasOption("extract"));
@@ -42,8 +41,7 @@ public class DisablePartialMatchingTest
}
@Test
- public void testRegularPartialMatching() throws Exception
- {
+ public void testRegularPartialMatching() throws Exception {
final CommandLineParser parser = new DefaultParser();
final Options options = new Options();
@@ -52,8 +50,7 @@ public class DisablePartialMatchingTest
options.addOption(new Option("e", "extract", false, "Turn on extract."));
options.addOption(new Option("o", "option", true, "Turn on option with argument."));
-
- final CommandLine line = parser.parse(options, new String[]{"-de", "--option=foobar"});
+ final CommandLine line = parser.parse(options, new String[] {"-de", "--option=foobar"});
assertTrue("There should be an option debug in any case...", line.hasOption("debug"));
assertFalse("There should not be an extract option because partial matching only selects debug", line.hasOption("extract"));
diff --git a/src/test/java/org/apache/commons/cli/GnuParserTest.java b/src/test/java/org/apache/commons/cli/GnuParserTest.java
index 680747a..af289a4 100644
--- a/src/test/java/org/apache/commons/cli/GnuParserTest.java
+++ b/src/test/java/org/apache/commons/cli/GnuParserTest.java
@@ -22,118 +22,137 @@ import org.junit.Ignore;
import org.junit.Test;
@SuppressWarnings("deprecation") // tests some deprecated classes
-public class GnuParserTest extends ParserTestCase
-{
+public class GnuParserTest extends ParserTestCase {
@Override
@Before
- public void setUp()
- {
+ public void setUp() {
super.setUp();
parser = new GnuParser();
}
- @Override @Test @Ignore("not supported by the GnuParser")
- public void testDoubleDash2() throws Exception
- {
+ @Override
+ @Test
+ @Ignore("not supported by the GnuParser")
+ public void testDoubleDash2() throws Exception {
}
- @Override @Test @Ignore("not supported by the GnuParser")
- public void testLongWithoutEqualSingleDash() throws Exception
- {
+ @Override
+ @Test
+ @Ignore("not supported by the GnuParser")
+ public void testLongWithoutEqualSingleDash() throws Exception {
}
- @Override @Test @Ignore("not supported by the GnuParser")
- public void testAmbiguousLongWithoutEqualSingleDash() throws Exception
- {
+ @Override
+ @Test
+ @Ignore("not supported by the GnuParser")
+ public void testAmbiguousLongWithoutEqualSingleDash() throws Exception {
}
- @Override @Test @Ignore("not supported by the GnuParser (CLI-184)")
- public void testNegativeOption() throws Exception
- {
+ @Override
+ @Test
+ @Ignore("not supported by the GnuParser (CLI-184)")
+ public void testNegativeOption() throws Exception {
}
- @Override @Test @Ignore("not supported by the GnuParser")
- public void testLongWithUnexpectedArgument1() throws Exception
- {
+ @Override
+ @Test
+ @Ignore("not supported by the GnuParser")
+ public void testLongWithUnexpectedArgument1() throws Exception {
}
- @Override @Test @Ignore("not supported by the GnuParser")
- public void testLongWithUnexpectedArgument2() throws Exception
- {
+ @Override
+ @Test
+ @Ignore("not supported by the GnuParser")
+ public void testLongWithUnexpectedArgument2() throws Exception {
}
- @Override @Test @Ignore("not supported by the GnuParser")
- public void testShortWithUnexpectedArgument() throws Exception
- {
+ @Override
+ @Test
+ @Ignore("not supported by the GnuParser")
+ public void testShortWithUnexpectedArgument() throws Exception {
}
- @Override @Test @Ignore("not supported by the GnuParser")
- public void testUnambiguousPartialLongOption1() throws Exception
- {
+ @Override
+ @Test
+ @Ignore("not supported by the GnuParser")
+ public void testUnambiguousPartialLongOption1() throws Exception {
}
- @Override @Test @Ignore("not supported by the GnuParser")
- public void testUnambiguousPartialLongOption2() throws Exception
- {
+ @Override
+ @Test
+ @Ignore("not supported by the GnuParser")
+ public void testUnambiguousPartialLongOption2() throws Exception {
}
- @Override @Test @Ignore("not supported by the GnuParser")
- public void testUnambiguousPartialLongOption3() throws Exception
- {
+ @Override
+ @Test
+ @Ignore("not supported by the GnuParser")
+ public void testUnambiguousPartialLongOption3() throws Exception {
}
- @Override @Test @Ignore("not supported by the GnuParser")
- public void testUnambiguousPartialLongOption4() throws Exception
- {
+ @Override
+ @Test
+ @Ignore("not supported by the GnuParser")
+ public void testUnambiguousPartialLongOption4() throws Exception {
}
- @Override @Test @Ignore("not supported by the GnuParser")
- public void testAmbiguousPartialLongOption1() throws Exception
- {
+ @Override
+ @Test
+ @Ignore("not supported by the GnuParser")
+ public void testAmbiguousPartialLongOption1() throws Exception {
}
- @Override @Test @Ignore("not supported by the GnuParser")
- public void testAmbiguousPartialLongOption2() throws Exception
- {
+ @Override
+ @Test
+ @Ignore("not supported by the GnuParser")
+ public void testAmbiguousPartialLongOption2() throws Exception {
}
- @Override @Test @Ignore("not supported by the GnuParser")
- public void testAmbiguousPartialLongOption3() throws Exception
- {
+ @Override
+ @Test
+ @Ignore("not supported by the GnuParser")
+ public void testAmbiguousPartialLongOption3() throws Exception {
}
- @Override @Test @Ignore("not supported by the GnuParser")
- public void testAmbiguousPartialLongOption4() throws Exception
- {
+ @Override
+ @Test
+ @Ignore("not supported by the GnuParser")
+ public void testAmbiguousPartialLongOption4() throws Exception {
}
- @Override @Test @Ignore("not supported by the GnuParser")
- public void testPartialLongOptionSingleDash() throws Exception
- {
+ @Override
+ @Test
+ @Ignore("not supported by the GnuParser")
+ public void testPartialLongOptionSingleDash() throws Exception {
}
- @Override @Test @Ignore("not supported by the GnuParser")
- public void testBursting() throws Exception
- {
+ @Override
+ @Test
+ @Ignore("not supported by the GnuParser")
+ public void testBursting() throws Exception {
}
- @Override @Test @Ignore("not supported by the GnuParser")
- public void testUnrecognizedOptionWithBursting() throws Exception
- {
+ @Override
+ @Test
+ @Ignore("not supported by the GnuParser")
+ public void testUnrecognizedOptionWithBursting() throws Exception {
}
- @Override @Test @Ignore("not supported by the GnuParser")
- public void testMissingArgWithBursting() throws Exception
- {
+ @Override
+ @Test
+ @Ignore("not supported by the GnuParser")
+ public void testMissingArgWithBursting() throws Exception {
}
- @Override @Test @Ignore("not supported by the GnuParser")
- public void testStopBursting() throws Exception
- {
+ @Override
+ @Test
+ @Ignore("not supported by the GnuParser")
+ public void testStopBursting() throws Exception {
}
- @Override @Test @Ignore("not supported by the GnuParser")
- public void testStopBursting2() throws Exception
- {
+ @Override
+ @Test
+ @Ignore("not supported by the GnuParser")
+ public void testStopBursting2() 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 b98b664..e3c83cc 100644
--- a/src/test/java/org/apache/commons/cli/HelpFormatterTest.java
+++ b/src/test/java/org/apache/commons/cli/HelpFormatterTest.java
@@ -30,13 +30,11 @@ import org.junit.Test;
/**
* Test case for the HelpFormatter class.
*/
-public class HelpFormatterTest
-{
+public class HelpFormatterTest {
private static final String EOL = System.getProperty("line.separator");
@Test
- public void testFindWrapPos() throws Exception
- {
+ public void testFindWrapPos() throws Exception {
final HelpFormatter hf = new HelpFormatter();
String text = "This is a test.";
@@ -63,13 +61,11 @@ public class HelpFormatterTest
}
@Test
- public void testRenderWrappedTextWordCut()
- {
+ public void testRenderWrappedTextWordCut() {
final int width = 7;
final int padding = 0;
final String text = "Thisisatest.";
- final String expected = "Thisisa" + EOL +
- "test.";
+ final String expected = "Thisisa" + EOL + "test.";
final StringBuffer sb = new StringBuffer();
new HelpFormatter().renderWrappedText(sb, width, padding, text);
@@ -77,14 +73,12 @@ public class HelpFormatterTest
}
@Test
- public void testRenderWrappedTextSingleLine()
- {
+ 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 String expected = "This is a" + EOL + "test.";
final StringBuffer sb = new StringBuffer();
new HelpFormatter().renderWrappedText(sb, width, padding, text);
@@ -92,14 +86,12 @@ public class HelpFormatterTest
}
@Test
- public void testRenderWrappedTextSingleLinePadded()
- {
+ 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 String expected = "This is a" + EOL + " test.";
final StringBuffer sb = new StringBuffer();
new HelpFormatter().renderWrappedText(sb, width, padding, text);
@@ -107,16 +99,17 @@ public class HelpFormatterTest
}
@Test
- public void testRenderWrappedTextSingleLinePadded2()
- {
+ 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]]";
+ "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]]";
+ " 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);
@@ -124,14 +117,15 @@ public class HelpFormatterTest
}
@Test
- public void testRenderWrappedTextMultiLine()
- {
+ public void testRenderWrappedTextMultiLine() {
// multi line text
final int width = 16;
final int padding = 0;
+ //@formatter:off
final String expected = "aaaa aaaa aaaa" + EOL +
- "aaaaaa" + EOL +
- "aaaaa";
+ "aaaaaa" + EOL +
+ "aaaaa";
+ //@formatter:on
final StringBuffer sb = new StringBuffer();
new HelpFormatter().renderWrappedText(sb, width, padding, expected);
@@ -139,17 +133,18 @@ public class HelpFormatterTest
}
@Test
- public void testRenderWrappedTextMultiLinePadded()
- {
+ public void testRenderWrappedTextMultiLinePadded() {
// multi-line padded text
final int width = 16;
final int padding = 4;
+ //@formatter:off
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);
@@ -157,8 +152,7 @@ public class HelpFormatterTest
}
@Test
- public void testPrintOptions() throws Exception
- {
+ public void testPrintOptions() throws Exception {
final StringBuffer sb = new StringBuffer();
final HelpFormatter hf = new HelpFormatter();
final int leftPad = 1;
@@ -174,13 +168,11 @@ public class HelpFormatterTest
assertEquals("simple non-wrapped option", expected, sb.toString());
int nextLineTabStop = leftPad + descPad + "-a".length();
- expected = lpad + "-a" + dpad + "aaaa aaaa aaaa" + EOL +
- hf.createPadding(nextLineTabStop) + "aaaa aaaa";
+ 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());
-
options = new Options().addOption("a", "aaa", false, "dddd dddd dddd dddd");
expected = lpad + "-a,--aaa" + dpad + "dddd dddd dddd dddd";
sb.setLength(0);
@@ -188,52 +180,39 @@ public class HelpFormatterTest
assertEquals("long non-wrapped option", expected, sb.toString());
nextLineTabStop = leftPad + descPad + "-a,--aaa".length();
- expected = lpad + "-a,--aaa" + dpad + "dddd dddd" + EOL +
- hf.createPadding(nextLineTabStop) + "dddd dddd";
+ 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";
+ 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
- public void testPrintHelpWithEmptySyntax()
- {
+ public void testPrintHelpWithEmptySyntax() {
final HelpFormatter formatter = new HelpFormatter();
- try
- {
+ try {
formatter.printHelp(null, new Options());
fail("null command line syntax should be rejected");
- }
- catch (final IllegalArgumentException e)
- {
+ } catch (final IllegalArgumentException e) {
// expected
}
- try
- {
+ try {
formatter.printHelp("", new Options());
fail("empty command line syntax should be rejected");
- }
- catch (final IllegalArgumentException e)
- {
+ } catch (final IllegalArgumentException e) {
// expected
}
}
@Test
- public void testAutomaticUsage() throws Exception
- {
+ public void testAutomaticUsage() throws Exception {
final HelpFormatter hf = new HelpFormatter();
Options options;
String expected = "usage: app [-a]";
@@ -247,8 +226,7 @@ public class HelpFormatterTest
out.reset();
expected = "usage: app [-a] [-b]";
- options = new Options().addOption("a", false, "aaaa aaaa aaaa aaaa aaaa")
- .addOption("b", false, "bbb");
+ 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());
@@ -258,8 +236,7 @@ public class HelpFormatterTest
// This test ensures the options are properly sorted
// See https://issues.apache.org/jira/browse/CLI-131
@Test
- public void testPrintUsage()
- {
+ public void testPrintUsage() {
final Option optionA = new Option("a", "first");
final Option optionB = new Option("b", "second");
final Option optionC = new Option("c", "third");
@@ -277,19 +254,16 @@ public class HelpFormatterTest
// uses the test for CLI-131 to implement CLI-155
@Test
- public void testPrintSortedUsage()
- {
+ 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>()
- {
+ helpFormatter.setOptionComparator(new Comparator<Option>() {
@Override
- public int compare(final Option opt1, final Option opt2)
- {
+ public int compare(final Option opt1, final Option opt2) {
// reverses the functionality of the default comparator
return opt2.getKey().compareToIgnoreCase(opt1.getKey());
}
@@ -302,8 +276,7 @@ public class HelpFormatterTest
}
@Test
- public void testPrintSortedUsageWithNullComparator()
- {
+ public void testPrintSortedUsageWithNullComparator() {
final Options opts = new Options();
opts.addOption(new Option("c", "first"));
opts.addOption(new Option("b", "second"));
@@ -319,8 +292,7 @@ public class HelpFormatterTest
}
@Test
- public void testPrintOptionGroupUsage()
- {
+ public void testPrintOptionGroupUsage() {
final OptionGroup group = new OptionGroup();
group.addOption(Option.builder("a").build());
group.addOption(Option.builder("b").build());
@@ -338,8 +310,7 @@ public class HelpFormatterTest
}
@Test
- public void testPrintRequiredOptionGroupUsage()
- {
+ public void testPrintRequiredOptionGroupUsage() {
final OptionGroup group = new OptionGroup();
group.addOption(Option.builder("a").build());
group.addOption(Option.builder("b").build());
@@ -358,8 +329,7 @@ public class HelpFormatterTest
}
@Test
- public void testPrintOptionWithEmptyArgNameUsage()
- {
+ public void testPrintOptionWithEmptyArgNameUsage() {
final Option option = new Option("f", true, null);
option.setArgName("");
option.setRequired(true);
@@ -376,8 +346,7 @@ public class HelpFormatterTest
}
@Test
- public void testDefaultArgName()
- {
+ public void testDefaultArgName() {
final Option option = Option.builder("f").hasArg().required(true).build();
final Options options = new Options();
@@ -393,8 +362,7 @@ public class HelpFormatterTest
}
@Test
- public void testRtrim()
- {
+ public void testRtrim() {
final HelpFormatter formatter = new HelpFormatter();
assertEquals(null, formatter.rtrim(null));
@@ -403,8 +371,7 @@ public class HelpFormatterTest
}
@Test
- public void testAccessors()
- {
+ public void testAccessors() {
final HelpFormatter formatter = new HelpFormatter();
formatter.setArgName("argname");
@@ -433,8 +400,7 @@ public class HelpFormatterTest
}
@Test
- public void testHeaderStartingWithLineSeparator()
- {
+ public void testHeaderStartingWithLineSeparator() {
// related to Bugzilla #21215
final Options options = new Options();
final HelpFormatter formatter = new HelpFormatter();
@@ -442,18 +408,19 @@ public class HelpFormatterTest
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());
+ "Footer" + EOL,
+ out.toString());
+ //@formatter:on
}
@Test
- public void testIndentedHeaderAndFooter()
- {
+ public void testIndentedHeaderAndFooter() {
// related to CLI-207
final Options options = new Options();
final HelpFormatter formatter = new HelpFormatter();
@@ -461,20 +428,20 @@ public class HelpFormatterTest
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
assertEquals(
"usage: foobar" + EOL +
" Header1" + EOL +
" Header2" + EOL +
"" + EOL +
" Footer1" + EOL +
- " Footer2" + EOL
- , out.toString());
+ " Footer2" + EOL,
+ out.toString());
+ //@formatter:on
}
@Test
- public void testOptionWithoutShortFormat()
- {
+ public void testOptionWithoutShortFormat() {
// related to Bugzilla #19383 (CLI-67)
final Options options = new Options();
options.addOption(new Option("a", "aaa", false, "aaaaaaa"));
@@ -484,23 +451,25 @@ public class HelpFormatterTest
final HelpFormatter formatter = new HelpFormatter();
final StringWriter out = new StringWriter();
formatter.printHelp(new PrintWriter(out), 80, "foobar", "", options, 2, 2, "", true);
+ //@formatter:off
assertEquals(
"usage: foobar [-a] [--bbb] [-c]" + EOL +
" -a,--aaa aaaaaaa" + EOL +
" --bbb bbbbbbb" + EOL +
- " -c ccccccc" + EOL
- , out.toString());
+ " -c ccccccc" + EOL,
+ out.toString());
+ //@formatter:on
}
@Test
- public void testOptionWithoutShortFormat2()
- {
+ 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()
@@ -531,6 +500,7 @@ public class HelpFormatterTest
.valueSeparator()
.desc("Use the specified configuration file")
.build();
+ //@formatter:on
final Options mOptions = new Options();
mOptions.addOption(help);
@@ -544,31 +514,32 @@ public class HelpFormatterTest
mOptions.addOption(configFile);
final HelpFormatter formatter = new HelpFormatter();
- final String EOL = System.getProperty("line.separator");
+ 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.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());
+ "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
- public void testHelpWithLongOptSeparator() throws Exception
- {
+ public void testHelpWithLongOptSeparator() throws Exception {
final Options options = new Options();
- options.addOption( "f", true, "the file" );
+ 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());
@@ -581,6 +552,7 @@ public class HelpFormatterTest
formatter.printHelp(new PrintWriter(out), 80, "create", "header", options, 2, 2, "footer");
+ //@formatter:off
assertEquals(
"usage: create" + EOL +
"header" + EOL +
@@ -589,13 +561,13 @@ public class HelpFormatterTest
" -s,--size=<SIZE> the size" + EOL +
"footer" + EOL,
out.toString());
+ //@formatter:on
}
@Test
- public void testUsageWithLongOptSeparator() throws Exception
- {
+ public void testUsageWithLongOptSeparator() throws Exception {
final Options options = new Options();
- options.addOption( "f", true, "the file" );
+ 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());
diff --git a/src/test/java/org/apache/commons/cli/OptionBuilderTest.java b/src/test/java/org/apache/commons/cli/OptionBuilderTest.java
index b413b49..fe8ffae 100644
--- a/src/test/java/org/apache/commons/cli/OptionBuilderTest.java
+++ b/src/test/java/org/apache/commons/cli/OptionBuilderTest.java
@@ -25,82 +25,84 @@ import static org.junit.Assert.fail;
import org.junit.Test;
@SuppressWarnings("deprecation") // OptionBuilder is marked deprecated
-public class OptionBuilderTest
-{
+public class OptionBuilderTest {
@Test
- public void testCompleteOption( ) {
- final Option simple = OptionBuilder.withLongOpt( "simple option")
- .hasArg( )
- .isRequired( )
- .hasArgs( )
- .withType( Float.class )
- .withDescription( "this is a simple option" )
- .create( 's' );
-
- 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() );
+ 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( ) {
- Option simple = OptionBuilder.withLongOpt( "simple option")
- .hasArg( )
- .isRequired( )
- .hasArgs( )
- .withType( Float.class )
- .withDescription( "this is a simple option" )
- .create( 's' );
-
- 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() );
-
- simple = OptionBuilder.withLongOpt( "dimple option")
- .hasArg( )
- .withDescription( "this is a dimple option" )
- .create( 'd' );
-
- 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() );
+ 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' );
+ final Option base = OptionBuilder.withDescription("option description").create('o');
- assertEquals( "o", base.getOpt() );
- assertEquals( "option description", base.getDescription() );
- assertTrue( !base.hasArg() );
+ assertEquals("o", base.getOpt());
+ assertEquals("option description", base.getDescription());
+ assertTrue(!base.hasArg());
}
@Test
public void testBaseOptionStringOpt() {
- final Option base = OptionBuilder.withDescription( "option description")
- .create( "o" );
+ final Option base = OptionBuilder.withDescription("option description").create("o");
- assertEquals( "o", base.getOpt() );
- assertEquals( "option description", base.getDescription() );
- assertTrue( !base.hasArg() );
+ assertEquals("o", base.getOpt());
+ assertEquals("option description", base.getDescription());
+ assertTrue(!base.hasArg());
}
@Test
- public void testSpecialOptChars() throws Exception
- {
+ public void testSpecialOptChars() throws Exception {
// '?'
final Option opt1 = OptionBuilder.withDescription("help options").create('?');
assertEquals("?", opt1.getOpt());
@@ -112,87 +114,76 @@ public class OptionBuilderTest
// ' '
try {
OptionBuilder.create(' ');
- fail( "IllegalArgumentException not caught" );
+ fail("IllegalArgumentException not caught");
} catch (final IllegalArgumentException e) {
// success
}
}
@Test
- public void testOptionArgNumbers()
- {
- final Option opt = OptionBuilder.withDescription( "option description" )
- .hasArgs( 2 )
- .create( 'o' );
- assertEquals( 2, opt.getArgs() );
+ 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 testIllegalOptions() {
// bad single character option
try {
- OptionBuilder.withDescription( "option description" ).create( '"' );
- fail( "IllegalArgumentException not caught" );
- }
- catch( final IllegalArgumentException exp ) {
+ OptionBuilder.withDescription("option description").create('"');
+ fail("IllegalArgumentException not caught");
+ } catch (final IllegalArgumentException exp) {
// success
}
// bad character in option string
try {
- OptionBuilder.create( "opt`" );
- fail( "IllegalArgumentException not caught" );
- }
- catch( final IllegalArgumentException exp ) {
+ OptionBuilder.create("opt`");
+ fail("IllegalArgumentException not caught");
+ } catch (final IllegalArgumentException exp) {
// success
}
// valid option
try {
- OptionBuilder.create( "opt" );
+ OptionBuilder.create("opt");
// success
- }
- catch( final IllegalArgumentException exp ) {
- fail( "IllegalArgumentException caught" );
+ } catch (final IllegalArgumentException exp) {
+ fail("IllegalArgumentException caught");
}
}
@Test
public void testCreateIncompleteOption() {
- try
- {
+ try {
OptionBuilder.hasArg().create();
fail("Incomplete option should be rejected");
- }
- catch (final IllegalArgumentException e)
- {
+ } catch (final IllegalArgumentException e) {
// expected
// implicitly reset the builder
- OptionBuilder.create( "opt" );
+ OptionBuilder.create("opt");
}
}
@Test
public void testBuilderIsResettedAlways() {
- try
- {
+ try {
OptionBuilder.withDescription("JUnit").create('"');
fail("IllegalArgumentException expected");
- }
- catch (final IllegalArgumentException e)
- {
+ } catch (final IllegalArgumentException e) {
// expected
}
assertNull("we inherited a description", OptionBuilder.create('x').getDescription());
- try
- {
+ try {
OptionBuilder.withDescription("JUnit").create();
fail("IllegalArgumentException expected");
- }
- catch (final IllegalArgumentException e)
- {
+ } catch (final IllegalArgumentException e) {
// expected
}
assertNull("we inherited a description", OptionBuilder.create('x').getDescription());
diff --git a/src/test/java/org/apache/commons/cli/OptionGroupTest.java b/src/test/java/org/apache/commons/cli/OptionGroupTest.java
index a59e9d2..4444e82 100644
--- a/src/test/java/org/apache/commons/cli/OptionGroupTest.java
+++ b/src/test/java/org/apache/commons/cli/OptionGroupTest.java
@@ -28,141 +28,129 @@ import org.junit.Before;
import org.junit.Test;
@SuppressWarnings("deprecation") // tests some deprecated classes
-public class OptionGroupTest
-{
- private Options _options = null;
+public class OptionGroupTest {
+ private Options options;
private final Parser parser = new PosixParser();
@Before
- public void setUp()
- {
- final Option file = new Option( "f", "file", false, "file to process" );
- final Option dir = new Option( "d", "directory", false, "directory to process" );
+ public void setUp() {
+ final Option file = new Option("f", "file", false, "file to process");
+ final Option dir = new Option("d", "directory", false, "directory to process");
final OptionGroup group = new OptionGroup();
- group.addOption( file );
- group.addOption( dir );
- _options = new Options().addOptionGroup( group );
+ group.addOption(file);
+ group.addOption(dir);
+ options = new Options().addOptionGroup(group);
- final Option section = new Option( "s", "section", false, "section to process" );
- final Option chapter = new Option( "c", "chapter", false, "chapter to process" );
+ final Option section = new Option("s", "section", false, "section to process");
+ final Option chapter = new Option("c", "chapter", false, "chapter to process");
final OptionGroup group2 = new OptionGroup();
- group2.addOption( section );
- group2.addOption( chapter );
+ group2.addOption(section);
+ group2.addOption(chapter);
- _options.addOptionGroup( group2 );
+ options.addOptionGroup(group2);
- final Option importOpt = new Option( null, "import", false, "section to process" );
- final Option exportOpt = new Option( null, "export", false, "chapter to process" );
+ final Option importOpt = new Option(null, "import", false, "section to process");
+ final Option exportOpt = new Option(null, "export", false, "chapter to process");
final OptionGroup group3 = new OptionGroup();
- group3.addOption( importOpt );
- group3.addOption( exportOpt );
- _options.addOptionGroup( group3 );
+ group3.addOption(importOpt);
+ group3.addOption(exportOpt);
+ options.addOptionGroup(group3);
- _options.addOption( "r", "revision", false, "revision number" );
+ options.addOption("r", "revision", false, "revision number");
}
@Test
- public void testSingleOptionFromGroup() throws Exception
- {
- final String[] args = new String[] { "-f" };
-
- final CommandLine cl = parser.parse( _options, args);
-
- 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());
+ 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 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 testSingleOption() throws Exception
- {
- final String[] args = new String[] { "-r" };
-
- final CommandLine cl = parser.parse( _options, args);
-
- assertTrue( "Confirm -r is 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());
+ 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 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 = new String[] { "-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());
+ 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());
}
@Test
- public void testSingleLongOption() throws Exception
- {
- final String[] args = new String[] { "--file" };
-
- final CommandLine cl = parser.parse( _options, args);
-
- 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());
+ public void testSingleLongOption() throws Exception {
+ final String[] args = {"--file"};
+
+ final CommandLine cl = parser.parse(options, args);
+
+ 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());
}
@Test
- public void testTwoValidLongOptions() throws Exception
- {
- final String[] args = new String[] { "--revision", "--file" };
-
- 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());
+ public void testTwoValidLongOptions() throws Exception {
+ final String[] args = {"--revision", "--file"};
+
+ 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 testNoOptionsExtraArgs() throws Exception
- {
- final String[] args = new String[] { "arg1", "arg2" };
-
- 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 -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);
+ public void testNoOptionsExtraArgs() throws Exception {
+ final String[] args = {"arg1", "arg2"};
+
+ 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 -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);
}
@Test
- public void testTwoOptionsFromGroup() throws Exception
- {
- final String[] args = new String[] { "-f", "-d" };
-
- try
- {
- parser.parse( _options, args);
- fail( "two arguments from group not allowed" );
- }
- catch (final AlreadySelectedException e)
- {
+ 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());
@@ -170,17 +158,13 @@ public class OptionGroupTest
}
@Test
- public void testTwoLongOptionsFromGroup() throws Exception
- {
- final String[] args = new String[] { "--file", "--directory" };
-
- try
- {
- parser.parse(_options, args);
- fail( "two arguments from group not allowed" );
- }
- catch (final AlreadySelectedException e)
- {
+ public void testTwoLongOptionsFromGroup() throws Exception {
+ final String[] args = {"--file", "--directory"};
+
+ 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());
@@ -188,45 +172,41 @@ public class OptionGroupTest
}
@Test
- public void testTwoOptionsFromDifferentGroup() throws Exception
- {
- final String[] args = new String[] { "-f", "-s" };
-
- final CommandLine cl = parser.parse( _options, args);
- 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 set", cl.hasOption("s") );
- assertTrue( "Confirm -c is NOT set", !cl.hasOption("c") );
- assertTrue( "Confirm NO extra args", cl.getArgList().isEmpty());
+ public void testTwoOptionsFromDifferentGroup() throws Exception {
+ final String[] args = {"-f", "-s"};
+
+ final CommandLine cl = parser.parse(options, args);
+ 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 set", cl.hasOption("s"));
+ assertTrue("Confirm -c is NOT set", !cl.hasOption("c"));
+ assertTrue("Confirm NO extra args", cl.getArgList().isEmpty());
}
@Test
- public void testTwoOptionsFromGroupWithProperties() throws Exception
- {
- final String[] args = new String[] { "-f" };
+ public void testTwoOptionsFromGroupWithProperties() throws Exception {
+ final String[] args = {"-f"};
final Properties properties = new Properties();
properties.put("d", "true");
- final CommandLine cl = parser.parse( _options, args, properties);
+ final CommandLine cl = parser.parse(options, args, properties);
assertTrue(cl.hasOption("f"));
assertTrue(!cl.hasOption("d"));
}
@Test
- public void testValidLongOnlyOptions() throws Exception
- {
- final CommandLine cl1 = parser.parse(_options, new String[]{"--export"});
+ public void testValidLongOnlyOptions() throws Exception {
+ final CommandLine cl1 = parser.parse(options, new String[] {"--export"});
assertTrue("Confirm --export is set", cl1.hasOption("export"));
- final CommandLine cl2 = parser.parse(_options, new String[]{"--import"});
+ final CommandLine cl2 = parser.parse(options, new String[] {"--import"});
assertTrue("Confirm --import is set", cl2.hasOption("import"));
}
@Test
- public void testToString()
- {
+ public void testToString() {
final OptionGroup group1 = new OptionGroup();
group1.addOption(new Option(null, "foo", false, "Foo"));
group1.addOption(new Option(null, "bar", false, "Bar"));
@@ -245,8 +225,7 @@ public class OptionGroupTest
}
@Test
- public void testGetNames()
- {
+ public void testGetNames() {
final OptionGroup group = new OptionGroup();
group.addOption(OptionBuilder.create('a'));
group.addOption(OptionBuilder.create('b'));
diff --git a/src/test/java/org/apache/commons/cli/OptionTest.java b/src/test/java/org/apache/commons/cli/OptionTest.java
index 324048b..e04fd18 100644
--- a/src/test/java/org/apache/commons/cli/OptionTest.java
+++ b/src/test/java/org/apache/commons/cli/OptionTest.java
@@ -25,28 +25,23 @@ import static org.junit.Assert.assertTrue;
import org.junit.Test;
-public class OptionTest
-{
- private static class TestOption extends Option
- {
+public class OptionTest {
+ private static class TestOption extends Option {
private static final long serialVersionUID = 1L;
- public TestOption(final String opt, final boolean hasArg, final String description) throws IllegalArgumentException
- {
+ TestOption(final String opt, final boolean hasArg, final String description) throws IllegalArgumentException {
super(opt, hasArg, description);
}
@Override
- public boolean addValue(final String value)
- {
+ public boolean addValue(final String value) {
addValueForProcessing(value);
return true;
}
}
@Test
- public void testClear()
- {
+ public void testClear() {
final TestOption option = new TestOption("x", true, "");
assertEquals(0, option.getValuesList().size());
option.addValue("a");
@@ -57,8 +52,7 @@ public class OptionTest
// See https://issues.apache.org/jira/browse/CLI-21
@Test
- public void testClone()
- {
+ public void testClone() {
final TestOption a = new TestOption("a", true, "");
final TestOption b = (TestOption) a.clone();
assertEquals(a, b);
@@ -75,33 +69,29 @@ 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()) ;
+ 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 class DefaultOption extends Option {
private static final long serialVersionUID = 1L;
private final String defaultValue;
- public DefaultOption(final String opt, final String description, final String defaultValue) throws IllegalArgumentException
- {
+ DefaultOption(final String opt, final String description, final String defaultValue) throws IllegalArgumentException {
super(opt, true, description);
this.defaultValue = defaultValue;
}
@Override
- public String getValue()
- {
+ public String getValue() {
return super.getValue() != null ? super.getValue() : defaultValue;
}
}
@Test
- public void testSubclass()
- {
+ public void testSubclass() {
final Option option = new DefaultOption("f", "file", "myfile.txt");
final Option clone = (Option) option.clone();
assertEquals("myfile.txt", clone.getValue());
@@ -109,8 +99,7 @@ public class OptionTest
}
@Test
- public void testHasArgName()
- {
+ public void testHasArgName() {
final Option option = new Option("f", null);
option.setArgName(null);
@@ -124,8 +113,7 @@ public class OptionTest
}
@Test
- public void testHasArgs()
- {
+ public void testHasArgs() {
final Option option = new Option("f", null);
option.setArgs(0);
@@ -145,8 +133,7 @@ public class OptionTest
}
@Test
- public void testGetValue()
- {
+ public void testGetValue() {
final Option option = new Option("f", null);
option.setArgs(Option.UNLIMITED_VALUES);
@@ -161,57 +148,47 @@ public class OptionTest
}
@Test
- public void testBuilderMethods()
- {
+ 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);
+ 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()
- {
+ @Test(expected = IllegalArgumentException.class)
+ public void testBuilderInsufficientParams1() {
Option.builder().desc("desc").build();
}
- @Test(expected=IllegalArgumentException.class)
- public void testBuilderInsufficientParams2()
- {
+ @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)
- {
+ 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());
@@ -221,7 +198,7 @@ public class OptionTest
assertEquals(optionalArg, option.hasOptionalArg());
assertEquals(valueSeparator, option.getValueSeparator());
- assertEquals(cls, option.getType());
+ assertEquals(cls, option.getType());
}
}
diff --git a/src/test/java/org/apache/commons/cli/OptionsTest.java b/src/test/java/org/apache/commons/cli/OptionsTest.java
index fae74c7..9082ef0 100644
--- a/src/test/java/org/apache/commons/cli/OptionsTest.java
+++ b/src/test/java/org/apache/commons/cli/OptionsTest.java
@@ -28,11 +28,9 @@ import java.util.Collection;
import org.junit.Test;
@SuppressWarnings("deprecation") // tests some deprecated classes
-public class OptionsTest
-{
+public class OptionsTest {
@Test
- public void testSimple()
- {
+ public void testSimple() {
final Options opts = new Options();
opts.addOption("a", false, "toggle -a");
@@ -43,8 +41,7 @@ public class OptionsTest
}
@Test
- public void testDuplicateSimple()
- {
+ public void testDuplicateSimple() {
final Options opts = new Options();
opts.addOption("a", false, "toggle -a");
opts.addOption("a", true, "toggle -a*");
@@ -53,8 +50,7 @@ public class OptionsTest
}
@Test
- public void testLong()
- {
+ public void testLong() {
final Options opts = new Options();
opts.addOption("a", "--a", false, "toggle -a");
@@ -65,8 +61,7 @@ public class OptionsTest
}
@Test
- public void testDuplicateLong()
- {
+ public void testDuplicateLong() {
final Options opts = new Options();
opts.addOption("a", "--a", false, "toggle -a");
opts.addOption("a", "--a", false, "toggle -a*");
@@ -74,8 +69,7 @@ public class OptionsTest
}
@Test
- public void testHelpOptions()
- {
+ public void testHelpOptions() {
final Option longOnly1 = OptionBuilder.withLongOpt("long-only1").create();
final Option longOnly2 = OptionBuilder.withLongOpt("long-only2").create();
final Option shortOnly1 = OptionBuilder.create("1");
@@ -106,41 +100,32 @@ public class OptionsTest
}
@Test
- public void testMissingOptionException() throws ParseException
- {
+ public void testMissingOptionException() throws ParseException {
final Options options = new Options();
options.addOption(OptionBuilder.isRequired().create("f"));
- try
- {
+ try {
new PosixParser().parse(options, new String[0]);
fail("Expected MissingOptionException to be thrown");
- }
- catch (final MissingOptionException e)
- {
+ } catch (final MissingOptionException e) {
assertEquals("Missing required option: f", e.getMessage());
}
}
@Test
- public void testMissingOptionsException() throws ParseException
- {
+ public void testMissingOptionsException() throws ParseException {
final Options options = new Options();
options.addOption(OptionBuilder.isRequired().create("f"));
options.addOption(OptionBuilder.isRequired().create("x"));
- try
- {
+ try {
new PosixParser().parse(options, new String[0]);
fail("Expected MissingOptionException to be thrown");
- }
- catch (final MissingOptionException e)
- {
+ } catch (final MissingOptionException e) {
assertEquals("Missing required options: f, x", e.getMessage());
}
}
@Test
- public void testToString()
- {
+ public void testToString() {
final Options options = new Options();
options.addOption("f", "foo", true, "Foo");
options.addOption("b", "bar", false, "Bar");
@@ -152,8 +137,7 @@ public class OptionsTest
}
@Test
- public void testGetOptionsGroups()
- {
+ public void testGetOptionsGroups() {
final Options options = new Options();
final OptionGroup group1 = new OptionGroup();
@@ -172,8 +156,7 @@ public class OptionsTest
}
@Test
- public void testGetMatchingOpts()
- {
+ public void testGetMatchingOpts() {
final Options options = new Options();
options.addOption(OptionBuilder.withLongOpt("version").create());
options.addOption(OptionBuilder.withLongOpt("verbose").create());
diff --git a/src/test/java/org/apache/commons/cli/ParserTestCase.java b/src/test/java/org/apache/commons/cli/ParserTestCase.java
index 307c94b..c404c9e 100644
--- a/src/test/java/org/apache/commons/cli/ParserTestCase.java
+++ b/src/test/java/org/apache/commons/cli/ParserTestCase.java
@@ -33,27 +33,24 @@ import org.junit.Test;
/**
* Abstract test case testing common parser features.
*/
-public abstract class ParserTestCase
-{
+public abstract class ParserTestCase {
protected CommandLineParser parser;
protected Options options;
@Before
- public void setUp()
- {
+ public void setUp() {
+ //@formatter:off
options = new Options()
.addOption("a", "enable-a", false, "turn [a] on or off")
.addOption("b", "bfile", true, "set the value of [b]")
.addOption("c", "copt", false, "turn [c] on or off");
+ //@formatter:on
}
@Test
- public void testSimpleShort() throws Exception
- {
- final String[] args = new String[] { "-a",
- "-b", "toast",
- "foo", "bar" };
+ public void testSimpleShort() throws Exception {
+ final String[] args = {"-a", "-b", "toast", "foo", "bar"};
final CommandLine cl = parser.parse(options, args);
@@ -64,27 +61,21 @@ public abstract class ParserTestCase
}
@Test
- public void testSimpleLong() throws Exception
- {
- final String[] args = new String[] { "--enable-a",
- "--bfile", "toast",
- "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);
+ 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 testMultiple() throws Exception
- {
- final String[] args = new String[] { "-c",
- "foobar",
- "-b", "toast" };
+ public void testMultiple() throws Exception {
+ final String[] args = {"-c", "foobar", "-b", "toast"};
CommandLine cl = parser.parse(options, args, true);
assertTrue("Confirm -c is set", cl.hasOption("c"));
@@ -100,11 +91,8 @@ public abstract class ParserTestCase
}
@Test
- public void testMultipleWithLong() throws Exception
- {
- final String[] args = new String[] { "--copt",
- "foobar",
- "--bfile", "toast" };
+ public void testMultipleWithLong() throws Exception {
+ final String[] args = {"--copt", "foobar", "--bfile", "toast"};
CommandLine cl = parser.parse(options, args, true);
assertTrue("Confirm -c is set", cl.hasOption("c"));
@@ -120,47 +108,36 @@ public abstract class ParserTestCase
}
@Test
- public void testUnrecognizedOption() throws Exception
- {
- final String[] args = new String[] { "-a", "-d", "-b", "toast", "foo", "bar" };
+ public void testUnrecognizedOption() throws Exception {
+ final String[] args = {"-a", "-d", "-b", "toast", "foo", "bar"};
- try
- {
+ try {
parser.parse(options, args);
fail("UnrecognizedOptionException wasn't thrown");
- }
- catch (final UnrecognizedOptionException e)
- {
+ } catch (final UnrecognizedOptionException e) {
assertEquals("-d", e.getOption());
}
}
@Test
- public void testMissingArg() throws Exception
- {
- final String[] args = new String[] { "-b" };
+ public void testMissingArg() throws Exception {
+ final String[] args = {"-b"};
boolean caught = false;
- try
- {
+ try {
parser.parse(options, args);
- }
- catch (final MissingArgumentException e)
- {
+ } catch (final MissingArgumentException e) {
caught = true;
assertEquals("option missing an argument", "b", e.getOption().getOpt());
}
- assertTrue( "Confirm MissingArgumentException caught", caught );
+ assertTrue("Confirm MissingArgumentException caught", caught);
}
@Test
- public void testDoubleDash1() throws Exception
- {
- final String[] args = new String[] { "--copt",
- "--",
- "-b", "toast" };
+ public void testDoubleDash1() throws Exception {
+ final String[] args = {"--copt", "--", "-b", "toast"};
final CommandLine cl = parser.parse(options, args);
@@ -170,31 +147,23 @@ public abstract class ParserTestCase
}
@Test
- public void testDoubleDash2() throws Exception
- {
+ public void testDoubleDash2() throws Exception {
final Options options = new Options();
options.addOption(OptionBuilder.hasArg().create('n'));
options.addOption(OptionBuilder.create('m'));
- try
- {
- parser.parse(options, new String[]{"-n", "--", "-m"});
+ try {
+ parser.parse(options, new String[] {"-n", "--", "-m"});
fail("MissingArgumentException not thrown for option -n");
- }
- catch (final MissingArgumentException e)
- {
+ } catch (final MissingArgumentException e) {
assertNotNull("option null", e.getOption());
assertEquals("n", e.getOption().getOpt());
}
}
@Test
- public void testSingleDash() throws Exception
- {
- final String[] args = new String[] { "--copt",
- "-b", "-",
- "-a",
- "-" };
+ public void testSingleDash() throws Exception {
+ final String[] args = {"--copt", "-b", "-", "-a", "-"};
final CommandLine cl = parser.parse(options, args);
@@ -206,12 +175,8 @@ public abstract class ParserTestCase
}
@Test
- public void testStopAtUnexpectedArg() throws Exception
- {
- final String[] args = new String[] { "-c",
- "foober",
- "-b",
- "toast" };
+ 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"));
@@ -219,9 +184,8 @@ public abstract class ParserTestCase
}
@Test
- public void testStopAtExpectedArg() throws Exception
- {
- final String[] args = new String[]{"-b", "foo"};
+ public void testStopAtExpectedArg() throws Exception {
+ final String[] args = {"-b", "foo"};
final CommandLine cl = parser.parse(options, args, true);
@@ -231,11 +195,8 @@ public abstract class ParserTestCase
}
@Test
- public void testStopAtNonOptionShort() throws Exception
- {
- final String[] args = new String[]{"-z",
- "-a",
- "-btoast"};
+ 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"));
@@ -243,11 +204,8 @@ public abstract class ParserTestCase
}
@Test
- public void testStopAtNonOptionLong() throws Exception
- {
- final String[] args = new String[]{"--zop==1",
- "-abtoast",
- "--b=bar"};
+ public void testStopAtNonOptionLong() throws Exception {
+ final String[] args = {"--zop==1", "-abtoast", "--b=bar"};
final CommandLine cl = parser.parse(options, args, true);
@@ -257,18 +215,16 @@ public abstract class ParserTestCase
}
@Test
- public void testNegativeArgument() throws Exception
- {
- final String[] args = new String[] { "-b", "-1"} ;
+ 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 = new String[] { "-b", "-1"} ;
+ public void testNegativeOption() throws Exception {
+ final String[] args = {"-b", "-1"};
options.addOption("1", false, null);
@@ -277,18 +233,16 @@ public abstract class ParserTestCase
}
@Test
- public void testArgumentStartingWithHyphen() throws Exception
- {
- final String[] args = new String[]{"-b", "-foo"};
+ 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 testShortWithEqual() throws Exception
- {
- final String[] args = new String[] { "-f=bar" };
+ public void testShortWithEqual() throws Exception {
+ final String[] args = {"-f=bar"};
final Options options = new Options();
options.addOption(OptionBuilder.withLongOpt("foo").hasArg().create('f'));
@@ -299,9 +253,8 @@ public abstract class ParserTestCase
}
@Test
- public void testShortWithoutEqual() throws Exception
- {
- final String[] args = new String[] { "-fbar" };
+ public void testShortWithoutEqual() throws Exception {
+ final String[] args = {"-fbar"};
final Options options = new Options();
options.addOption(OptionBuilder.withLongOpt("foo").hasArg().create('f'));
@@ -312,9 +265,8 @@ public abstract class ParserTestCase
}
@Test
- public void testLongWithEqualDoubleDash() throws Exception
- {
- final String[] args = new String[] { "--foo=bar" };
+ public void testLongWithEqualDoubleDash() throws Exception {
+ final String[] args = {"--foo=bar"};
final Options options = new Options();
options.addOption(OptionBuilder.withLongOpt("foo").hasArg().create('f'));
@@ -325,9 +277,8 @@ public abstract class ParserTestCase
}
@Test
- public void testLongWithEqualSingleDash() throws Exception
- {
- final String[] args = new String[] { "-foo=bar" };
+ public void testLongWithEqualSingleDash() throws Exception {
+ final String[] args = {"-foo=bar"};
final Options options = new Options();
options.addOption(OptionBuilder.withLongOpt("foo").hasArg().create('f'));
@@ -338,9 +289,8 @@ public abstract class ParserTestCase
}
@Test
- public void testLongWithoutEqualSingleDash() throws Exception
- {
- final String[] args = new String[] { "-foobar" };
+ public void testLongWithoutEqualSingleDash() throws Exception {
+ final String[] args = {"-foobar"};
final Options options = new Options();
options.addOption(OptionBuilder.withLongOpt("foo").hasArg().create('f'));
@@ -351,9 +301,8 @@ public abstract class ParserTestCase
}
@Test
- public void testAmbiguousLongWithoutEqualSingleDash() throws Exception
- {
- final String[] args = new String[] { "-b", "-foobar" };
+ public void testAmbiguousLongWithoutEqualSingleDash() throws Exception {
+ final String[] args = {"-b", "-foobar"};
final Options options = new Options();
options.addOption(OptionBuilder.withLongOpt("foo").hasOptionalArg().create('f'));
@@ -367,9 +316,8 @@ public abstract class ParserTestCase
}
@Test
- public void testLongWithoutEqualDoubleDash() throws Exception
- {
- final String[] args = new String[] { "--foobar" };
+ public void testLongWithoutEqualDoubleDash() throws Exception {
+ final String[] args = {"--foobar"};
final Options options = new Options();
options.addOption(OptionBuilder.withLongOpt("foo").hasArg().create('f'));
@@ -380,19 +328,15 @@ public abstract class ParserTestCase
}
@Test
- public void testLongWithUnexpectedArgument1() throws Exception
- {
- final String[] args = new String[] { "--foo=bar" };
+ public void testLongWithUnexpectedArgument1() throws Exception {
+ final String[] args = {"--foo=bar"};
final Options options = new Options();
options.addOption(OptionBuilder.withLongOpt("foo").create('f'));
- try
- {
+ try {
parser.parse(options, args);
- }
- catch (final UnrecognizedOptionException e)
- {
+ } catch (final UnrecognizedOptionException e) {
assertEquals("--foo=bar", e.getOption());
return;
}
@@ -401,19 +345,15 @@ public abstract class ParserTestCase
}
@Test
- public void testLongWithUnexpectedArgument2() throws Exception
- {
- final String[] args = new String[] { "-foobar" };
+ public void testLongWithUnexpectedArgument2() throws Exception {
+ final String[] args = {"-foobar"};
final Options options = new Options();
options.addOption(OptionBuilder.withLongOpt("foo").create('f'));
- try
- {
+ try {
parser.parse(options, args);
- }
- catch (final UnrecognizedOptionException e)
- {
+ } catch (final UnrecognizedOptionException e) {
assertEquals("-foobar", e.getOption());
return;
}
@@ -422,19 +362,15 @@ public abstract class ParserTestCase
}
@Test
- public void testShortWithUnexpectedArgument() throws Exception
- {
- final String[] args = new String[] { "-f=bar" };
+ public void testShortWithUnexpectedArgument() throws Exception {
+ final String[] args = {"-f=bar"};
final Options options = new Options();
options.addOption(OptionBuilder.withLongOpt("foo").create('f'));
- try
- {
+ try {
parser.parse(options, args);
- }
- catch (final UnrecognizedOptionException e)
- {
+ } catch (final UnrecognizedOptionException e) {
assertEquals("-f=bar", e.getOption());
return;
}
@@ -443,9 +379,8 @@ public abstract class ParserTestCase
}
@Test
- public void testPropertiesOption1() throws Exception
- {
- final String[] args = new String[] { "-Jsource=1.5", "-J", "target", "1.5", "foo" };
+ 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'));
@@ -466,9 +401,8 @@ public abstract class ParserTestCase
}
@Test
- public void testPropertiesOption2() throws Exception
- {
- final String[] args = new String[] { "-Dparam1", "-Dparam2=value2", "-D"};
+ 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'));
@@ -486,9 +420,8 @@ public abstract class ParserTestCase
}
@Test
- public void testUnambiguousPartialLongOption1() throws Exception
- {
- final String[] args = new String[] { "--ver" };
+ public void testUnambiguousPartialLongOption1() throws Exception {
+ final String[] args = {"--ver"};
final Options options = new Options();
options.addOption(OptionBuilder.withLongOpt("version").create());
@@ -500,9 +433,8 @@ public abstract class ParserTestCase
}
@Test
- public void testUnambiguousPartialLongOption2() throws Exception
- {
- final String[] args = new String[] { "-ver" };
+ public void testUnambiguousPartialLongOption2() throws Exception {
+ final String[] args = {"-ver"};
final Options options = new Options();
options.addOption(OptionBuilder.withLongOpt("version").create());
@@ -514,9 +446,8 @@ public abstract class ParserTestCase
}
@Test
- public void testUnambiguousPartialLongOption3() throws Exception
- {
- final String[] args = new String[] { "--ver=1" };
+ public void testUnambiguousPartialLongOption3() throws Exception {
+ final String[] args = {"--ver=1"};
final Options options = new Options();
options.addOption(OptionBuilder.withLongOpt("verbose").hasOptionalArg().create());
@@ -529,9 +460,8 @@ public abstract class ParserTestCase
}
@Test
- public void testUnambiguousPartialLongOption4() throws Exception
- {
- final String[] args = new String[] { "-ver=1" };
+ public void testUnambiguousPartialLongOption4() throws Exception {
+ final String[] args = {"-ver=1"};
final Options options = new Options();
options.addOption(OptionBuilder.withLongOpt("verbose").hasOptionalArg().create());
@@ -544,9 +474,8 @@ public abstract class ParserTestCase
}
@Test
- public void testAmbiguousPartialLongOption1() throws Exception
- {
- final String[] args = new String[] { "--ver" };
+ public void testAmbiguousPartialLongOption1() throws Exception {
+ final String[] args = {"--ver"};
final Options options = new Options();
options.addOption(OptionBuilder.withLongOpt("version").create());
@@ -554,25 +483,21 @@ public abstract class ParserTestCase
boolean caught = false;
- try
- {
+ try {
parser.parse(options, args);
- }
- catch (final AmbiguousOptionException e)
- {
+ } 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 );
+ assertTrue("Confirm MissingArgumentException caught", caught);
}
@Test
- public void testAmbiguousPartialLongOption2() throws Exception
- {
- final String[] args = new String[] { "-ver" };
+ public void testAmbiguousPartialLongOption2() throws Exception {
+ final String[] args = {"-ver"};
final Options options = new Options();
options.addOption(OptionBuilder.withLongOpt("version").create());
@@ -580,25 +505,21 @@ public abstract class ParserTestCase
boolean caught = false;
- try
- {
+ try {
parser.parse(options, args);
- }
- catch (final AmbiguousOptionException e)
- {
+ } 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 );
+ assertTrue("Confirm MissingArgumentException caught", caught);
}
@Test
- public void testAmbiguousPartialLongOption3() throws Exception
- {
- final String[] args = new String[] { "--ver=1" };
+ public void testAmbiguousPartialLongOption3() throws Exception {
+ final String[] args = {"--ver=1"};
final Options options = new Options();
options.addOption(OptionBuilder.withLongOpt("version").create());
@@ -606,25 +527,21 @@ public abstract class ParserTestCase
boolean caught = false;
- try
- {
+ try {
parser.parse(options, args);
- }
- catch (final AmbiguousOptionException e)
- {
+ } 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 );
+ assertTrue("Confirm MissingArgumentException caught", caught);
}
@Test
- public void testAmbiguousPartialLongOption4() throws Exception
- {
- final String[] args = new String[] { "-ver=1" };
+ public void testAmbiguousPartialLongOption4() throws Exception {
+ final String[] args = {"-ver=1"};
final Options options = new Options();
options.addOption(OptionBuilder.withLongOpt("version").create());
@@ -632,25 +549,21 @@ public abstract class ParserTestCase
boolean caught = false;
- try
- {
+ try {
parser.parse(options, args);
- }
- catch (final AmbiguousOptionException e)
- {
+ } 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 );
+ assertTrue("Confirm MissingArgumentException caught", caught);
}
@Test
- public void testPartialLongOptionSingleDash() throws Exception
- {
- final String[] args = new String[] { "-ver" };
+ public void testPartialLongOptionSingleDash() throws Exception {
+ final String[] args = {"-ver"};
final Options options = new Options();
options.addOption(OptionBuilder.withLongOpt("version").create());
@@ -663,15 +576,14 @@ public abstract class ParserTestCase
}
@Test
- public void testWithRequiredOption() throws Exception
- {
- final String[] args = new String[] { "-b", "file" };
+ public void testWithRequiredOption() throws Exception {
+ final String[] args = {"-b", "file"};
final Options options = new Options();
options.addOption("a", "enable-a", false, null);
options.addOption(OptionBuilder.withLongOpt("bfile").hasArg().isRequired().create('b'));
- final CommandLine cl = parser.parse(options,args);
+ final CommandLine cl = parser.parse(options, args);
assertTrue("Confirm -a is NOT set", !cl.hasOption("a"));
assertTrue("Confirm -b is set", cl.hasOption("b"));
@@ -680,15 +592,14 @@ public abstract class ParserTestCase
}
@Test
- public void testOptionAndRequiredOption() throws Exception
- {
- final String[] args = new String[] { "-a", "-b", "file" };
+ public void testOptionAndRequiredOption() throws Exception {
+ final String[] args = {"-a", "-b", "file"};
final Options options = new Options();
options.addOption("a", "enable-a", false, null);
options.addOption(OptionBuilder.withLongOpt("bfile").hasArg().isRequired().create('b'));
- final CommandLine cl = parser.parse(options,args);
+ final CommandLine cl = parser.parse(options, args);
assertTrue("Confirm -a is set", cl.hasOption("a"));
assertTrue("Confirm -b is set", cl.hasOption("b"));
@@ -697,60 +608,47 @@ public abstract class ParserTestCase
}
@Test
- public void testMissingRequiredOption()
- {
- final String[] args = new String[] { "-a" };
+ public void testMissingRequiredOption() {
+ final String[] args = {"-a"};
final Options options = new Options();
options.addOption("a", "enable-a", false, null);
options.addOption(OptionBuilder.withLongOpt("bfile").hasArg().isRequired().create('b'));
- try
- {
- parser.parse(options,args);
+ 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() );
+ } catch (final MissingOptionException e) {
+ assertEquals("Incorrect exception message", "Missing required option: b", e.getMessage());
assertTrue(e.getMissingOptions().contains("b"));
- }
- catch (final ParseException e)
- {
+ } catch (final ParseException e) {
fail("expected to catch MissingOptionException");
}
}
@Test
- public void testMissingRequiredOptions()
- {
- final String[] args = new String[] { "-a" };
+ public void testMissingRequiredOptions() {
+ final String[] args = {"-a"};
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'));
- try
- {
- parser.parse(options,args);
+ try {
+ parser.parse(options, args);
fail("exception should have been thrown");
- }
- catch (final MissingOptionException e)
- {
+ } 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)
- {
+ } catch (final ParseException e) {
fail("expected to catch MissingOptionException");
}
}
@Test
- public void testMissingRequiredGroup() throws Exception
- {
+ public void testMissingRequiredGroup() throws Exception {
final OptionGroup group = new OptionGroup();
group.addOption(OptionBuilder.create("a"));
group.addOption(OptionBuilder.create("b"));
@@ -760,25 +658,19 @@ public abstract class ParserTestCase
options.addOptionGroup(group);
options.addOption(OptionBuilder.isRequired().create("c"));
- try
- {
- parser.parse(options, new String[] { "-c" });
+ try {
+ parser.parse(options, new String[] {"-c"});
fail("MissingOptionException not thrown");
- }
- catch (final MissingOptionException e)
- {
+ } catch (final MissingOptionException e) {
assertEquals(1, e.getMissingOptions().size());
assertTrue(e.getMissingOptions().get(0) instanceof OptionGroup);
- }
- catch (final ParseException e)
- {
+ } catch (final ParseException e) {
fail("Expected to catch MissingOptionException");
}
}
@Test
- public void testOptionGroup() throws Exception
- {
+ public void testOptionGroup() throws Exception {
final OptionGroup group = new OptionGroup();
group.addOption(OptionBuilder.create("a"));
group.addOption(OptionBuilder.create("b"));
@@ -786,14 +678,13 @@ public abstract class ParserTestCase
final Options options = new Options();
options.addOptionGroup(group);
- parser.parse(options, new String[] { "-b" });
+ parser.parse(options, new String[] {"-b"});
assertEquals("selected option", "b", group.getSelected());
}
@Test
- public void testOptionGroupLong() throws Exception
... 2685 lines suppressed ...