diff --git a/.github/dependabot.yml b/.github/dependabot.yml
index 00079caf1..90ec55f74 100644
--- a/.github/dependabot.yml
+++ b/.github/dependabot.yml
@@ -18,10 +18,8 @@ updates:
- package-ecosystem: "maven"
directory: "/"
schedule:
- interval: "weekly"
- day: "friday"
+ interval: "quarterly"
- package-ecosystem: "github-actions"
directory: "/"
schedule:
- interval: "weekly"
- day: "friday"
+ interval: "quarterly"
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md
index 4cbe168c3..9ff35c83e 100644
--- a/.github/pull_request_template.md
+++ b/.github/pull_request_template.md
@@ -23,7 +23,7 @@ Before you push a pull request, review this list:
- [ ] Read the [contribution guidelines](CONTRIBUTING.md) for this project.
- [ ] Read the [ASF Generative Tooling Guidance](https://www.apache.org/legal/generative-tooling.html) if you use Artificial Intelligence (AI).
-- [ ] I used AI to create any part of, or all of, this pull request.
+- [ ] I used AI to create any part of, or all of, this pull request. Which AI tool was used to create this pull request, and to what extent did it contribute?
- [ ] Run a successful build using the default [Maven](https://maven.apache.org/) goal with `mvn`; that's `mvn` on the command line by itself.
- [ ] Write unit tests that match behavioral changes, where the tests fail if the changes to the runtime are not applied. This may not always be possible, but it is a best practice.
- [ ] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml
index f8db33bf4..d0c44b99c 100644
--- a/.github/workflows/codeql-analysis.yml
+++ b/.github/workflows/codeql-analysis.yml
@@ -37,6 +37,7 @@ jobs:
security-events: write
strategy:
+ max-parallel: 20
fail-fast: false
matrix:
language: [ 'java' ]
@@ -45,10 +46,10 @@ jobs:
steps:
- name: Checkout repository
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # 5.0.0
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- - uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
+ - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 #v6.1.0
with:
path: ~/.m2/repository
key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
@@ -57,7 +58,7 @@ jobs:
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
- uses: github/codeql-action/init@0499de31b99561a6d14a36a5f662c2a54f91beee # 3.29.5
+ uses: github/codeql-action/init@ff2f1c621b7f889edc0d3c761ac2e6a3f8cdb0dd # 4.37.7
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
@@ -68,7 +69,7 @@ jobs:
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
- uses: github/codeql-action/autobuild@0499de31b99561a6d14a36a5f662c2a54f91beee # 3.29.5
+ uses: github/codeql-action/autobuild@ff2f1c621b7f889edc0d3c761ac2e6a3f8cdb0dd # 4.37.7
# ℹ️ Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
@@ -82,4 +83,4 @@ jobs:
# make release
- name: Perform CodeQL Analysis
- uses: github/codeql-action/analyze@0499de31b99561a6d14a36a5f662c2a54f91beee # 3.29.5
+ uses: github/codeql-action/analyze@ff2f1c621b7f889edc0d3c761ac2e6a3f8cdb0dd # 4.37.7
diff --git a/.github/workflows/dependency-review.yml b/.github/workflows/dependency-review.yml
index a657a4ae2..4c17443c9 100644
--- a/.github/workflows/dependency-review.yml
+++ b/.github/workflows/dependency-review.yml
@@ -26,6 +26,6 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: 'Checkout Repository'
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: 'Dependency Review PR'
- uses: actions/dependency-review-action@40c09b7dc99638e5ddb0bfd91c1673effc064d8a # v4.8.1
+ uses: actions/dependency-review-action@a1d282b36b6f3519aa1f3fc636f609c47dddb294 # v5.0.0
diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml
index f923232fc..f3235a887 100644
--- a/.github/workflows/maven.yml
+++ b/.github/workflows/maven.yml
@@ -15,7 +15,11 @@
name: Java CI
-on: [push, pull_request]
+on:
+ push:
+ branches:
+ - 'master'
+ pull_request: {}
permissions:
contents: read
@@ -26,25 +30,28 @@ jobs:
runs-on: ubuntu-latest
continue-on-error: ${{ matrix.experimental }}
strategy:
+ max-parallel: 20
matrix:
- java: [ 8, 11, 17, 21, 25 ]
+ java: [ 8, 11, 17, 21, 25, 26 ]
experimental: [false]
include:
- - java: 26-ea
+ - java: 27-ea
+ experimental: true
+ - java: 28-ea
experimental: true
steps:
- - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # 5.0.0
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- - uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
+ - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 #v6.1.0
with:
path: ~/.m2/repository
key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
restore-keys: |
${{ runner.os }}-maven-
- name: Set up JDK ${{ matrix.java }}
- uses: actions/setup-java@dded0888837ed1f317902acf8a20df0ad188d165 # v5.0.0
+ uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # 5.7.0
with:
distribution: 'temurin'
java-version: ${{ matrix.java }}
diff --git a/.github/workflows/scorecards-analysis.yml b/.github/workflows/scorecards-analysis.yml
index 17444b765..b5289bff0 100644
--- a/.github/workflows/scorecards-analysis.yml
+++ b/.github/workflows/scorecards-analysis.yml
@@ -40,12 +40,12 @@ jobs:
steps:
- name: "Checkout code"
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # 5.0.0
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: "Run analysis"
- uses: ossf/scorecard-action@4eaacf0543bb3f2c246792bd56e8cdeffafb205a # 2.4.3
+ uses: ossf/scorecard-action@2d1146689b8cda280b9bc96326124645441f03bc #2.4.4
with:
results_file: results.sarif
results_format: sarif
@@ -57,13 +57,13 @@ jobs:
publish_results: true
- name: "Upload artifact"
- uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0
+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: SARIF file
path: results.sarif
retention-days: 5
- name: "Upload to code-scanning"
- uses: github/codeql-action/upload-sarif@0499de31b99561a6d14a36a5f662c2a54f91beee # 3.29.5
+ uses: github/codeql-action/upload-sarif@ff2f1c621b7f889edc0d3c761ac2e6a3f8cdb0dd # 4.37.7
with:
sarif_file: results.sarif
diff --git a/.gitignore b/.gitignore
index 979659713..5a3aaa1b2 100644
--- a/.gitignore
+++ b/.gitignore
@@ -23,3 +23,7 @@ site-content
*.iws
*.ipr
*.iml
+
+# NetBeans files
+nb-configuration.xml
+nbactions.xml
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index e4440b2a2..7be0822d2 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -48,13 +48,13 @@ Getting Started
---------------
+ Make sure you have a [JIRA account](https://issues.apache.org/jira/).
-+ Make sure you have a [GitHub account](https://github.com/signup/free). This is not essential, but makes providing patches much easier.
++ Make sure you have a [GitHub account](https://github.com/signup). This is not essential, but makes providing patches much easier.
+ If you're planning to implement a new feature it makes sense to discuss your changes on the [dev list](https://commons.apache.org/mail-lists.html) first. This way you can make sure you're not wasting your time on something that isn't considered to be in Apache Commons CLI's scope.
+ Submit a [Jira Ticket][jira] for your issue, assuming one does not already exist.
+ Clearly describe the issue including steps to reproduce when it is a bug.
+ Make sure you fill in the earliest version that you know has the issue.
+ Find the corresponding [repository on GitHub](https://github.com/apache/?query=commons-),
-[fork](https://help.github.com/articles/fork-a-repo/) and check out your forked repository. If you don't have a GitHub account, you can still clone the Commons repository.
+[fork](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/fork-a-repo) and check out your forked repository. If you don't have a GitHub account, you can still clone the Commons repository.
Making Changes
--------------
@@ -108,8 +108,8 @@ Additional Resources
+ [Contributing patches](https://commons.apache.org/patches.html)
+ [Apache Commons CLI JIRA project page][jira]
+ [Contributor License Agreement][cla]
-+ [General GitHub documentation](https://help.github.com/)
-+ [GitHub pull request documentation](https://help.github.com/articles/creating-a-pull-request/)
++ [General GitHub documentation](https://docs.github.com/)
++ [GitHub pull request documentation](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request)
+ [Apache Commons Twitter Account](https://twitter.com/ApacheCommons)
[cla]:https://www.apache.org/licenses/#clas
diff --git a/NOTICE.txt b/NOTICE.txt
index 10eb78eb4..a8fd7fbae 100644
--- a/NOTICE.txt
+++ b/NOTICE.txt
@@ -1,5 +1,5 @@
Apache Commons CLI
-Copyright 2002-2025 The Apache Software Foundation
+Copyright 2002-2026 The Apache Software Foundation
This product includes software developed at
The Apache Software Foundation (https://www.apache.org/).
diff --git a/pom.xml b/pom.xml
index ec44cb737..760a67205 100644
--- a/pom.xml
+++ b/pom.xml
@@ -19,12 +19,12 @@
org.apache.commons
commons-parent
- 91
+ 104
4.0.0
commons-cli
commons-cli
- 1.11.1-SNAPSHOT
+ 1.12.0-SNAPSHOT
Apache Commons CLI
2002
@@ -68,19 +68,18 @@
commons-io
commons-io
- 2.21.0
+ 2.22.0
test
org.apache.commons
commons-text
- 1.14.0
+ 1.15.0
test
org.mockito
mockito-core
- ${commons.mockito.version}
test
@@ -91,12 +90,12 @@
1.8
cli
org.apache.commons.cli
- 1.11.0
- 1.11.1
+ 1.12.0
+ 1.12.1
commons-cli-${commons.release.version}
true
RC1
- 1.10.0
+ 1.11.0
org.apache.commons.cli
CLI
12310463
diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index 269763f54..0bc73da08 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -22,6 +22,27 @@
Apache Commons CLI Release Notes
+
+
+ Fix broken Introduction links on the website #417.
+ Fix malformed Javadoc comments.
+ Correct HelpFormatter Javadoc #418.
+ Fix broken Javadoc links, replace deprecated methods in usage examples, and add a missing method to HelpFormatter (#424).
+ Use Locale.ENGLISH when parsing dates in Converter.DATE (#426).
+ Reject non-BMP code points in the Character type converter (#425).
+ Reject invalid dates in Converter.DATE (#430).
+ Reject an empty option name in getMatchingOptions (#434).
+ Reject trailing text after the date in Converter.DATE (#435).
+ Fix integer overflow in TextHelpAppendable.indexOfWrap (#437).
+ Reject UTF-16 surrogate values in Character converter (#438).
+ Fix HelpFormatter wrapped description indent (#439).
+
+ Add AbstractHelpFormatter.printHelp(String, Options).
+
+ Bump org.apache.commons:commons-parent from 91 to 104 #414, #416.
+ [test] Bump org.apache.commons:commons-text from 1.14.0 to 1.15.0.
+ Bump commons-io:commons-io from 2.21.0 to 2.22.0.
+
Multiple trailing BREAK_CHAR_SET characters cause infinite loop in HelpFormatter.
diff --git a/src/main/java/org/apache/commons/cli/AlreadySelectedException.java b/src/main/java/org/apache/commons/cli/AlreadySelectedException.java
index 7603eac5e..99024c197 100644
--- a/src/main/java/org/apache/commons/cli/AlreadySelectedException.java
+++ b/src/main/java/org/apache/commons/cli/AlreadySelectedException.java
@@ -36,8 +36,8 @@ public class AlreadySelectedException extends ParseException {
/**
* Constructs a new {@code AlreadySelectedException} for the specified option group.
*
- * @param optionGroup the option group already selected.
- * @param option the option that triggered the exception.
+ * @param optionGroup The option group already selected.
+ * @param option The option that triggered the exception.
* @since 1.2
*/
public AlreadySelectedException(final OptionGroup optionGroup, final Option option) {
@@ -48,7 +48,7 @@ public AlreadySelectedException(final OptionGroup optionGroup, final Option opti
/**
* Constructs a new {@code AlreadySelectedException} with the specified detail message.
*
- * @param message the detail message.
+ * @param message The detail message.
*/
public AlreadySelectedException(final String message) {
this(message, null, null);
@@ -63,7 +63,7 @@ private AlreadySelectedException(final String message, final OptionGroup optionG
/**
* Gets the option that was added to the group and triggered the exception.
*
- * @return the related option.
+ * @return The related option.
* @since 1.2
*/
public Option getOption() {
@@ -73,7 +73,7 @@ public Option getOption() {
/**
* Gets the option group where another option has been selected.
*
- * @return the related option group.
+ * @return The related option group.
* @since 1.2
*/
public OptionGroup getOptionGroup() {
diff --git a/src/main/java/org/apache/commons/cli/AmbiguousOptionException.java b/src/main/java/org/apache/commons/cli/AmbiguousOptionException.java
index d38a81ccc..1a64e95c1 100644
--- a/src/main/java/org/apache/commons/cli/AmbiguousOptionException.java
+++ b/src/main/java/org/apache/commons/cli/AmbiguousOptionException.java
@@ -26,6 +26,7 @@ Licensed to the Apache Software Foundation (ASF) under one or more
* @since 1.3
*/
public class AmbiguousOptionException extends UnrecognizedOptionException {
+
/**
* This exception {@code serialVersionUID}.
*/
@@ -61,8 +62,8 @@ private static String createMessage(final String option, final Collection matchingOptions) {
super(createMessage(option, matchingOptions), option);
@@ -72,7 +73,7 @@ public AmbiguousOptionException(final String option, final Collection ma
/**
* Gets the options matching the partial name.
*
- * @return a collection of options matching the name.
+ * @return A collection of options matching the name.
*/
public Collection getMatchingOptions() {
return matchingOptions;
diff --git a/src/main/java/org/apache/commons/cli/CommandLine.java b/src/main/java/org/apache/commons/cli/CommandLine.java
index 477903e7d..2942d5f92 100644
--- a/src/main/java/org/apache/commons/cli/CommandLine.java
+++ b/src/main/java/org/apache/commons/cli/CommandLine.java
@@ -76,7 +76,7 @@ public Builder() {
/**
* Adds left-over unrecognized option/argument.
*
- * @param arg the unrecognized option/argument.
+ * @param arg The unrecognized option/argument.
* @return this Builder instance for method chaining.
*/
public Builder addArg(final String arg) {
@@ -89,7 +89,7 @@ public Builder addArg(final String arg) {
/**
* Adds an option to the command line. The values of the option are stored.
*
- * @param option the processed option.
+ * @param option The processed option.
* @return this Builder instance for method chaining.
*/
public Builder addOption(final Option option) {
@@ -102,7 +102,7 @@ public Builder addOption(final Option option) {
/**
* Creates a new instance.
*
- * @return a new instance.
+ * @return A new instance.
* @deprecated Use {@link #get()}.
*/
@Deprecated
@@ -113,7 +113,7 @@ public CommandLine build() {
/**
* Creates a new instance.
*
- * @return a new instance.
+ * @return A new instance.
* @since 1.10.0
*/
@Override
@@ -124,7 +124,7 @@ public CommandLine get() {
/**
* Sets the deprecated option handler.
*
- * @param deprecatedHandler the deprecated option handler.
+ * @param deprecatedHandler The deprecated option handler.
* @return {@code this} instance.
* @since 1.7.0
*/
@@ -140,7 +140,7 @@ public Builder setDeprecatedHandler(final Consumer deprecatedHandler) {
/**
* Creates a new builder.
*
- * @return a new builder.
+ * @return A new builder.
* @since 1.7.0
*/
public static Builder builder() {
@@ -180,7 +180,7 @@ private CommandLine(final List args, final List options, final C
/**
* Adds left-over unrecognized option/argument.
*
- * @param arg the unrecognized option/argument.
+ * @param arg The unrecognized option/argument.
*/
protected void addArg(final String arg) {
if (arg != null) {
@@ -191,7 +191,7 @@ protected void addArg(final String arg) {
/**
* Adds an option to the command line. The values of the option are stored.
*
- * @param option the processed option.
+ * @param option The processed option.
*/
protected void addOption(final Option option) {
if (option != null) {
@@ -202,8 +202,8 @@ protected void addOption(final Option option) {
/**
* Gets the first element or null if values is null.
*
- * @param values the array to query.
- * @return the first element or null if values is null.
+ * @param values The array to query.
+ * @return The first element or null if values is null.
*/
private String first(final String[] values) {
return values == null ? null : values[0];
@@ -234,7 +234,7 @@ public String[] getArgs() {
/**
* Gets the number of times this option appears in the command line
*
- * @param optionChar the character name of the option.
+ * @param optionChar The character name of the option.
* @return Number of times the option is present.
* @since 1.11.0
*/
@@ -245,7 +245,7 @@ public int getOptionCount(final char optionChar) {
/**
* Gets the number of times this option appears in the command line.
*
- * @param option the option.
+ * @param option The option.
* @return Number of times the option is present.
* @since 1.11.0
*/
@@ -256,7 +256,7 @@ public int getOptionCount(final Option option) {
/**
* Gets the number of times this option appears in the command line
*
- * @param optionName the name of the option.
+ * @param optionName The name of the option.
* @return Number of times the option is present.
* @since 1.11.0
*/
@@ -267,9 +267,9 @@ public int getOptionCount(final String optionName) {
/**
* Gets the {@code Object} type of this {@code Option}.
*
+ * @param optionChar The name of the option.
+ * @return The type of opt.
* @deprecated due to System.err message; use {@link #getParsedOptionValue(char)} instead.
- * @param optionChar the name of the option.
- * @return the type of opt.
*/
@Deprecated
public Object getOptionObject(final char optionChar) {
@@ -279,8 +279,8 @@ public Object getOptionObject(final char optionChar) {
/**
* Gets the {@code Object} type of this {@code Option}.
*
- * @param optionName the name of the option.
- * @return the type of this {@code Option}.
+ * @param optionName The name of the option.
+ * @return The type of this {@code Option}.
* @deprecated due to System.err message; use {@link #getParsedOptionValue(String)} instead.
*/
@Deprecated
@@ -337,7 +337,7 @@ public Properties getOptionProperties(final String optionName) {
/**
* Gets an array of the processed {@link Option}s.
*
- * @return an array of the processed {@link Option}s.
+ * @return An array of the processed {@link Option}s.
*/
public Option[] getOptions() {
return options.toArray(Option.EMPTY_ARRAY);
@@ -346,7 +346,7 @@ public Option[] getOptions() {
/**
* Gets the first argument, if any, of this option.
*
- * @param optionChar the character name of the option.
+ * @param optionChar The character name of the option.
* @return Value of the argument if option is set, and has an argument, otherwise null.
*/
public String getOptionValue(final char optionChar) {
@@ -379,7 +379,7 @@ public String getOptionValue(final char optionChar, final Supplier defau
/**
* Gets the first argument, if any, of this option.
*
- * @param option the option.
+ * @param option The option.
* @return Value of the argument if option is set, and has an argument, otherwise null.
* @since 1.5.0
*/
@@ -390,7 +390,7 @@ public String getOptionValue(final Option option) {
/**
* Gets the first argument, if any, of an option.
*
- * @param option the option.
+ * @param option 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}.
* @since 1.5.0
@@ -402,7 +402,7 @@ public String getOptionValue(final Option option, final String defaultValue) {
/**
* Gets the first argument, if any, of an option.
*
- * @param option the option.
+ * @param option The option.
* @param defaultValue is a supplier for 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}.
* @since 1.7.0
@@ -415,7 +415,7 @@ public String getOptionValue(final Option option, final Supplier default
/**
* Gets the first argument, if any, of this option group.
*
- * @param optionGroup the option group.
+ * @param optionGroup The option group.
* @return Value of the argument if option group is selected, and has an argument, otherwise null.
* @since 1.9.0
*/
@@ -426,7 +426,7 @@ public String getOptionValue(final OptionGroup optionGroup) {
/**
* Gets the first argument, if any, of an option group.
*
- * @param optionGroup the option group.
+ * @param optionGroup The option group.
* @param defaultValue is the default value to be returned if the option group is not selected.
* @return Value of the argument if option group is selected, and has an argument, otherwise {@code defaultValue}.
* @since 1.9.0
@@ -438,7 +438,7 @@ public String getOptionValue(final OptionGroup optionGroup, final String default
/**
* Gets the first argument, if any, of an option group.
*
- * @param optionGroup the option group.
+ * @param optionGroup The option group.
* @param defaultValue is a supplier for the default value to be returned if the option group is not selected.
* @return Value of the argument if option group is selected, and has an argument, otherwise {@code defaultValue}.
* @since 1.9.0
@@ -451,7 +451,7 @@ public String getOptionValue(final OptionGroup optionGroup, final Supplier The return type for the method.
- * @return the value parsed into a particular object or null if the option is not set.
+ * @return The value parsed into a particular object or null if the option is not set.
* @throws ParseException if there are problems turning the option value into the desired type.
* @see PatternOptionBuilder
* @since 1.5.0
@@ -555,10 +555,10 @@ public T getParsedOptionValue(final char optionChar) throws ParseException {
/**
* Gets a version of this {@code Option} converted to a particular type.
*
- * @param optionChar the name of the option.
- * @param defaultValue the default value to return if opt is not set.
+ * @param optionChar The name of the option.
+ * @param defaultValue The default value to return if opt is not set.
* @param The return type for the method.
- * @return the value parsed into a particular object or the defaultValue if the option is not set.
+ * @return The value parsed into a particular object or the defaultValue if the option is not set.
* @throws ParseException if there are problems turning the option value into the desired type.
* @see PatternOptionBuilder
* @since 1.7.0
@@ -570,10 +570,10 @@ public T getParsedOptionValue(final char optionChar, final Supplier defau
/**
* Gets a version of this {@code Option} converted to a particular type.
*
- * @param optionChar the name of the option.
- * @param defaultValue the default value to return if opt is not set.
+ * @param optionChar The name of the option.
+ * @param defaultValue The default value to return if opt is not set.
* @param The return type for the method.
- * @return the value parsed into a particular object or the defaultValue if the option is not set.
+ * @return The value parsed into a particular object or the defaultValue if the option is not set.
* @throws ParseException if there are problems turning the option value into the desired type.
* @see PatternOptionBuilder
* @since 1.7.0
@@ -585,9 +585,9 @@ public T getParsedOptionValue(final char optionChar, final T defaultValue) t
/**
* Gets a version of this {@code Option} converted to a particular type.
*
- * @param option the option.
+ * @param option The option.
* @param The return type for the method.
- * @return the value parsed into a particular object or null if the option is not set.
+ * @return The value parsed into a particular object or null if the option is not set.
* @throws ParseException if there are problems turning the option value into the desired type.
* @see PatternOptionBuilder
* @since 1.5.0
@@ -599,10 +599,10 @@ public T getParsedOptionValue(final Option option) throws ParseException {
/**
* Gets a version of this {@code Option} converted to a particular type.
*
- * @param option the option.
- * @param defaultValue the default value to return if opt is not set.
+ * @param option The option.
+ * @param defaultValue The default value to return if opt is not set.
* @param The return type for the method.
- * @return the value parsed into a particular object or the defaultValue if the option is not set.
+ * @return The value parsed into a particular object or the defaultValue if the option is not set.
* @throws ParseException if there are problems turning the option value into the desired type.
* @see PatternOptionBuilder
* @since 1.7.0
@@ -626,10 +626,10 @@ public T getParsedOptionValue(final Option option, final Supplier default
/**
* Gets a version of this {@code Option} converted to a particular type.
*
- * @param option the option.
- * @param defaultValue the default value to return if opt is not set.
+ * @param option The option.
+ * @param defaultValue The default value to return if opt is not set.
* @param The return type for the method.
- * @return the value parsed into a particular object or the defaultValue if the option is not set.
+ * @return The value parsed into a particular object or the defaultValue if the option is not set.
* @throws ParseException if there are problems turning the option value into the desired type.
* @see PatternOptionBuilder
* @since 1.7.0
@@ -641,9 +641,9 @@ public T getParsedOptionValue(final Option option, final T defaultValue) thr
/**
* Gets a version of this {@code OptionGroup} converted to a particular type.
*
- * @param optionGroup the option group.
+ * @param optionGroup The option group.
* @param The return type for the method.
- * @return the value parsed into a particular object or null if no option in the OptionGroup is set.
+ * @return The value parsed into a particular object or null if no option in the OptionGroup is set.
* @throws ParseException if there are problems turning the selected option value into the desired type.
* @see PatternOptionBuilder
* @since 1.9.0
@@ -655,10 +655,10 @@ public T getParsedOptionValue(final OptionGroup optionGroup) throws ParseExc
/**
* Gets a version of this {@code OptionGroup} converted to a particular type.
*
- * @param optionGroup the option group.
- * @param defaultValue the default value to return if opt is not set.
+ * @param optionGroup The option group.
+ * @param defaultValue The default value to return if opt is not set.
* @param The return type for the method.
- * @return the value parsed into a particular object or the defaultValue if no option in the OptionGroup is set.
+ * @return The value parsed into a particular object or the defaultValue if no option in the OptionGroup is set.
* @throws ParseException if there are problems turning the selected option value into the desired type.
* @see PatternOptionBuilder
* @since 1.9.0
@@ -673,10 +673,10 @@ public T getParsedOptionValue(final OptionGroup optionGroup, final Supplier<
/**
* Gets a version of this {@code OptionGroup} converted to a particular type.
*
- * @param optionGroup the option group.
- * @param defaultValue the default value to return if an option is not selected.
+ * @param optionGroup The option group.
+ * @param defaultValue The default value to return if an option is not selected.
* @param The return type for the method.
- * @return the value parsed into a particular object or the defaultValue if no option in the OptionGroup is set.
+ * @return The value parsed into a particular object or the defaultValue if no option in the OptionGroup is set.
* @throws ParseException if there are problems turning the option value into the desired type.
* @see PatternOptionBuilder
* @since 1.9.0
@@ -688,9 +688,9 @@ public T getParsedOptionValue(final OptionGroup optionGroup, final T default
/**
* Gets a version of this {@code Option} converted to a particular type.
*
- * @param optionName the name of the option.
+ * @param optionName The name of the option.
* @param The return type for the method.
- * @return the value parsed into a particular object or null if the option is not set.
+ * @return The value parsed into a particular object or null if the option is not set.
* @throws ParseException if there are problems turning the option value into the desired type.
* @see PatternOptionBuilder
* @since 1.2
@@ -702,10 +702,10 @@ public T getParsedOptionValue(final String optionName) throws ParseException
/**
* Gets a version of this {@code Option} converted to a particular type.
*
- * @param optionName the name of the option.
- * @param defaultValue the default value to return if opt is not set.
+ * @param optionName The name of the option.
+ * @param defaultValue The default value to return if opt is not set.
* @param The return type for the method.
- * @return the value parsed into a particular object or the defaultValue if the option is not set.
+ * @return The value parsed into a particular object or the defaultValue if the option is not set.
* @throws ParseException if there are problems turning the option value into the desired type.
* @see PatternOptionBuilder
* @since 1.7.0
@@ -717,10 +717,10 @@ public T getParsedOptionValue(final String optionName, final Supplier def
/**
* Gets a version of this {@code Option} converted to a particular type.
*
- * @param optionName the name of the option.
- * @param defaultValue the default value to return if opt is not set.
+ * @param optionName The name of the option.
+ * @param defaultValue The default value to return if opt is not set.
* @param The return type for the method.
- * @return the value parsed into a particular object or the defaultValue if the option is not set.
+ * @return The value parsed into a particular object or the defaultValue if the option is not set.
* @throws ParseException if there are problems turning the option value into the desired type.
* @see PatternOptionBuilder
* @since 1.7.0
@@ -732,9 +732,9 @@ public T getParsedOptionValue(final String optionName, final T defaultValue)
/**
* Gets a version of this {@code Option} converted to an array of a particular type.
*
- * @param optionChar the name of the option.
+ * @param optionChar The name of the option.
* @param The array type for the return value.
- * @return the values parsed into an array of objects or null if the option is not set.
+ * @return The values parsed into an array of objects or null if the option is not set.
* @throws ParseException if there are problems turning the option value into the desired type.
* @see PatternOptionBuilder
* @since 1.10.0
@@ -746,10 +746,10 @@ public T[] getParsedOptionValues(final char optionChar) throws ParseExceptio
/**
* Gets a version of this {@code Option} converted to an array of a particular type.
*
- * @param optionChar the name of the option.
- * @param defaultValue the default value to return if opt is not set.
+ * @param optionChar The name of the option.
+ * @param defaultValue The default value to return if opt is not set.
* @param The array type for the return value.
- * @return the values parsed into an array of objects or the defaultValue if the option is not set.
+ * @return The values parsed into an array of objects or the defaultValue if the option is not set.
* @throws ParseException if there are problems turning the option value into the desired type.
* @see PatternOptionBuilder
* @since 1.10.0
@@ -761,10 +761,10 @@ public T[] getParsedOptionValues(final char optionChar, final Supplier
/**
* Gets a version of this {@code Option} converted to an array of a particular type.
*
- * @param optionChar the name of the option.
- * @param defaultValue the default value to return if opt is not set.
+ * @param optionChar The name of the option.
+ * @param defaultValue The default value to return if opt is not set.
* @param The array type for the return value.
- * @return the values parsed into an array of objects or the defaultValue if the option is not set.
+ * @return The values parsed into an array of objects or the defaultValue if the option is not set.
* @throws ParseException if there are problems turning the option value into the desired type.
* @see PatternOptionBuilder
* @since 1.10.0
@@ -776,9 +776,9 @@ public T[] getParsedOptionValues(final char optionChar, final T[] defaultVal
/**
* Gets a version of this {@code Option} converted to an array of a particular type.
*
- * @param option the option.
+ * @param option The option.
* @param The array type for the return value.
- * @return the values parsed into an array of objects or null if the option is not set.
+ * @return The values parsed into an array of objects or null if the option is not set.
* @throws ParseException if there are problems turning the option value into the desired type.
* @see PatternOptionBuilder
* @since 1.10.0
@@ -790,10 +790,10 @@ public T[] getParsedOptionValues(final Option option) throws ParseException
/**
* Gets a version of this {@code Option} converted to an array of a particular type.
*
- * @param option the option.
- * @param defaultValue the default value to return if opt is not set.
+ * @param option The option.
+ * @param defaultValue The default value to return if opt is not set.
* @param The array type for the return value.
- * @return the values parsed into an array of objects or the defaultValue if the option is not set.
+ * @return The values parsed into an array of objects or the defaultValue if the option is not set.
* @throws ParseException if there are problems turning the option value into the desired type.
* @see PatternOptionBuilder
* @since 1.10.0
@@ -822,10 +822,10 @@ public T[] getParsedOptionValues(final Option option, final Supplier de
/**
* Gets a version of this {@code Option} converted to an array of a particular type.
*
- * @param option the option.
- * @param defaultValue the default value to return if opt is not set.
+ * @param option The option.
+ * @param defaultValue The default value to return if opt is not set.
* @param The array type for the return value.
- * @return the values parsed into an array of objects or the defaultValue if the option is not set.
+ * @return The values parsed into an array of objects or the defaultValue if the option is not set.
* @throws ParseException if there are problems turning the option value into the desired type.
* @see PatternOptionBuilder
* @since 1.10.0
@@ -837,9 +837,9 @@ public T[] getParsedOptionValues(final Option option, final T[] defaultValue
/**
* Gets a version of this {@code OptionGroup} converted to an array of a particular type.
*
- * @param optionGroup the option group.
+ * @param optionGroup The option group.
* @param The array type for the return value.
- * @return the values parsed into an array of objects or null if no option in the OptionGroup is set.
+ * @return The values parsed into an array of objects or null if no option in the OptionGroup is set.
* @throws ParseException if there are problems turning the selected option value into the desired type.
* @see PatternOptionBuilder
* @since 1.10.0
@@ -851,10 +851,10 @@ public T[] getParsedOptionValues(final OptionGroup optionGroup) throws Parse
/**
* Gets a version of this {@code OptionGroup} converted to an array of a particular type.
*
- * @param optionGroup the option group.
- * @param defaultValue the default value to return if opt is not set.
+ * @param optionGroup The option group.
+ * @param defaultValue The default value to return if opt is not set.
* @param The array type for the return value.
- * @return the values parsed into an array of objects or null if no option in the OptionGroup is set.
+ * @return The values parsed into an array of objects or null if no option in the OptionGroup is set.
* @throws ParseException if there are problems turning the selected option value into the desired type.
* @see PatternOptionBuilder
* @since 1.10.0
@@ -869,10 +869,10 @@ public T[] getParsedOptionValues(final OptionGroup optionGroup, final Suppli
/**
* Gets a version of this {@code OptionGroup} converted to an array of a particular type.
*
- * @param optionGroup the option group.
- * @param defaultValue the default value to return if an option is not selected.
+ * @param optionGroup The option group.
+ * @param defaultValue The default value to return if an option is not selected.
* @param The array type for the return value.
- * @return the values parsed into an array of objects or null if no option in the OptionGroup is set.
+ * @return The values parsed into an array of objects or null if no option in the OptionGroup is set.
* @throws ParseException if there are problems turning the option value into the desired type.
* @see PatternOptionBuilder
* @since 1.10.0
@@ -884,9 +884,9 @@ public T[] getParsedOptionValues(final OptionGroup optionGroup, final T[] de
/**
* Gets a version of this {@code Option} converted to an array of a particular type.
*
- * @param optionName the name of the option.
+ * @param optionName The name of the option.
* @param The array type for the return value.
- * @return the values parsed into an array of objects or null if the option is not set.
+ * @return The values parsed into an array of objects or null if the option is not set.
* @throws ParseException if there are problems turning the option value into the desired type.
* @see PatternOptionBuilder
* @since 1.10.0
@@ -898,10 +898,10 @@ public T[] getParsedOptionValues(final String optionName) throws ParseExcept
/**
* Gets a version of this {@code Option} converted to an array of a particular type.
*
- * @param optionName the name of the option.
- * @param defaultValue the default value to return if opt is not set.
+ * @param optionName The name of the option.
+ * @param defaultValue The default value to return if opt is not set.
* @param The array type for the return value.
- * @return the values parsed into an array of objects or defaultValues if the option is not set.
+ * @return The values parsed into an array of objects or defaultValues if the option is not set.
* @throws ParseException if there are problems turning the option value into the desired type.
* @see PatternOptionBuilder
* @since 1.10.0
@@ -913,10 +913,10 @@ public T[] getParsedOptionValues(final String optionName, final Supplier The array type for the return value.
- * @return the values parsed into an array of objects or defaultValues if the option is not set.
+ * @return The values parsed into an array of objects or defaultValues if the option is not set.
* @throws ParseException if there are problems turning the option value into the desired type.
* @see PatternOptionBuilder
* @since 1.10.0
@@ -928,7 +928,7 @@ public T[] getParsedOptionValues(final String optionName, final T[] defaultV
/**
* Handles deprecated options.
*
- * @param option a deprecated option.
+ * @param option A deprecated option.
*/
private void handleDeprecated(final Option option) {
if (deprecatedHandler != null) {
@@ -967,7 +967,7 @@ public boolean hasOption(final char optionChar) {
/**
* Tests to see if an option has been set.
*
- * @param option the option to check.
+ * @param option The option to check.
* @return true if set, false if not.
* @since 1.5.0
*/
@@ -982,7 +982,7 @@ public boolean hasOption(final Option option) {
/**
* Tests to see if an option has been set.
*
- * @param optionGroup the option group to check.
+ * @param optionGroup The option group to check.
* @return true if set, false if not.
* @since 1.9.0
*/
@@ -1006,7 +1006,7 @@ public boolean hasOption(final String optionName) {
/**
* Returns an iterator over the Option members of CommandLine.
*
- * @return an {@code Iterator} over the processed {@link Option} members of this {@link CommandLine}.
+ * @return An {@code Iterator} over the processed {@link Option} members of this {@link CommandLine}.
*/
public Iterator iterator() {
return options.iterator();
@@ -1017,8 +1017,8 @@ public Iterator iterator() {
* and even numbered values are property values. If there are an odd number of values
* the last value is assumed to be a boolean with a value of "true".
*
- * @param props the properties to update.
- * @param values the list of values to parse.
+ * @param props The properties to update.
+ * @param values The list of values to parse.
*/
private void processPropertiesFromValues(final Properties props, final List values) {
for (int i = 0; i < values.size(); i += 2) {
diff --git a/src/main/java/org/apache/commons/cli/CommandLineParser.java b/src/main/java/org/apache/commons/cli/CommandLineParser.java
index fb35630d5..8b686905d 100644
--- a/src/main/java/org/apache/commons/cli/CommandLineParser.java
+++ b/src/main/java/org/apache/commons/cli/CommandLineParser.java
@@ -26,9 +26,9 @@ public interface CommandLineParser {
/**
* Parses the arguments according to the specified options.
*
- * @param options the specified Options.
- * @param arguments the command line arguments.
- * @return the list of atomic option and value tokens.
+ * @param options The specified Options.
+ * @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.
*/
CommandLine parse(Options options, String[] arguments) throws ParseException;
@@ -36,13 +36,13 @@ public interface CommandLineParser {
/**
* Parses the arguments according to the specified options.
*
- * @param options the specified Options.
- * @param arguments the command line arguments.
+ * @param options The specified Options.
+ * @param arguments The command line arguments.
* @param stopAtNonOption if {@code true} an unrecognized argument stops the parsing and the remaining arguments
* are added to the {@link CommandLine}s args list. If {@code false} an unrecognized argument triggers a
* ParseException.
*
- * @return the list of atomic option and value tokens.
+ * @return The list of atomic option and value 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;
diff --git a/src/main/java/org/apache/commons/cli/Converter.java b/src/main/java/org/apache/commons/cli/Converter.java
index 7e92c32f0..1faf78174 100644
--- a/src/main/java/org/apache/commons/cli/Converter.java
+++ b/src/main/java/org/apache/commons/cli/Converter.java
@@ -22,8 +22,10 @@ Licensed to the Apache Software Foundation (ASF) under one or more
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Paths;
+import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
+import java.util.Locale;
/**
* The definition of the functional interface to call when doing a conversion. Like {@code Function} but can throw an Exception.
@@ -37,27 +39,27 @@ public interface Converter {
// See also Apache Commons Lang FailableFunction
/**
- * The default converter. Does nothing.
+ * The default converter does nothing.
*/
Converter, RuntimeException> DEFAULT = s -> s;
/**
- * Class name converter. Calls {@link Class#forName(String)}.
+ * Converts a String to a {@link Class}. Calls {@link Class#forName(String)}.
*/
Converter, ClassNotFoundException> CLASS = Class::forName;
/**
- * File name converter. Calls {@link File#File(String)}.
+ * Converts a String to a {@link File}. Calls {@link File#File(String)}.
*/
Converter FILE = File::new;
/**
- * Path converter. Calls {@link Paths#get(java.net.URI)}.
+ * Converts a String to a {@link Path}. Calls {@link Paths#get(String, String...)}.
*/
Converter PATH = Paths::get;
/**
- * Number converter. Converts to a Double if a decimal point ('.') is in the string or a Long otherwise.
+ * Converts a String to a {@link Number}. Converts to a Double if a decimal point ('.') is in the string or a Long otherwise.
*/
Converter NUMBER = s -> s.indexOf('.') != -1 ? (Number) Double.valueOf(s) : (Number) Long.valueOf(s);
@@ -69,20 +71,45 @@ public interface Converter {
Converter OBJECT = s -> CLASS.apply(s).getConstructor().newInstance();
/**
- * Creates a URL. Calls {@link URL#URL(String)}.
+ * Converts a String to a {@link URL}. Calls {@link URL#URL(String)}.
*/
Converter URL = URL::new;
/**
- * Converts to a date using the format string Form "EEE MMM dd HH:mm:ss zzz yyyy".
+ * Converts a String to a {@link Date} using the format string Form "EEE MMM dd HH:mm:ss zzz yyyy".
*/
- Converter DATE = s -> new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy").parse(s);
+ Converter DATE = s -> {
+ final String pattern = "EEE MMM dd HH:mm:ss zzz yyyy";
+ final SimpleDateFormat format = new SimpleDateFormat(pattern);
+ // reject out-of-range fields (for example "Feb 30") instead of silently rolling them over.
+ format.setLenient(false);
+ // SimpleDateFormat.parse(String) stops at the first character it cannot use and ignores any
+ // trailing text, so " garbage" would be accepted. Parse from an explicit position
+ // and reject the value unless the whole string is consumed.
+ final ParsePosition pos = new ParsePosition(0);
+ Date date = format.parse(s, pos);
+ if (date == null) {
+ // Date.toString() always emits English month/day names, so fall back to Locale.ENGLISH
+ // when the default locale rejects the documented format. Only retry when the default
+ // locale matched nothing; a partial match is a trailing-text failure, handled below.
+ final SimpleDateFormat englishFormat = new SimpleDateFormat(pattern, Locale.ENGLISH);
+ englishFormat.setLenient(false);
+ pos.setIndex(0);
+ pos.setErrorIndex(-1);
+ date = englishFormat.parse(s, pos);
+ }
+ if (date == null || pos.getIndex() != s.length()) {
+ final int errorIndex = pos.getErrorIndex() >= 0 ? pos.getErrorIndex() : pos.getIndex();
+ throw new java.text.ParseException(String.format("Unparseable date: \"%s\"", s), errorIndex);
+ }
+ return date;
+ };
/**
* Applies the conversion function to the String argument.
*
- * @param string the String to convert.
- * @return the Object from the conversion.
+ * @param string The String to convert.
+ * @return The Object from the conversion.
* @throws E on error.
*/
T apply(String string) throws E;
diff --git a/src/main/java/org/apache/commons/cli/DefaultParser.java b/src/main/java/org/apache/commons/cli/DefaultParser.java
index da7960b3d..4dd7dfec2 100644
--- a/src/main/java/org/apache/commons/cli/DefaultParser.java
+++ b/src/main/java/org/apache/commons/cli/DefaultParser.java
@@ -35,15 +35,11 @@ Licensed to the Apache Software Foundation (ASF) under one or more
public class DefaultParser implements CommandLineParser {
/**
- * A nested builder class to create {@code DefaultParser} instances
- * using descriptive methods.
+ * A nested builder class to create {@code DefaultParser} instances using descriptive methods. Example usage:
*
- * Example usage:
*
- * DefaultParser parser = Option.builder()
- * .setAllowPartialMatching(false)
- * .setStripLeadingAndTrailingQuotes(false)
- * .build();
+ *
+ * DefaultParser parser = Option.builder().setAllowPartialMatching(false).setStripLeadingAndTrailingQuotes(false).build();
*
*
* @since 1.5.0
@@ -76,7 +72,7 @@ private Builder() {
/**
* Builds an DefaultParser with the values declared by this {@link Builder}.
*
- * @return the new {@link DefaultParser}.
+ * @return The new {@link DefaultParser}.
* @since 1.5.0
* @deprecated Use {@link #get()}.
*/
@@ -88,7 +84,7 @@ public DefaultParser build() {
/**
* Builds an DefaultParser with the values declared by this {@link Builder}.
*
- * @return the new {@link DefaultParser}.
+ * @return The new {@link DefaultParser}.
* @since 1.10.0
*/
@Override
@@ -110,7 +106,7 @@ public DefaultParser get() {
* }
*
* If "partial matching" is turned on, {@code -de} only matches the {@code "debug"} option. However, with "partial matching" disabled, {@code -de} would
- * enable both {@code debug} as well as {@code extract}
+ * enable both {@code debug} as well as {@code extract}.
*
*
* @param allowPartialMatching whether to allow partial matching of long options.
@@ -125,7 +121,7 @@ public Builder setAllowPartialMatching(final boolean allowPartialMatching) {
/**
* Sets the deprecated option handler.
*
- * @param deprecatedHandler the deprecated option handler.
+ * @param deprecatedHandler The deprecated option handler.
* @return {@code this} instance.
* @since 1.7.0
*/
@@ -136,7 +132,6 @@ public Builder setDeprecatedHandler(final Consumer deprecatedHandler) {
/**
* Sets if balanced leading and trailing double quotes should be stripped from option arguments.
- *
*
* If "stripping of balanced leading and trailing double quotes from option arguments" is true, the outermost balanced double quotes of option arguments
* values will be removed. For example, {@code -o '"x"'} getValue() will return {@code x}, instead of {@code "x"}
@@ -157,11 +152,12 @@ public Builder setStripLeadingAndTrailingQuotes(final Boolean stripLeadingAndTra
}
/**
- * Enum representing possible actions that may be done when "non option" is discovered during parsing.
+ * Enumerates possible actions that may be done when "non option" is discovered during parsing.
*
* @since 1.10.0
*/
public enum NonOptionAction {
+
/**
* Parsing continues and current token is ignored.
*/
@@ -171,22 +167,19 @@ public enum NonOptionAction {
*/
SKIP,
/**
- * Parsing will stop and remaining tokens are added to command line arguments.
- * Equivalent of {@code stopAtNonOption = true}.
+ * Parsing will stop and remaining tokens are added to command line arguments. Equivalent of {@code stopAtNonOption = true}.
*/
STOP,
/**
- * Parsing will abort and exception is thrown.
- * Equivalent of {@code stopAtNonOption = false}.
+ * Parsing will abort and exception is thrown. Equivalent of {@code stopAtNonOption = false}.
*/
THROW;
}
/**
- * Creates a new {@link Builder} to create an {@link DefaultParser} using descriptive
- * methods.
+ * Creates a new {@link Builder} to create an {@link DefaultParser} using descriptive methods.
*
- * @return a new {@link Builder} instance
+ * @return A new {@link Builder} instance
* @since 1.5.0
*/
public static Builder builder() {
@@ -204,8 +197,8 @@ static int indexOfEqual(final String token) {
protected Options options;
/**
- * Flag indicating how unrecognized tokens are handled. {@code true} to stop the parsing and add the remaining
- * tokens to the args list. {@code false} to throw an exception.
+ * Flag indicating how unrecognized tokens are handled. {@code true} to stop the parsing and add the remaining tokens to the args list. {@code false} to
+ * throw an exception.
*
* @deprecated Use {@link #nonOptionAction} instead. This field is unused, and left for binary compatibility reasons.
*/
@@ -236,8 +229,9 @@ static int indexOfEqual(final String token) {
/** Flag indicating if partial matching of long options is supported. */
private final boolean allowPartialMatching;
- /** Flag indicating if balanced leading and trailing double quotes should be stripped from option arguments.
- * null represents the historic arbitrary behavior */
+ /**
+ * Flag indicating if balanced leading and trailing double quotes should be stripped from option arguments. null represents the historic arbitrary behavior
+ */
private final Boolean stripLeadingAndTrailingQuotes;
/**
@@ -262,9 +256,8 @@ static int indexOfEqual(final String token) {
* }
*
*
- * with "partial matching" turned on, {@code -de} only matches the {@code "debug"} option. However, with
- * "partial matching" disabled, {@code -de} would enable both {@code debug} as well as {@code extract}
- * options.
+ * with "partial matching" turned on, {@code -de} only matches the {@code "debug"} option. However, with "partial matching" disabled, {@code -de} would
+ * enable both {@code debug} as well as {@code extract} options.
*/
public DefaultParser() {
this.allowPartialMatching = true;
@@ -277,20 +270,20 @@ public DefaultParser() {
*
* By "partial matching" we mean that given the following code:
*
+ *
* {@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."));
+ * 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."));
* }
*
*
- * with "partial matching" turned on, {@code -de} only matches the {@code "debug"} option. However, with
- * "partial matching" disabled, {@code -de} would enable both {@code debug} as well as {@code extract}
- * options.
+ * with "partial matching" turned on, {@code -de} only matches the {@code "debug"} option. However, with "partial matching" disabled, {@code -de} would
+ * enable both {@code debug} as well as {@code extract} options.
*
*
- * @param allowPartialMatching if partial matching of long options shall be enabled
+ * @param allowPartialMatching if partial matching of long options shall be enabled.
*/
public DefaultParser(final boolean allowPartialMatching) {
this.allowPartialMatching = allowPartialMatching;
@@ -299,11 +292,10 @@ public DefaultParser(final boolean allowPartialMatching) {
}
/**
- * Creates a new DefaultParser instance with the specified partial matching and quote
- * stripping policy.
+ * Creates a new DefaultParser instance with the specified partial matching and quote stripping policy.
*
- * @param allowPartialMatching if partial matching of long options shall be enabled
- * @param stripLeadingAndTrailingQuotes if balanced outer double quoutes should be stripped
+ * @param allowPartialMatching if partial matching of long options shall be enabled.
+ * @param stripLeadingAndTrailingQuotes if balanced outer double quoutes should be stripped.
*/
private DefaultParser(final boolean allowPartialMatching, final Boolean stripLeadingAndTrailingQuotes, final Consumer deprecatedHandler) {
this.allowPartialMatching = allowPartialMatching;
@@ -314,7 +306,7 @@ private DefaultParser(final boolean allowPartialMatching, final Boolean stripLea
/**
* Adds token to command line {@link CommandLine#addArg(String)}.
*
- * @param token the unrecognized option/argument.
+ * @param token The unrecognized option/argument.
* @since 1.10.0
*/
protected void addArg(final String token) {
@@ -348,7 +340,7 @@ protected void checkRequiredOptions() throws MissingOptionException {
/**
* Searches for a prefix that is the long name of an option (-Xmx512m).
*
- * @param token
+ * @param token The command line token to test.
*/
private String getLongPrefix(final String token) {
final String t = Util.stripLeadingHyphens(token);
@@ -367,8 +359,8 @@ private String getLongPrefix(final String token) {
/**
* Gets 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.
+ * @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 getMatchingLongOptions(final String token) {
if (allowPartialMatching) {
@@ -383,19 +375,16 @@ private List getMatchingLongOptions(final String token) {
/**
* Breaks {@code token} into its constituent parts using the following algorithm.
- *
*
* ignore the first character ("- ")
* for each remaining character check if an {@link Option} exists with that id.
- * if an {@link Option} does exist then add that character prepended with "- " to the list of processed
- * tokens.
- * 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.
- * if an {@link Option} does NOT exist AND {@code stopAtNonOption} IS set then add the
- * special token "-- " followed by the remaining characters and also the remaining tokens directly to the
- * processed tokens list.
- * if an {@link Option} does NOT exist AND {@code stopAtNonOption} IS NOT set then add
- * that character prepended with "- ".
+ * if an {@link Option} does exist then add that character prepended with "- " to the list of processed tokens.
+ * 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.
+ * if an {@link Option} does NOT exist AND {@code stopAtNonOption} IS set then add the special token
+ * "-- " followed by the remaining characters and also the remaining tokens directly to the processed tokens list.
+ * if an {@link Option} does NOT exist AND {@code stopAtNonOption} IS NOT set then add that character
+ * prepended with "- ".
*
*
* @param token The current token to be burst at the first non-Option encountered.
@@ -419,11 +408,12 @@ protected void handleConcatenatedOptions(final String token) throws ParseExcepti
/**
* Handles the following tokens:
+ *
*
* --L --L=V --L V --l
*
*
- * @param token the command line token to handle.
+ * @param token The command line token to handle.
*/
private void handleLongOption(final String token) throws ParseException {
if (indexOfEqual(token) == -1) {
@@ -435,11 +425,12 @@ private void handleLongOption(final String token) throws ParseException {
/**
* Handles the following tokens:
+ *
*
* --L=V -L=V --l=V -l=V
*
*
- * @param token the command line token to handle.
+ * @param token The command line token to handle.
*/
private void handleLongOptionWithEqual(final String token) throws ParseException {
final int pos = indexOfEqual(token);
@@ -470,7 +461,7 @@ private void handleLongOptionWithEqual(final String token) throws ParseException
* --L -L --l -l
*
*
- * @param token the command line token to handle.
+ * @param token The command line token to handle.
*/
private void handleLongOptionWithoutEqual(final String token) throws ParseException {
final List matchingOpts = getMatchingLongOptions(token);
@@ -514,7 +505,6 @@ private void handleProperties(final Properties properties) throws ParseException
if (!cmd.hasOption(option) && !selected) {
// get the value from the properties
final String value = properties.getProperty(option);
-
if (opt.hasArg()) {
if (opt.isValuesEmpty()) {
opt.processValue(stripLeadingAndTrailingQuotesDefaultOff(value));
@@ -531,13 +521,14 @@ private void handleProperties(final Properties properties) throws ParseException
/**
* Handles the following tokens:
+ *
*
* -S -SV -S V -S=V -S1S2 -S1S2 V -SV1=V2
*
* -L -LV -L V -L=V -l
*
*
- * @param hyphenToken the command line token to handle.
+ * @param hyphenToken The command line token to handle.
*/
private void handleShortAndLongOption(final String hyphenToken) throws ParseException {
final String token = Util.stripLeadingHyphens(hyphenToken);
@@ -559,7 +550,6 @@ private void handleShortAndLongOption(final String hyphenToken) throws ParseExce
} else {
// look for a long prefix (-Xmx512m)
final String opt = getLongPrefix(token);
-
if (opt != null && options.getOption(opt).acceptsArg()) {
handleOption(options.getOption(opt));
currentOption.processValue(stripLeadingAndTrailingQuotesDefaultOff(token.substring(opt.length())));
@@ -578,7 +568,6 @@ private void handleShortAndLongOption(final String hyphenToken) throws ParseExce
// equal sign found (-xxx=yyy)
final String opt = token.substring(0, pos);
final String value = token.substring(pos + 1);
-
if (opt.length() == 1) {
// -S=V
final Option option = options.getOption(opt);
@@ -605,7 +594,7 @@ private void handleShortAndLongOption(final String hyphenToken) throws ParseExce
/**
* Handles any command line token.
*
- * @param token the command line token to handle.
+ * @param token The command line token to handle.
* @throws ParseException
*/
private void handleToken(final String token) throws ParseException {
@@ -631,11 +620,10 @@ private void handleToken(final String token) throws ParseException {
}
/**
- * 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.
+ * @param token The command line token to handle.
* @throws ParseException if parsing should fail.
* @since 1.10.0
*/
@@ -655,7 +643,7 @@ protected void handleUnknownToken(final String token) throws ParseException {
/**
* Tests if the token is a valid argument.
*
- * @param token
+ * @param token The command line token to test.
*/
private boolean isArgument(final String token) {
return !isOption(token) || isNegativeNumber(token);
@@ -663,6 +651,8 @@ private boolean isArgument(final String token) {
/**
* Tests if the specified token is a Java-like property (-Dkey=value).
+ *
+ * @param token The command line token to test.
*/
private boolean isJavaProperty(final String token) {
final String opt = token.isEmpty() ? null : token.substring(0, 1);
@@ -673,7 +663,7 @@ private boolean isJavaProperty(final String token) {
/**
* Tests if the token looks like a long option.
*
- * @param token
+ * @param token The command line token to test.
*/
private boolean isLongOption(final String token) {
if (token == null || !token.startsWith(OptionFormatter.DEFAULT_OPT_PREFIX) || token.length() == 1) {
@@ -695,7 +685,7 @@ private boolean isLongOption(final String token) {
/**
* Tests if the token is a negative number.
*
- * @param token
+ * @param token The command line token to test.
*/
private boolean isNegativeNumber(final String token) {
try {
@@ -709,7 +699,7 @@ private boolean isNegativeNumber(final String token) {
/**
* Tests if the token looks like an option.
*
- * @param token
+ * @param token The command line token to test.
*/
private boolean isOption(final String token) {
return isLongOption(token) || isShortOption(token);
@@ -718,7 +708,7 @@ private boolean isOption(final String token) {
/**
* Tests if the token looks like a short option.
*
- * @param token
+ * @param token The command line token to test.
*/
private boolean isShortOption(final String token) {
// short options (-S, -SV, -S=V, -SV1=V2, -S1S2)
@@ -738,12 +728,11 @@ private boolean isShortOption(final String token) {
/**
* Parses the arguments according to the specified options and properties.
*
- * @param options the specified Options
- * @param properties command line option name-value pairs
+ * @param options The specified Options.
+ * @param properties command line option name-value pairs.
* @param nonOptionAction see {@link NonOptionAction}.
- * @param arguments the command line arguments
- *
- * @return the list of atomic option and value tokens.
+ * @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.
* @since 1.10.0
*/
@@ -778,6 +767,14 @@ public CommandLine parse(final Options options, final String[] arguments) throws
}
/**
+ * Parses the arguments according to the specified options and properties.
+ *
+ * @param options The specified Options.
+ * @param arguments The command line arguments.
+ * @param stopAtNonOption if {@code true} an unrecognized argument stops the parsing and the remaining arguments are added to the {@link CommandLine}s args
+ * list. If {@code false} 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.
* @see #parse(Options, Properties, NonOptionAction, String[])
*/
@Override
@@ -788,10 +785,10 @@ public CommandLine parse(final Options options, final String[] arguments, final
/**
* Parses 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.
+ * @return The list of atomic option and value tokens.
* @throws ParseException if there are any problems encountered while parsing the command line tokens.
*/
public CommandLine parse(final Options options, final String[] arguments, final Properties properties) throws ParseException {
@@ -801,26 +798,24 @@ public CommandLine parse(final Options options, final String[] arguments, final
/**
* Parses 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} an unrecognized argument stops the parsing and the remaining arguments
- * are added to the {@link CommandLine}s args list. If {@code false} an unrecognized argument triggers a
- * ParseException.
- * @return the list of atomic option and value tokens.
+ * @param options The specified Options.
+ * @param arguments The command line arguments.
+ * @param properties command line option name-value pairs.
+ * @param stopAtNonOption if {@code true} an unrecognized argument stops the parsing and the remaining arguments are added to the {@link CommandLine}s args
+ * list. If {@code false} 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.
* @see #parse(Options, Properties, NonOptionAction, String[])
*/
public CommandLine parse(final Options options, final String[] arguments, final Properties properties, final boolean stopAtNonOption)
- throws ParseException {
+ throws ParseException {
return parse(options, properties, stopAtNonOption ? NonOptionAction.STOP : NonOptionAction.THROW, arguments);
}
/**
- * Strips balanced leading and trailing quotes if the stripLeadingAndTrailingQuotes is set
- * If stripLeadingAndTrailingQuotes is null, then do not strip
+ * Strips balanced leading and trailing quotes if the stripLeadingAndTrailingQuotes is set If stripLeadingAndTrailingQuotes is null, then do not strip
*
- * @param token a string.
+ * @param token A string.
* @return token with the quotes stripped (if set).
*/
private String stripLeadingAndTrailingQuotesDefaultOff(final String token) {
@@ -831,10 +826,9 @@ private String stripLeadingAndTrailingQuotesDefaultOff(final String token) {
}
/**
- * Strips balanced leading and trailing quotes if the stripLeadingAndTrailingQuotes is set
- * If stripLeadingAndTrailingQuotes is null, then do not strip
+ * Strips balanced leading and trailing quotes if the stripLeadingAndTrailingQuotes is set If stripLeadingAndTrailingQuotes is null, then do not strip
*
- * @param token a string.
+ * @param token A string.
* @return token with the quotes stripped (if set).
*/
private String stripLeadingAndTrailingQuotesDefaultOn(final String token) {
@@ -847,7 +841,7 @@ private String stripLeadingAndTrailingQuotesDefaultOn(final String token) {
/**
* Removes the option or its group from the list of expected elements.
*
- * @param option
+ * @param option The option to remove from the list of expected elements.
*/
private void updateRequiredOptions(final Option option) throws AlreadySelectedException {
if (option.isRequired()) {
diff --git a/src/main/java/org/apache/commons/cli/DeprecatedAttributes.java b/src/main/java/org/apache/commons/cli/DeprecatedAttributes.java
index b4ec5f35a..3d19a2b79 100644
--- a/src/main/java/org/apache/commons/cli/DeprecatedAttributes.java
+++ b/src/main/java/org/apache/commons/cli/DeprecatedAttributes.java
@@ -73,7 +73,7 @@ public DeprecatedAttributes get() {
/**
* Sets the description.
*
- * @param description the description.
+ * @param description The description.
* @return {@code this} instance.
*/
public Builder setDescription(final String description) {
@@ -96,7 +96,7 @@ public Builder setForRemoval(final boolean forRemoval) {
/**
* Sets the version in which the option became deprecated.
*
- * @param since the version in which the option became deprecated.
+ * @param since The version in which the option became deprecated.
* @return {@code this} instance.
*/
public Builder setSince(final String since) {
@@ -118,7 +118,7 @@ public Builder setSince(final String since) {
/**
* Creates a new builder.
*
- * @return a new builder.
+ * @return A new builder.
*/
public static Builder builder() {
return new Builder();
@@ -149,7 +149,7 @@ private DeprecatedAttributes(final String description, final String since, final
/**
* Gets the descriptions.
*
- * @return the descriptions.
+ * @return The descriptions.
*/
public String getDescription() {
return description;
@@ -158,7 +158,7 @@ public String getDescription() {
/**
* Gets version in which the option became deprecated.
*
- * @return the version in which the option became deprecated.
+ * @return The version in which the option became deprecated.
*/
public String getSince() {
return since;
diff --git a/src/main/java/org/apache/commons/cli/GnuParser.java b/src/main/java/org/apache/commons/cli/GnuParser.java
index 6d2b8715e..7c5750927 100644
--- a/src/main/java/org/apache/commons/cli/GnuParser.java
+++ b/src/main/java/org/apache/commons/cli/GnuParser.java
@@ -50,7 +50,7 @@ public GnuParser() {
* @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.
+ * @return A String array of the flattened arguments.
*/
@Override
protected String[] flatten(final Options options, final String[] arguments, final boolean stopAtNonOption) {
diff --git a/src/main/java/org/apache/commons/cli/HelpFormatter.java b/src/main/java/org/apache/commons/cli/HelpFormatter.java
index fb9da62e9..361788054 100644
--- a/src/main/java/org/apache/commons/cli/HelpFormatter.java
+++ b/src/main/java/org/apache/commons/cli/HelpFormatter.java
@@ -44,9 +44,9 @@ Licensed to the Apache Software Foundation (ASF) under one or more
*
*
* 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("help").create('h'));
+ * options.addOption(Option.builder("f").longOpt("file").desc("The file to be processed").hasArg().argName("FILE").required().get());
+ * options.addOption(Option.builder("v").longOpt("version").desc("Print the version of the application").get());
+ * options.addOption(Option.builder("h").longOpt("help").get());
*
* String header = "Do something useful with an input file\n\n";
* String footer = "\nPlease report issues at https://example.com/issues";
@@ -67,6 +67,7 @@ Licensed to the Apache Software Foundation (ASF) under one or more
*
* Please report issues at https://example.com/issues
* }
+ *
* @deprecated Use {@link org.apache.commons.cli.help.HelpFormatter}.
*/
@Deprecated
@@ -114,7 +115,7 @@ public HelpFormatter get() {
/**
* Sets the output PrintWriter, defaults to wrapping {@link System#out}.
*
- * @param printWriter the output PrintWriter, not null.
+ * @param printWriter The output PrintWriter, not null.
* @return {@code this} instance.
*/
public Builder setPrintWriter(final PrintWriter printWriter) {
@@ -146,6 +147,7 @@ public Builder setShowDeprecated(final Function deprecatedFormat
/**
* Sets whether to show the date the option was first added.
+ *
* @param showSince if @{code true} the date the options was first added will be shown.
* @return this builder.
* @since 1.9.0
@@ -170,7 +172,7 @@ private static final class OptionComparator implements Comparator , Seria
*
* @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
+ * @return A negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than
* the second.
*/
@Override
@@ -219,7 +221,7 @@ public int compare(final Option opt1, final Option opt2) {
/**
* Creates a new builder.
*
- * @return a new builder.
+ * @return A new builder.
* @since 1.7.0
*/
public static Builder builder() {
@@ -232,8 +234,9 @@ private static PrintWriter createDefaultPrintWriter() {
/**
* Gets the option description or an empty string if the description is {@code null}.
+ *
* @param option The option to get the description from.
- * @return the option description or an empty string if the description is {@code null}.
+ * @return The option description or an empty string if the description is {@code null}.
* @since 1.8.0
*/
public static String getDescription(final Option option) {
@@ -339,6 +342,7 @@ public HelpFormatter() {
/**
* Constructs a new instance.
+ *
* @param printWriter TODO
*/
private HelpFormatter(final Function deprecatedFormatFunction, final PrintWriter printWriter, final boolean showSince) {
@@ -352,8 +356,8 @@ private HelpFormatter(final Function deprecatedFormatFunction, f
/**
* Appends the usage clause for an Option to a StringBuffer.
*
- * @param buff the StringBuffer to append to
- * @param option the Option to append
+ * @param buff The StringBuffer to append to
+ * @param option The Option to append
* @param required whether the Option is required or not
*/
private void appendOption(final StringBuilder buff, final Option option, final boolean required) {
@@ -380,8 +384,8 @@ private void appendOption(final StringBuilder buff, final Option option, final b
* 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 StringBuilder to append to
- * @param optionGroup the group to append
+ * @param buff The StringBuilder to append to
+ * @param optionGroup The group to append
* @see #appendOption(StringBuilder,Option,boolean)
*/
private void appendOptionGroup(final StringBuilder buff, final OptionGroup optionGroup) {
@@ -411,10 +415,10 @@ private void appendOptionGroup(final StringBuilder buff, final OptionGroup optio
* @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
- * @return the StringBuffer with the rendered Options contents.
- * @throws IOException if an I/O error occurs.
+ * @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.
+ * @throws IOException Thrown if an I/O error occurs.
*/
A appendOptions(final A sb, final int width, final Options options, final int leftPad, final int descPad) throws IOException {
final String lpad = createPadding(leftPad);
@@ -497,8 +501,8 @@ A appendOptions(final A sb, final int width, final Option
* @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.
- * @return the StringBuffer with the rendered Options contents.
- * @throws IOException if an I/O error occurs.
+ * @return The StringBuffer with the rendered Options contents.
+ * @throws IOException Thrown if an I/O error occurs.
*/
A appendWrappedText(final A appendable, final int width, final int nextLineTabStop, final String text) throws IOException {
if (width <= 0) {
@@ -592,7 +596,7 @@ protected int findWrapPos(final String text, final int width, final int startPos
/**
* Gets the 'argName'.
*
- * @return the 'argName'
+ * @return The 'argName'
*/
public String getArgName() {
return defaultArgName;
@@ -601,7 +605,7 @@ public String getArgName() {
/**
* Gets the 'descPadding'.
*
- * @return the 'descPadding'
+ * @return The 'descPadding'
*/
public int getDescPadding() {
return defaultDescPad;
@@ -610,7 +614,7 @@ public int getDescPadding() {
/**
* Gets the 'leftPadding'.
*
- * @return the 'leftPadding'
+ * @return The 'leftPadding'
*/
public int getLeftPadding() {
return defaultLeftPad;
@@ -619,7 +623,7 @@ public int getLeftPadding() {
/**
* Gets the 'longOptPrefix'.
*
- * @return the 'longOptPrefix'
+ * @return The 'longOptPrefix'
*/
public String getLongOptPrefix() {
return defaultLongOptPrefix;
@@ -628,7 +632,7 @@ public String getLongOptPrefix() {
/**
* Gets the separator displayed between a long option and its value.
*
- * @return the separator
+ * @return The separator
* @since 1.3
*/
public String getLongOptSeparator() {
@@ -638,7 +642,7 @@ public String getLongOptSeparator() {
/**
* Gets the 'newLine'.
*
- * @return the 'newLine'
+ * @return The 'newLine'
*/
public String getNewLine() {
return defaultNewLine;
@@ -648,7 +652,7 @@ public String getNewLine() {
* 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
+ * @return The {@link Comparator} currently in use to sort the options
* @since 1.2
*/
public Comparator getOptionComparator() {
@@ -658,7 +662,7 @@ public Comparator getOptionComparator() {
/**
* Gets the 'optPrefix'.
*
- * @return the 'optPrefix'
+ * @return The 'optPrefix'
*/
public String getOptPrefix() {
return defaultOptPrefix;
@@ -667,7 +671,7 @@ public String getOptPrefix() {
/**
* Gets the 'syntaxPrefix'.
*
- * @return the 'syntaxPrefix'
+ * @return The 'syntaxPrefix'
*/
public String getSyntaxPrefix() {
return defaultSyntaxPrefix;
@@ -676,7 +680,7 @@ public String getSyntaxPrefix() {
/**
* Gets the 'width'.
*
- * @return the 'width'
+ * @return The 'width'
*/
public int getWidth() {
return defaultWidth;
@@ -686,11 +690,11 @@ public int getWidth() {
* Prints the help for {@code options} with the specified command line syntax. This method prints help information
* to {@link System#out} by default.
*
- * @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 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
*/
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);
@@ -700,11 +704,11 @@ public void printHelp(final int width, final String cmdLineSyntax, final String
* Prints the help for {@code options} with the specified command line syntax. This method prints help information
* to {@link System#out} by default.
*
- * @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 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
*/
public void printHelp(final int width, final String cmdLineSyntax, final String header, final Options options, final String footer,
@@ -717,14 +721,14 @@ public void printHelp(final int width, final String cmdLineSyntax, final String
/**
* Prints the help for {@code options} 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 footer the banner to display at the end of the help
+ * @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 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,
@@ -735,14 +739,14 @@ public void printHelp(final PrintWriter pw, final int width, final String cmdLin
/**
* Prints the help for {@code options} 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 footer the banner to display at the end of the help
+ * @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 footer The banner to display at the end of the help
* @param autoUsage whether to print an automatically generated usage statement
* @throws IllegalStateException if there is no room to print a line
*/
@@ -769,8 +773,8 @@ public void printHelp(final PrintWriter pw, final int width, final String cmdLin
* Prints the help for {@code options} with the specified command line syntax. This method prints help information
* to {@link System#out} by default.
*
- * @param cmdLineSyntax the syntax for this application
- * @param options the Options instance
+ * @param cmdLineSyntax The syntax for this application
+ * @param options The Options instance
*/
public void printHelp(final String cmdLineSyntax, final Options options) {
printHelp(getWidth(), cmdLineSyntax, null, options, null, false);
@@ -780,8 +784,8 @@ public void printHelp(final String cmdLineSyntax, final Options options) {
* Prints the help for {@code options} with the specified command line syntax. This method prints help information
* to {@link System#out} by default.
*
- * @param cmdLineSyntax the syntax for this application
- * @param options the Options instance
+ * @param cmdLineSyntax The syntax for this application
+ * @param options The Options instance
* @param autoUsage whether to print an automatically generated usage statement
*/
public void printHelp(final String cmdLineSyntax, final Options options, final boolean autoUsage) {
@@ -792,10 +796,10 @@ public void printHelp(final String cmdLineSyntax, final Options options, final b
* Prints the help for {@code options} with the specified command line syntax. This method prints help information
* to {@link System#out} by default.
*
- * @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 cmdLineSyntax The syntax for this application
+ * @param header The banner to display at the beginning of the help
+ * @param options The Options instance
+ * @param footer The banner to display at the end of the help
*/
public void printHelp(final String cmdLineSyntax, final String header, final Options options, final String footer) {
printHelp(cmdLineSyntax, header, options, footer, false);
@@ -805,10 +809,10 @@ public void printHelp(final String cmdLineSyntax, final String header, final Opt
* Prints the help for {@code options} with the specified command line syntax. This method prints help information
* to {@link System#out} by default.
*
- * @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 cmdLineSyntax The syntax for this application
+ * @param header The banner to display at the beginning of the help
+ * @param options The Options instance
+ * @param footer The banner to display at the end of the help
* @param autoUsage whether to print an automatically generated usage statement
*/
public void printHelp(final String cmdLineSyntax, final String header, final Options options, final String footer, final boolean autoUsage) {
@@ -822,8 +826,8 @@ public void printHelp(final String cmdLineSyntax, final String header, final Opt
* @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) {
try {
@@ -923,9 +927,9 @@ public void printWrapped(final PrintWriter pw, final int width, final String tex
* @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
- * @return the StringBuffer with the rendered Options contents.
+ * @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) {
try {
@@ -943,7 +947,7 @@ protected StringBuffer renderOptions(final StringBuffer sb, final int width, fin
* @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.
- * @return the StringBuffer with the rendered Options contents.
+ * @return The StringBuffer with the rendered Options contents.
*/
protected StringBuffer renderWrappedText(final StringBuffer sb, final int width, final int nextLineTabStop, final String text) {
try {
@@ -1002,7 +1006,7 @@ protected String rtrim(final String s) {
/**
* Sets the 'argName'.
*
- * @param name the new value of 'argName'
+ * @param name The new value of 'argName'
*/
public void setArgName(final String name) {
this.defaultArgName = name;
@@ -1011,7 +1015,7 @@ public void setArgName(final String name) {
/**
* Sets the 'descPadding'.
*
- * @param padding the new value of 'descPadding'
+ * @param padding The new value of 'descPadding'
*/
public void setDescPadding(final int padding) {
this.defaultDescPad = padding;
@@ -1020,7 +1024,7 @@ public void setDescPadding(final int padding) {
/**
* Sets the 'leftPadding'.
*
- * @param padding the new value of 'leftPadding'
+ * @param padding The new value of 'leftPadding'
*/
public void setLeftPadding(final int padding) {
this.defaultLeftPad = padding;
@@ -1029,7 +1033,7 @@ public void setLeftPadding(final int padding) {
/**
* Sets the 'longOptPrefix'.
*
- * @param prefix the new value of 'longOptPrefix'
+ * @param prefix The new value of 'longOptPrefix'
*/
public void setLongOptPrefix(final String prefix) {
this.defaultLongOptPrefix = prefix;
@@ -1039,7 +1043,7 @@ public void setLongOptPrefix(final String prefix) {
* Sets 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 '='.
+ * @param longOptSeparator The separator, typically ' ' or '='.
* @since 1.3
*/
public void setLongOptSeparator(final String longOptSeparator) {
@@ -1049,7 +1053,7 @@ public void setLongOptSeparator(final String longOptSeparator) {
/**
* Sets the 'newLine'.
*
- * @param newline the new value of 'newLine'
+ * @param newline The new value of 'newLine'
*/
public void setNewLine(final String newline) {
this.defaultNewLine = newline;
@@ -1059,7 +1063,7 @@ public void setNewLine(final String newline) {
* Sets 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
+ * @param comparator The {@link Comparator} to use for sorting the options
* @since 1.2
*/
public void setOptionComparator(final Comparator comparator) {
@@ -1069,7 +1073,7 @@ public void setOptionComparator(final Comparator comparator) {
/**
* Sets the 'optPrefix'.
*
- * @param prefix the new value of 'optPrefix'
+ * @param prefix The new value of 'optPrefix'
*/
public void setOptPrefix(final String prefix) {
this.defaultOptPrefix = prefix;
@@ -1078,7 +1082,7 @@ public void setOptPrefix(final String prefix) {
/**
* Sets the 'syntaxPrefix'.
*
- * @param prefix the new value of 'syntaxPrefix'
+ * @param prefix The new value of 'syntaxPrefix'
*/
public void setSyntaxPrefix(final String prefix) {
this.defaultSyntaxPrefix = prefix;
@@ -1087,7 +1091,7 @@ public void setSyntaxPrefix(final String prefix) {
/**
* Sets the 'width'.
*
- * @param width the new value of 'width'
+ * @param width The new value of 'width'
*/
public void setWidth(final int width) {
this.defaultWidth = width;
diff --git a/src/main/java/org/apache/commons/cli/MissingArgumentException.java b/src/main/java/org/apache/commons/cli/MissingArgumentException.java
index 5deffa672..9ddb30e06 100644
--- a/src/main/java/org/apache/commons/cli/MissingArgumentException.java
+++ b/src/main/java/org/apache/commons/cli/MissingArgumentException.java
@@ -21,6 +21,7 @@ Licensed to the Apache Software Foundation (ASF) under one or more
* Thrown when an option requiring an argument is not provided with an argument.
*/
public class MissingArgumentException extends ParseException {
+
/**
* This exception {@code serialVersionUID}.
*/
@@ -32,7 +33,7 @@ public class MissingArgumentException extends ParseException {
/**
* Constructs a new {@code MissingArgumentException} with the specified detail message.
*
- * @param option the option requiring an argument
+ * @param option The option requiring an argument
* @since 1.2
*/
public MissingArgumentException(final Option option) {
@@ -43,7 +44,7 @@ public MissingArgumentException(final Option option) {
/**
* Constructs a new {@code MissingArgumentException} with the specified detail message.
*
- * @param message the detail message
+ * @param message The detail message
*/
public MissingArgumentException(final String message) {
super(message);
@@ -52,7 +53,7 @@ public MissingArgumentException(final String message) {
/**
* Gets the option requiring an argument that wasn't provided on the command line.
*
- * @return the related option
+ * @return The related option
* @since 1.2
*/
public Option getOption() {
diff --git a/src/main/java/org/apache/commons/cli/MissingOptionException.java b/src/main/java/org/apache/commons/cli/MissingOptionException.java
index 7ab196564..23e73a10f 100644
--- a/src/main/java/org/apache/commons/cli/MissingOptionException.java
+++ b/src/main/java/org/apache/commons/cli/MissingOptionException.java
@@ -30,7 +30,7 @@ public class MissingOptionException extends ParseException {
/**
* Build the exception message from the specified list of options.
*
- * @param missingOptions the list of missing options and groups
+ * @param missingOptions The list of missing options and groups
*/
private static String createMessage(final List> missingOptions) {
final StringBuilder buf = new StringBuilder("Missing required option");
@@ -45,7 +45,7 @@ private static String createMessage(final List> missingOptions) {
/**
* Constructs a new {@code MissingSelectedException} with the specified list of missing options.
*
- * @param missingOptions the list of missing options and groups
+ * @param missingOptions The list of missing options and groups
* @since 1.2
*/
public MissingOptionException(final List missingOptions) {
@@ -56,7 +56,7 @@ public MissingOptionException(final List missingOptions) {
/**
* Constructs a new {@code MissingSelectedException} with the specified detail message.
*
- * @param message the detail message
+ * @param message The detail message
*/
public MissingOptionException(final String message) {
super(message);
@@ -65,7 +65,7 @@ public MissingOptionException(final String message) {
/**
* Gets 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
+ * @return The missing options, consisting of String instances for simple options, and OptionGroup instances for
* required option groups.
* @since 1.2
*/
diff --git a/src/main/java/org/apache/commons/cli/Option.java b/src/main/java/org/apache/commons/cli/Option.java
index 3f16186ab..6062d9d80 100644
--- a/src/main/java/org/apache/commons/cli/Option.java
+++ b/src/main/java/org/apache/commons/cli/Option.java
@@ -60,8 +60,8 @@ public static final class Builder implements Supplier {
/**
* Returns the input Class or the default type (String) if null.
*
- * @param type the candidate Class.
- * @return the input Class or the default type (String) if null.
+ * @param type The candidate Class.
+ * @return The input Class or the default type (String) if null.
*/
private static Class> toType(final Class> type) {
return type != null ? type : DEFAULT_TYPE;
@@ -116,7 +116,7 @@ private Builder(final String option) throws IllegalArgumentException {
/**
* Sets the display name for the argument value.
*
- * @param argName the display name for the argument value.
+ * @param argName The display name for the argument value.
* @return {@code this} instance..
*/
public Builder argName(final String argName) {
@@ -127,7 +127,7 @@ public Builder argName(final String argName) {
/**
* Constructs an Option with the values declared by this {@link Builder}.
*
- * @return the new {@link Option}.
+ * @return The new {@link Option}.
* @throws IllegalArgumentException if neither {@code opt} or {@code longOpt} has been set.
* @deprecated Use {@link #get()}.
*/
@@ -142,7 +142,7 @@ public Option build() {
* Note: See {@link TypeHandler} for serialization discussion.
*
*
- * @param converter the Converter to use.
+ * @param converter The Converter to use.
* @return {@code this} instance..
* @since 1.7.0
*/
@@ -176,7 +176,7 @@ public Builder deprecated(final DeprecatedAttributes deprecated) {
/**
* Sets the description for this option.
*
- * @param description the description of the option.
+ * @param description The description of the option.
* @return {@code this} instance..
*/
public Builder desc(final String description) {
@@ -187,7 +187,7 @@ public Builder desc(final String description) {
/**
* Constructs an Option with the values declared by this {@link Builder}.
*
- * @return the new {@link Option}.
+ * @return The new {@link Option}.
* @throws IllegalStateException if neither {@code opt} or {@code longOpt} has been set.
*/
@Override
@@ -229,7 +229,7 @@ public Builder hasArgs() {
/**
* Sets the long name of the Option.
*
- * @param longOption the long name of the Option
+ * @param longOption The long name of the Option
* @return this builder.
*/
public Builder longOpt(final String longOption) {
@@ -240,7 +240,7 @@ public Builder longOpt(final String longOption) {
/**
* Sets the number of argument values the Option can take.
*
- * @param argCount the number of argument values
+ * @param argCount The number of argument values
* @return this builder.
*/
public Builder numberOfArgs(final int argCount) {
@@ -251,7 +251,7 @@ public Builder numberOfArgs(final int argCount) {
/**
* Sets the name of the Option.
*
- * @param option the name of the Option.
+ * @param option The name of the Option.
* @return this builder.
* @throws IllegalArgumentException if there are any non valid Option characters in {@code opt}.
* @since 1.5.0
@@ -297,7 +297,7 @@ public Builder required(final boolean required) {
/** Sets the version number when this option was first defined."
*
- * @param since the version number when this option was first defined.
+ * @param since The version number when this option was first defined.
* @return this builder.
*/
public Builder since(final String since) {
@@ -308,7 +308,7 @@ public Builder since(final String since) {
/**
* Sets the type of the Option.
*
- * @param type the type of the Option.
+ * @param type The type of the Option.
* @return this builder.
*/
public Builder type(final Class> type) {
@@ -367,7 +367,7 @@ public Builder valueSeparator(final char valueSeparator) {
/**
* Returns a {@link Builder} to create an {@link Option} using descriptive methods.
*
- * @return a new {@link Builder} instance.
+ * @return A new {@link Builder} instance.
* @since 1.3
*/
public static Builder builder() {
@@ -378,7 +378,7 @@ public static Builder builder() {
* Returns a {@link Builder} to create an {@link Option} using descriptive methods.
*
* @param option short representation of the option.
- * @return a new {@link Builder} instance.
+ * @return A new {@link Builder} instance.
* @throws IllegalArgumentException if there are any non valid Option characters in {@code opt}.
* @since 1.3
*/
@@ -481,7 +481,7 @@ public Option(final String option, final String description) throws IllegalArgum
* Creates an Option using the specified parameters.
*
* @param option short representation of the option.
- * @param longOption the long representation of the option.
+ * @param longOption The long representation of the option.
* @param hasArg specifies whether the Option takes an argument or not.
* @param description describes the function of the option.
* @throws IllegalArgumentException if there are any non valid Option characters in {@code opt}.
@@ -525,7 +525,7 @@ private void add(final String value) {
/**
* 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.
+ * @param value The value to add.
* @return always throws an {@link UnsupportedOperationException}.
* @throws UnsupportedOperationException always.
* @deprecated Unused.
@@ -550,7 +550,7 @@ void clearValues() {
*
* After calling this method, it is very likely you will want to call clearValues().
*
- * @return a clone of this Option instance.
+ * @return A clone of this Option instance.
* @throws RuntimeException if a {@link CloneNotSupportedException} has been thrown by {@code super.clone()}.
*/
@Override
@@ -579,7 +579,7 @@ public boolean equals(final Object obj) {
/**
* Gets the display name for the argument value.
*
- * @return the display name for the argument value.
+ * @return The display name for the argument value.
*/
public String getArgName() {
return argName;
@@ -604,7 +604,7 @@ public int getArgs() {
/**
* Gets the value to type converter.
*
- * @return the value to type converter.
+ * @return The value to type converter.
* @since 1.7.0
*/
public Converter, ?> getConverter() {
@@ -633,7 +633,7 @@ public String getDescription() {
/**
* Gets 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.
+ * @return The id of this Option.
*/
public int getId() {
return getKey().charAt(0);
@@ -642,7 +642,7 @@ public int getId() {
/**
* Gets the 'unique' Option identifier. This is the option value if set or the long value if the options value is not set.
*
- * @return the 'unique' Option identifier.
+ * @return The 'unique' Option identifier.
* @since 1.7.0
*/
public String getKey() {
@@ -673,7 +673,8 @@ public String getOpt() {
/**
* Gets the version when this option was added.
- * @return the version when this option was added, or {@code null} if not set.
+ *
+ * @return The version when this option was added, or {@code null} if not set.
*/
public String getSince() {
return since;
@@ -691,7 +692,7 @@ public Object getType() {
/**
* Gets the specified value of this Option or {@code null} if there is no value.
*
- * @return the value/first value of this Option or {@code null} if there is no value.
+ * @return The value/first value of this Option or {@code null} if there is no value.
*/
public String getValue() {
return isValuesEmpty() ? null : values.get(0);
@@ -701,7 +702,7 @@ public String getValue() {
* Gets the specified value of this Option or {@code null} 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} if there is no value.
+ * @return The specified value of this Option or {@code null} if there is no value.
* @throws IndexOutOfBoundsException if index is less than 1 or greater than the number of the values for this Option.
*/
public String getValue(final int index) throws IndexOutOfBoundsException {
@@ -712,7 +713,7 @@ public String getValue(final int index) throws IndexOutOfBoundsException {
* Gets the value/first value of this Option or the {@code defaultValue} 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} if there are no values.
+ * @return The value/first value of this Option or the {@code defaultValue} if there are no values.
*/
public String getValue(final String defaultValue) {
final String value = getValue();
@@ -722,7 +723,7 @@ public String getValue(final String defaultValue) {
/**
* Gets the values of this Option as a String array or an empty array if there are no values.
*
- * @return the values of this Option as a String array or an empty array if there are no values.
+ * @return The values of this Option as a String array or an empty array if there are no values.
*/
public String[] getValues() {
return isValuesEmpty() ? null : values.toArray(EMPTY_STRING_ARRAY);
@@ -731,7 +732,7 @@ public String[] getValues() {
/**
* Gets the value separator character.
*
- * @return the value separator character.
+ * @return The value separator character.
*/
public char getValueSeparator() {
return valueSeparator;
@@ -740,7 +741,7 @@ public char getValueSeparator() {
/**
* Gets the values of this Option as a List. Will return an empty list if there are no values.
*
- * @return the values of this Option as a List or an empty List if there are no values.
+ * @return The values of this Option as a List or an empty List if there are no values.
*/
public List getValuesList() {
return values;
@@ -884,7 +885,7 @@ boolean requiresArg() {
/**
* Sets the display name for the argument value.
*
- * @param argName the display name for the argument value.
+ * @param argName The display name for the argument value.
*/
public void setArgName(final String argName) {
this.argName = argName;
@@ -893,7 +894,7 @@ public void setArgName(final String argName) {
/**
* Sets the number of argument values this Option can take.
*
- * @param num the number of argument values.
+ * @param num The number of argument values.
*/
public void setArgs(final int num) {
this.argCount = num;
@@ -922,7 +923,7 @@ public void setDescription(final String description) {
/**
* Sets the long name of this Option.
*
- * @param longOpt the long name of this Option.
+ * @param longOpt The long name of this Option.
*/
public void setLongOpt(final String longOpt) {
this.longOption = longOpt;
@@ -949,7 +950,7 @@ public void setRequired(final boolean required) {
/**
* Sets the type of this Option.
*
- * @param type the type of this Option.
+ * @param type The type of this Option.
* @since 1.3
*/
public void setType(final Class> type) {
@@ -962,7 +963,7 @@ public void setType(final Class> type) {
* Note: 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.
+ * @param type The type of this Option.
* @deprecated Since 1.3, use {@link #setType(Class)} instead.
*/
@Deprecated
@@ -999,7 +1000,7 @@ String toDeprecatedString() {
/**
* Creates a String suitable for debugging.
*
- * @return a String suitable for debugging.
+ * @return A String suitable for debugging.
*/
@Override
public String toString() {
diff --git a/src/main/java/org/apache/commons/cli/OptionBuilder.java b/src/main/java/org/apache/commons/cli/OptionBuilder.java
index 8b6ff0a9a..b21ee05b1 100644
--- a/src/main/java/org/apache/commons/cli/OptionBuilder.java
+++ b/src/main/java/org/apache/commons/cli/OptionBuilder.java
@@ -66,7 +66,7 @@ public final class OptionBuilder {
/**
* Creates an Option using the current settings.
*
- * @return the Option instance.
+ * @return The Option instance.
* @throws IllegalArgumentException if {@code longOpt} has not been set.
*/
public static Option create() throws IllegalArgumentException {
@@ -80,8 +80,8 @@ public static Option create() throws IllegalArgumentException {
/**
* Creates an Option using the current settings and with the specified Option {@code char}.
*
- * @param opt the character representation of the Option.
- * @return the Option instance.
+ * @param opt The character representation of the Option.
+ * @return The Option instance.
* @throws IllegalArgumentException if {@code opt} is not a valid character. See Option.
*/
public static Option create(final char opt) throws IllegalArgumentException {
@@ -91,8 +91,8 @@ public static Option create(final char opt) throws IllegalArgumentException {
/**
* Creates an Option using the current settings and with the specified Option {@code char}.
*
- * @param opt the {@code String} representation of the Option.
- * @return the Option instance.
+ * @param opt The {@code String} representation of the Option.
+ * @return The Option instance.
* @throws IllegalArgumentException if {@code opt} is not a valid character. See Option.
*/
public static Option create(final String opt) throws IllegalArgumentException {
@@ -120,7 +120,7 @@ public static Option create(final String opt) throws IllegalArgumentException {
/**
* The next Option created will require an argument value.
*
- * @return the OptionBuilder instance
+ * @return The OptionBuilder instance
*/
public static OptionBuilder hasArg() {
argCount = 1;
@@ -131,7 +131,7 @@ public static OptionBuilder hasArg() {
* The next Option created will require an argument value if {@code hasArg} is true.
*
* @param hasArg if true then the Option has an argument value.
- * @return the OptionBuilder instance.
+ * @return The OptionBuilder instance.
*/
public static OptionBuilder hasArg(final boolean hasArg) {
argCount = hasArg ? 1 : Option.UNINITIALIZED;
@@ -141,7 +141,7 @@ public static OptionBuilder hasArg(final boolean hasArg) {
/**
* The next Option created can have unlimited argument values.
*
- * @return the OptionBuilder instance.
+ * @return The OptionBuilder instance.
*/
public static OptionBuilder hasArgs() {
argCount = Option.UNLIMITED_VALUES;
@@ -151,8 +151,8 @@ public static OptionBuilder hasArgs() {
/**
* The next Option created can have {@code num} argument values.
*
- * @param num the number of args that the option can have.
- * @return the OptionBuilder instance.
+ * @param num The number of args that the option can have.
+ * @return The OptionBuilder instance.
*/
public static OptionBuilder hasArgs(final int num) {
argCount = num;
@@ -162,7 +162,7 @@ public static OptionBuilder hasArgs(final int num) {
/**
* The next Option can have an optional argument.
*
- * @return the OptionBuilder instance.
+ * @return The OptionBuilder instance.
*/
public static OptionBuilder hasOptionalArg() {
argCount = 1;
@@ -173,7 +173,7 @@ public static OptionBuilder hasOptionalArg() {
/**
* The next Option can have an unlimited number of optional arguments.
*
- * @return the OptionBuilder instance.
+ * @return The OptionBuilder instance.
*/
public static OptionBuilder hasOptionalArgs() {
argCount = Option.UNLIMITED_VALUES;
@@ -184,8 +184,8 @@ public static OptionBuilder hasOptionalArgs() {
/**
* 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.
- * @return the OptionBuilder instance.
+ * @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) {
argCount = numArgs;
@@ -196,7 +196,7 @@ public static OptionBuilder hasOptionalArgs(final int numArgs) {
/**
* The next Option created will be required.
*
- * @return the OptionBuilder instance.
+ * @return The OptionBuilder instance.
*/
public static OptionBuilder isRequired() {
required = true;
@@ -207,7 +207,7 @@ public static OptionBuilder isRequired() {
* The next Option created will be required if {@code required} is true.
*
* @param newRequired if true then the Option is required.
- * @return the OptionBuilder instance.
+ * @return The OptionBuilder instance.
*/
public static OptionBuilder isRequired(final boolean newRequired) {
required = newRequired;
@@ -231,8 +231,8 @@ private static void reset() {
/**
* The next Option created will have the specified argument value name.
*
- * @param name the name for the argument value.
- * @return the OptionBuilder instance.
+ * @param name The name for the argument value.
+ * @return The OptionBuilder instance.
*/
public static OptionBuilder withArgName(final String name) {
argName = name;
@@ -242,8 +242,8 @@ public static OptionBuilder withArgName(final String name) {
/**
* The next Option created will have the specified description
*
- * @param newDescription a description of the Option's purpose.
- * @return the OptionBuilder instance.
+ * @param newDescription A description of the Option's purpose.
+ * @return The OptionBuilder instance.
*/
public static OptionBuilder withDescription(final String newDescription) {
description = newDescription;
@@ -253,8 +253,8 @@ public static OptionBuilder withDescription(final String newDescription) {
/**
* The next Option created will have the following long option value.
*
- * @param newLongopt the long option value.
- * @return the OptionBuilder instance.
+ * @param newLongopt The long option value.
+ * @return The OptionBuilder instance.
*/
public static OptionBuilder withLongOpt(final String newLongopt) {
longOption = newLongopt;
@@ -264,8 +264,8 @@ public static OptionBuilder withLongOpt(final String newLongopt) {
/**
* The next Option created will have a value that will be an instance of {@code type}.
*
- * @param newType the type of the Options argument value.
- * @return the OptionBuilder instance.
+ * @param newType The type of the Options argument value.
+ * @return The OptionBuilder instance.
* @since 1.3
*/
public static OptionBuilder withType(final Class> newType) {
@@ -279,8 +279,8 @@ public static OptionBuilder withType(final Class> newType) {
* Note: 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.
+ * @param newType The type of the Options argument value.
+ * @return The OptionBuilder instance.
* @deprecated Since 1.3, use {@link #withType(Class)} instead.
*/
@Deprecated
@@ -301,7 +301,7 @@ public static OptionBuilder withType(final Object newType) {
* String propertyValue = opt.getValue(1);
*
*
- * @return the OptionBuilder instance.
+ * @return The OptionBuilder instance.
*/
public static OptionBuilder withValueSeparator() {
valueSeparator = Char.EQUAL;
@@ -323,7 +323,7 @@ public static OptionBuilder withValueSeparator() {
*
*
* @param sep The value separator to be used for the argument values.
- * @return the OptionBuilder instance.
+ * @return The OptionBuilder instance.
*/
public static OptionBuilder withValueSeparator(final char sep) {
valueSeparator = sep;
diff --git a/src/main/java/org/apache/commons/cli/OptionGroup.java b/src/main/java/org/apache/commons/cli/OptionGroup.java
index ed574dc10..ce5384f4d 100644
--- a/src/main/java/org/apache/commons/cli/OptionGroup.java
+++ b/src/main/java/org/apache/commons/cli/OptionGroup.java
@@ -54,7 +54,7 @@ public OptionGroup() {
/**
* Adds the given {@code Option} to this group.
*
- * @param option the option to add to this group.
+ * @param option The option to add to this group.
* @return this option group with the option added.
*/
public OptionGroup addOption(final Option option) {
@@ -65,7 +65,7 @@ public OptionGroup addOption(final Option option) {
/**
* Gets the names of the options in this group as a {@code Collection}.
*
- * @return the names of the options in this group as a {@code Collection}.
+ * @return The names of the options in this group as a {@code Collection}.
*/
public Collection getNames() {
// the key set is the collection of names
@@ -75,7 +75,7 @@ public Collection getNames() {
/**
* Gets the options in this group as a {@code Collection}.
*
- * @return the options in this group as a {@code Collection}.
+ * @return The options in this group as a {@code Collection}.
*/
public Collection getOptions() {
// the values are the collection of options
@@ -86,7 +86,8 @@ public Collection getOptions() {
* Gets the selected option name.
*
* If the selected option is deprecated no warning is logged .
- * @return the selected option name.
+ *
+ * @return The selected option name.
*/
public String getSelected() {
return selected;
@@ -105,6 +106,7 @@ public boolean isRequired() {
* Tests whether an option is selected.
*
* If an option is selected and is deprecated no warning is logged .
+ *
* @return whether whether an option is selected.
* @since 1.9.0
*/
@@ -125,7 +127,8 @@ public void setRequired(final boolean required) {
* Sets the selected option of this group to {@code name}.
*
* If the selected option is deprecated no warning is logged .
- * @param option the option that is selected.
+ *
+ * @param option The option that is selected.
* @throws AlreadySelectedException if an option from this group has already been selected.
*/
public void setSelected(final Option option) throws AlreadySelectedException {
@@ -146,7 +149,7 @@ public void setSelected(final Option option) throws AlreadySelectedException {
/**
* Returns the stringified version of this OptionGroup.
*
- * @return the stringified representation of this group.
+ * @return The stringified representation of this group.
*/
@Override
public String toString() {
diff --git a/src/main/java/org/apache/commons/cli/OptionValidator.java b/src/main/java/org/apache/commons/cli/OptionValidator.java
index 56852f20c..ab48847e7 100644
--- a/src/main/java/org/apache/commons/cli/OptionValidator.java
+++ b/src/main/java/org/apache/commons/cli/OptionValidator.java
@@ -21,11 +21,14 @@ Licensed to the Apache Software Foundation (ASF) under one or more
* Validates an Option string.
*/
final class OptionValidator {
- /* package private for testing access */
- /** The array of additional characters allowed as the first character in the option but not in the rest of the option */
- static final char[] ADDITIONAL_OPTION_CHARS = {'?', '@'};
- /** The array of additional characters allowed in the rest of the option but not in the first position */
- static final char[] ADDITIONAL_LONG_CHARS = {'-'};
+
+ /**
+ * The array of additional characters allowed as the first character in the option but not in the rest of the option. Package private for tests.
+ */
+ static final char[] ADDITIONAL_OPTION_CHARS = { '?', '@' };
+
+ /** The array of additional characters allowed in the rest of the option but not in the first position Package private for tests. */
+ static final char[] ADDITIONAL_LONG_CHARS = { '-' };
/**
* Returns whether the specified character is a valid character.
@@ -41,7 +44,8 @@ final class OptionValidator {
* isIdentifierIgnorable returns true for the character
* it is a hyphen/dash ('-')
*
- * @param c the character to validate
+ *
+ * @param c The character to validate
* @return true if {@code c} is a valid character letter.
*/
private static boolean isValidChar(final char c) {
@@ -62,7 +66,8 @@ private static boolean isValidChar(final char c) {
* isIdentifierIgnorable returns true for the character
* it is a question mark or 'at' sign ('?' or '@')
*
- * @param c the option to validate
+ *
+ * @param c The option to validate
* @return true if {@code c} is a letter, '?' or '@', otherwise false.
*/
private static boolean isValidOpt(final char c) {
@@ -71,8 +76,9 @@ private static boolean isValidOpt(final char c) {
/**
* Checks the char array for a matching char.
- * @param chars the char array to search
- * @param c the char to look for.
+ *
+ * @param chars The char array to search
+ * @param c The char to look for.
* @return {@code true} if {@code c} was in {@code ary}, {@code false} otherwise.
*/
private static boolean search(final char[] chars, final char c) {
@@ -92,8 +98,9 @@ private static boolean search(final char[] chars, final char c) {
* a single character {@code opt} that is either Chars.SP(special case), '?', '@' or a letter
* a multi character {@code opt} that only contains valid characters
*
- *
+ *
* A character is valid if any of the following conditions are true:
+ *
*
* it is a letter
* it is a currency symbol (such as '$')
@@ -105,8 +112,9 @@ private static boolean search(final char[] chars, final char c) {
* isIdentifierIgnorable returns true for the character
* it is a hyphen/dash ('-')
*
- *
+ *
* In case {@code opt} is {@code null} no further validation is performed.
+ *
*
* @param option The option string to validate, may be null.
* @throws IllegalArgumentException if the Option is not valid.
diff --git a/src/main/java/org/apache/commons/cli/Options.java b/src/main/java/org/apache/commons/cli/Options.java
index 7f0cda159..9088a389b 100644
--- a/src/main/java/org/apache/commons/cli/Options.java
+++ b/src/main/java/org/apache/commons/cli/Options.java
@@ -25,6 +25,7 @@ Licensed to the Apache Software Foundation (ASF) under one or more
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
+import java.util.stream.Collectors;
/**
* Main entry-point into the library.
@@ -67,8 +68,8 @@ public Options() {
/**
* Adds an option instance.
*
- * @param opt the option that is to be added.
- * @return the resulting Options instance.
+ * @param opt The option that is to be added.
+ * @return The resulting Options instance.
*/
public Options addOption(final Option opt) {
final String key = opt.getKey();
@@ -96,7 +97,7 @@ public Options addOption(final Option opt) {
* @param opt Short single-character name of the option.
* @param hasArg flag signaling if an argument is required after this option.
* @param description Self-documenting description.
- * @return the resulting Options instance.
+ * @return The resulting Options instance.
*/
public Options addOption(final String opt, final boolean hasArg, final String description) {
addOption(opt, null, hasArg, description);
@@ -111,7 +112,7 @@ public Options addOption(final String opt, final boolean hasArg, final String de
*
* @param opt Short single-character name of the option.
* @param description Self-documenting description.
- * @return the resulting Options instance.
+ * @return The resulting Options instance.
* @since 1.3
*/
public Options addOption(final String opt, final String description) {
@@ -129,7 +130,7 @@ public Options addOption(final String opt, final String description) {
* @param longOpt Long multi-character name of the option.
* @param hasArg flag signaling if an argument is required after this option.
* @param description Self-documenting description.
- * @return the resulting Options instance.
+ * @return The resulting Options instance.
*/
public Options addOption(final String opt, final String longOpt, final boolean hasArg, final String description) {
addOption(new Option(opt, longOpt, hasArg, description));
@@ -143,8 +144,8 @@ public Options addOption(final String opt, final String longOpt, final boolean h
* the given group are set to optional.
*
*
- * @param optionGroup the OptionGroup that is to be added.
- * @return the resulting Options instance.
+ * @param optionGroup The OptionGroup that is to be added.
+ * @return The resulting Options instance.
*/
public Options addOptionGroup(final OptionGroup optionGroup) {
if (optionGroup.isRequired()) {
@@ -167,7 +168,7 @@ public Options addOptionGroup(final OptionGroup optionGroup) {
* Adds options to this option. If any Option in {@code options} already exists
* in this Options an IllegalArgumentException is thrown.
*
- * @param options the options to add.
+ * @param options The options to add.
* @return The resulting Options instance.
* @since 1.7.0
*/
@@ -199,7 +200,7 @@ public Options addOptions(final Options options) {
* @param longOpt Long multi-character name of the option.
* @param hasArg flag signaling if an argument is required after this option.
* @param description Self-documenting description.
- * @return the resulting Options instance.
+ * @return The resulting Options instance.
* @since 1.4
*/
public Options addRequiredOption(final String opt, final String longOpt, final boolean hasArg, final String description) {
@@ -212,23 +213,22 @@ public Options addRequiredOption(final String opt, final String longOpt, final b
/**
* Gets the options with a long name starting with the name specified.
*
- * @param opt the partial name of the option.
- * @return the options matching the partial name specified, or an empty list if none matches.
+ * @param opt The partial name of the option, may be {@code null}.
+ * @return A list of matching long option names, or an empty list if no matches were found.
* @since 1.3
*/
public List getMatchingOptions(final String opt) {
final String clean = Util.stripLeadingHyphens(opt);
final List matchingOpts = new ArrayList<>();
+ // a null or empty name is not a partial name; empty would match every long option
+ if (Util.isEmpty(clean)) {
+ return matchingOpts;
+ }
// for a perfect match return the single option only
if (longOpts.containsKey(clean)) {
return Collections.singletonList(clean);
}
- longOpts.keySet().forEach(longOpt -> {
- if (longOpt.startsWith(clean)) {
- matchingOpts.add(longOpt);
- }
- });
- return matchingOpts;
+ return longOpts.keySet().stream().filter(s -> s.startsWith(clean)).collect(Collectors.toList());
}
/**
@@ -238,7 +238,7 @@ public List getMatchingOptions(final String opt) {
*
*
* @param opt short or long name of the {@link Option}.
- * @return the option represented by opt.
+ * @return The option represented by opt.
*/
public Option getOption(final String opt) {
final String clean = Util.stripLeadingHyphens(opt);
@@ -249,8 +249,8 @@ public Option getOption(final String opt) {
/**
* Gets the OptionGroup the {@code opt} belongs to.
*
- * @param option the option whose OptionGroup is being queried.
- * @return the OptionGroup if {@code opt} is part of an OptionGroup, otherwise return null.
+ * @param option The option whose OptionGroup is being queried.
+ * @return The OptionGroup if {@code opt} is part of an OptionGroup, otherwise return null.
*/
public OptionGroup getOptionGroup(final Option option) {
return optionGroups.get(option.getKey());
@@ -259,7 +259,7 @@ public OptionGroup getOptionGroup(final Option option) {
/**
* Gets the OptionGroups that are members of this Options instance.
*
- * @return a Collection of OptionGroup instances.
+ * @return A Collection of OptionGroup instances.
*/
Collection getOptionGroups() {
@@ -325,7 +325,7 @@ public boolean hasShortOption(final String opt) {
/**
* Returns the Options for use by the HelpFormatter.
*
- * @return the List of Options.
+ * @return The List of Options.
*/
List helpOptions() {
return new ArrayList<>(shortOpts.values());
diff --git a/src/main/java/org/apache/commons/cli/ParseException.java b/src/main/java/org/apache/commons/cli/ParseException.java
index a8a67f221..f322d8475 100644
--- a/src/main/java/org/apache/commons/cli/ParseException.java
+++ b/src/main/java/org/apache/commons/cli/ParseException.java
@@ -34,8 +34,8 @@ public class ParseException extends Exception {
* Note: {@code UnsupportedOperationException} are not wrapped. This is to solve a legacy expected exception problem and will be removed in the future.
*
*
- * @param e the exception to convert.
- * @return the ParseException.
+ * @param e The exception to convert.
+ * @return The ParseException.
* @throws UnsupportedOperationException due to legacy expectations. Will be removed in the future.
* @since 1.7.0
*/
@@ -53,7 +53,7 @@ public static ParseException wrap(final Throwable e) throws UnsupportedOperation
/**
* Constructs a new {@code ParseException} with the specified detail message.
*
- * @param message the detail message.
+ * @param message The detail message.
*/
public ParseException(final String message) {
super(message);
@@ -62,7 +62,7 @@ public ParseException(final String message) {
/**
* Constructs a new {@code ParseException} wrapping the specified exception.
*
- * @param e the Exception to wrap.
+ * @param e The Exception to wrap.
*/
public ParseException(final Throwable e) {
super(e);
diff --git a/src/main/java/org/apache/commons/cli/Parser.java b/src/main/java/org/apache/commons/cli/Parser.java
index 2ef6e9c9d..d120ea212 100644
--- a/src/main/java/org/apache/commons/cli/Parser.java
+++ b/src/main/java/org/apache/commons/cli/Parser.java
@@ -68,7 +68,7 @@ protected void checkRequiredOptions() throws MissingOptionException {
* @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.
- * @return a String array of the flattened arguments.
+ * @return A String array of the flattened arguments.
* @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;
@@ -76,7 +76,7 @@ protected void checkRequiredOptions() throws MissingOptionException {
/**
* Gets the options.
*
- * @return the options.
+ * @return The options.
*/
protected Options getOptions() {
return options;
@@ -85,7 +85,7 @@ protected Options getOptions() {
/**
* Gets the required options.
*
- * @return the required options.
+ * @return The required options.
*/
protected List getRequiredOptions() {
return requiredOptions;
@@ -94,9 +94,9 @@ protected List getRequiredOptions() {
/**
* Parses the specified {@code arguments} based on the specified {@link Options}.
*
- * @param options the {@code Options}.
- * @param arguments the {@code arguments}.
- * @return the {@code CommandLine}.
+ * @param options The {@code Options}.
+ * @param arguments The {@code arguments}.
+ * @return The {@code CommandLine}.
* @throws ParseException if there are any problems encountered while parsing the command line tokens.
*/
@Override
@@ -107,12 +107,12 @@ public CommandLine parse(final Options options, final String[] arguments) throws
/**
* Parses the specified {@code arguments} based on the specified {@link Options}.
*
- * @param options the {@code Options}.
- * @param arguments the {@code arguments}.
+ * @param options The {@code Options}.
+ * @param arguments The {@code arguments}.
* @param stopAtNonOption if {@code true} an unrecognized argument stops the parsing and the remaining arguments
* are added to the {@link CommandLine}s args list. If {@code false} an unrecognized argument triggers a
* ParseException.
- * @return the {@code CommandLine}.
+ * @return The {@code CommandLine}.
* @throws ParseException if an error occurs when parsing the arguments.
*/
@Override
@@ -123,10 +123,10 @@ public CommandLine parse(final Options options, final String[] arguments, final
/**
* Parses 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.
+ * @return The list of atomic option and value tokens.
* @throws ParseException if there are any problems encountered while parsing the command line tokens.
* @since 1.1
*/
@@ -137,13 +137,13 @@ public CommandLine parse(final Options options, final String[] arguments, final
/**
* Parses 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.
* @param stopAtNonOption if {@code true} an unrecognized argument stops the parsing and the remaining arguments
* are added to the {@link CommandLine}s args list. If {@code false} an unrecognized argument triggers a
* ParseException.
- * @return the list of atomic option and value tokens.
+ * @return The list of atomic option and value tokens.
* @throws ParseException if there are any problems encountered while parsing the command line tokens.
* @since 1.1
*/
@@ -306,7 +306,7 @@ protected void processProperties(final Properties properties) throws ParseExcept
/**
* Sets the options.
*
- * @param options the options.
+ * @param options The options.
*/
protected void setOptions(final Options options) {
this.options = options;
@@ -316,7 +316,7 @@ protected void setOptions(final Options options) {
/**
* Removes the option or its group from the list of expected elements.
*
- * @param opt the option.
+ * @param opt The option.
*/
private void updateRequiredOptions(final Option opt) throws ParseException {
// if the option is a required option remove the option from
diff --git a/src/main/java/org/apache/commons/cli/PatternOptionBuilder.java b/src/main/java/org/apache/commons/cli/PatternOptionBuilder.java
index 43b36abfa..f68cfaeac 100644
--- a/src/main/java/org/apache/commons/cli/PatternOptionBuilder.java
+++ b/src/main/java/org/apache/commons/cli/PatternOptionBuilder.java
@@ -113,7 +113,7 @@ public class PatternOptionBuilder {
/**
* Retrieve the class that {@code ch} represents.
*
- * @param ch the specified character.
+ * @param ch The specified character.
* @return The class that {@code ch} represents.
* @deprecated Use {@link #getValueType(char)}.
*/
@@ -125,7 +125,7 @@ public static Object getValueClass(final char ch) {
/**
* Retrieve the class that {@code ch} represents.
*
- * @param ch the specified character
+ * @param ch The specified character
* @return The class that {@code ch} represents
* @since 1.7.0
*/
@@ -157,7 +157,7 @@ public static Class> getValueType(final char ch) {
/**
* Returns whether {@code ch} is a value code, i.e. whether it represents a class in a pattern.
*
- * @param ch the specified character
+ * @param ch The specified character
* @return true if {@code ch} is a value code, otherwise false.
*/
public static boolean isValueCode(final char ch) {
@@ -167,7 +167,7 @@ public static boolean isValueCode(final char ch) {
/**
* Returns the {@link Options} instance represented by {@code pattern}.
*
- * @param pattern the pattern string
+ * @param pattern The pattern string
* @return The {@link Options} instance
*/
public static Options parsePattern(final String pattern) {
diff --git a/src/main/java/org/apache/commons/cli/TypeHandler.java b/src/main/java/org/apache/commons/cli/TypeHandler.java
index 9795de45b..4709c7811 100644
--- a/src/main/java/org/apache/commons/cli/TypeHandler.java
+++ b/src/main/java/org/apache/commons/cli/TypeHandler.java
@@ -50,7 +50,7 @@ public class TypeHandler {
/**
* Returns the class whose name is {@code className}.
*
- * @param className the class name.
+ * @param className The class name.
* @return The class if it is found.
* @throws ParseException if the class could not be found.
*/
@@ -64,7 +64,7 @@ public static Class> createClass(final String className) throws ParseException
* This method is not yet implemented and always throws an {@link UnsupportedOperationException}.
*
*
- * @param string the date string.
+ * @param string The date string.
* @return The date if {@code string} is a valid date string, otherwise return null.
*/
public static Date createDate(final String string) {
@@ -74,7 +74,7 @@ public static Date createDate(final String string) {
/**
* Creates a default converter map.
*
- * @return a default converter map.
+ * @return A default converter map.
* @since 1.7.0
*/
public static Map, Converter, ? extends Throwable>> createDefaultMap() {
@@ -84,7 +84,7 @@ public static Date createDate(final String string) {
/**
* Returns the File represented by {@code string}.
*
- * @param string the File location.
+ * @param string The File location.
* @return The file represented by {@code string}.
*/
public static File createFile(final String string) {
@@ -98,7 +98,7 @@ public static File createFile(final String string) {
* This method is not yet implemented and always throws an {@link UnsupportedOperationException}.
*
*
- * @param string the paths to the files.
+ * @param string The paths to the files.
* @return The File[] represented by {@code string}.
* @throws UnsupportedOperationException always.
* @deprecated Without replacement.
@@ -113,8 +113,8 @@ public static File[] createFiles(final String string) {
/**
* Creates a number from a String. If a '.' is present, it creates a Double, otherwise a Long.
*
- * @param string the value.
- * @return the number represented by {@code string}.
+ * @param string The value.
+ * @return The number represented by {@code string}.
* @throws ParseException if {@code string} is not a number.
*/
@Deprecated // since 1.7.0
@@ -125,8 +125,8 @@ public static Number createNumber(final String string) throws ParseException {
/**
* Creates an Object from the class name and empty constructor.
*
- * @param className the argument value.
- * @return the initialized object.
+ * @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.
* @deprecated Use {@link #createValue(String, Class)}.
*/
@@ -138,7 +138,7 @@ public static Object createObject(final String className) throws ParseException
/**
* Creates the URL represented by {@code string}.
*
- * @param string the URL string.
+ * @param string The URL string.
* @return The URL in {@code string} is well-formed.
* @throws ParseException if the URL in {@code string} is not well-formed.
*/
@@ -149,8 +149,8 @@ public static URL createURL(final String string) throws ParseException {
/**
* Creates the @code Object} of type {@code clazz} with the value of {@code string}.
*
- * @param string the command line value.
- * @param clazz the class representing the type of argument.
+ * @param string The command line value.
+ * @param clazz The class representing the type of argument.
* @param type of argument.
* @return The instance of {@code clazz} initialized with the value of {@code string}.
* @throws ParseException if the value creation for the given class threw an exception.
@@ -166,8 +166,8 @@ public static T createValue(final String string, final Class clazz) throw
/**
* Creates the {@code Object} of type {@code obj} with the value of {@code string}.
*
- * @param string the command line value.
- * @param obj the type of argument.
+ * @param string The command line value.
+ * @param obj The type of argument.
* @return The instance of {@code obj} initialized with the value of {@code string}.
* @throws ParseException if the value creation for the given object type failed.
* @deprecated Use {@link #createValue(String, Class)}.
@@ -180,8 +180,8 @@ public static Object createValue(final String string, final Object obj) throws P
/**
* Delegates to {@link #createValue(String, Class)} throwing IllegalArgumentException instead of ParseException.
*
- * @param string the command line value.
- * @param clazz the class representing the type of argument.
+ * @param string The command line value.
+ * @param clazz The class representing the type of argument.
* @param type of argument.
* @return The instance of {@code clazz} initialized with the value of {@code string}.
* @throws IllegalArgumentException if the value creation for the given class threw an exception.
@@ -197,7 +197,7 @@ private static T createValueUnchecked(final String string, final Class cl
/**
* Gets the default TypeHandler.
*
- * @return the default TypeHandler.
+ * @return The default TypeHandler.
* @since 1.7.0
*/
public static TypeHandler getDefault() {
@@ -207,7 +207,7 @@ public static TypeHandler getDefault() {
/**
* Returns the opened FileInputStream represented by {@code string}.
*
- * @param string the file location.
+ * @param string The file location.
* @return The file input stream represented by {@code string}.
* @throws ParseException if the file is not exist or not readable.
* @deprecated Use {@link #createValue(String, Class)}.
@@ -230,7 +230,19 @@ public static FileInputStream openFile(final String string) throws ParseExceptio
map.put(Integer.class, Integer::parseInt);
map.put(Short.class, Short::parseShort);
map.put(Byte.class, Byte::parseByte);
- map.put(Character.class, s -> s.startsWith("\\u") ? Character.toChars(Integer.parseInt(s.substring(2), HEX_RADIX))[0] : s.charAt(0));
+ map.put(Character.class, s -> {
+ if (s.startsWith("\\u")) {
+ final int codePoint = Integer.parseInt(s.substring(2), HEX_RADIX);
+ if (!Character.isBmpCodePoint(codePoint)) {
+ throw new IllegalArgumentException("Code point U+" + Integer.toHexString(codePoint) + " does not fit in a char");
+ }
+ if (Character.isSurrogate((char) codePoint)) {
+ throw new IllegalArgumentException("Code point U+" + Integer.toHexString(codePoint) + " is a UTF-16 surrogate");
+ }
+ return (char) codePoint;
+ }
+ return s.charAt(0);
+ });
map.put(Double.class, Double::parseDouble);
map.put(Float.class, Float::parseFloat);
map.put(BigInteger.class, BigInteger::new);
@@ -267,11 +279,11 @@ public TypeHandler(final Map, Converter, ? extends Throwable>> conver
}
/**
- * Gets the registered converter for the the Class, or {@link Converter#DEFAULT} if absent.
+ * Gets the registered converter for the Class, or {@link Converter#DEFAULT} if absent.
*
* @param The Class parameter type.
* @param clazz The Class to get the Converter for.
- * @return the registered converter if any, {@link Converter#DEFAULT} otherwise.
+ * @return The registered converter if any, {@link Converter#DEFAULT} otherwise.
* @since 1.7.0
*/
@SuppressWarnings("unchecked") // returned value will have type T because it is fixed by clazz
diff --git a/src/main/java/org/apache/commons/cli/UnrecognizedOptionException.java b/src/main/java/org/apache/commons/cli/UnrecognizedOptionException.java
index 49f0ed29a..6677fc6ef 100644
--- a/src/main/java/org/apache/commons/cli/UnrecognizedOptionException.java
+++ b/src/main/java/org/apache/commons/cli/UnrecognizedOptionException.java
@@ -33,7 +33,7 @@ public class UnrecognizedOptionException extends ParseException {
/**
* Constructs a new {@code UnrecognizedArgumentException} with the specified detail message.
*
- * @param message the detail message.
+ * @param message The detail message.
*/
public UnrecognizedOptionException(final String message) {
this(message, null);
@@ -42,8 +42,8 @@ public UnrecognizedOptionException(final String message) {
/**
* Constructs a new {@code UnrecognizedArgumentException} with the specified option and detail message.
*
- * @param message the detail message.
- * @param option the unrecognized option.
+ * @param message The detail message.
+ * @param option The unrecognized option.
* @since 1.2
*/
public UnrecognizedOptionException(final String message, final String option) {
@@ -54,7 +54,7 @@ public UnrecognizedOptionException(final String message, final String option) {
/**
* Gets the unrecognized option.
*
- * @return the related option.
+ * @return The related option.
* @since 1.2
*/
public String getOption() {
diff --git a/src/main/java/org/apache/commons/cli/Util.java b/src/main/java/org/apache/commons/cli/Util.java
index cca7369f7..7ecf05449 100644
--- a/src/main/java/org/apache/commons/cli/Util.java
+++ b/src/main/java/org/apache/commons/cli/Util.java
@@ -32,8 +32,8 @@ final class Util {
/**
* Tests whether the given array is null or empty.
*
- * @param array the array to test.
- * @return the given array is null or empty.
+ * @param array The array to test.
+ * @return The given array is null or empty.
*/
static boolean isEmpty(final Object[] array) {
return array == null || array.length == 0;
@@ -70,7 +70,7 @@ static String stripLeadingAndTrailingQuotes(final String str) {
* Removes the hyphens from the beginning of {@code str} and return the new String.
*
* @param str The string from which the hyphens should be removed.
- * @return the new String.
+ * @return The new String.
*/
static String stripLeadingHyphens(final String str) {
if (isEmpty(str)) {
diff --git a/src/main/java/org/apache/commons/cli/help/AbstractHelpFormatter.java b/src/main/java/org/apache/commons/cli/help/AbstractHelpFormatter.java
index 03a7f40ff..3007a9f55 100644
--- a/src/main/java/org/apache/commons/cli/help/AbstractHelpFormatter.java
+++ b/src/main/java/org/apache/commons/cli/help/AbstractHelpFormatter.java
@@ -85,7 +85,7 @@ protected B asThis() {
/**
* Gets the comparator to sort lists of options.
*
- * @return the comparator to sort lists of options.
+ * @return The comparator to sort lists of options.
*/
protected Comparator getComparator() {
return comparator;
@@ -94,7 +94,7 @@ protected Comparator getComparator() {
/**
* Gets {@link HelpAppendable}.
*
- * @return the {@link HelpAppendable}.
+ * @return The {@link HelpAppendable}.
*/
protected HelpAppendable getHelpAppendable() {
return helpAppendable;
@@ -103,7 +103,7 @@ protected HelpAppendable getHelpAppendable() {
/**
* Gets {@link OptionFormatter.Builder} to use to format options in the table.
*
- * @return the {@link OptionFormatter.Builder} to use to format options in the table.
+ * @return The {@link OptionFormatter.Builder} to use to format options in the table.
*/
protected OptionFormatter.Builder getOptionFormatBuilder() {
return optionFormatBuilder;
@@ -112,7 +112,7 @@ protected OptionFormatter.Builder getOptionFormatBuilder() {
/**
* Gets string to separate option groups.
*
- * @return the string to separate option groups.
+ * @return The string to separate option groups.
*/
protected String getOptionGroupSeparator() {
return optionGroupSeparator;
@@ -122,7 +122,7 @@ protected String getOptionGroupSeparator() {
* Sets the comparator to use for sorting options. If set to {@code null} no sorting is performed.
*
* @param comparator The comparator to use for sorting options.
- * @return this
+ * @return {@code this} instance.
*/
public B setComparator(final Comparator comparator) {
this.comparator = comparator;
@@ -132,8 +132,8 @@ public B setComparator(final Comparator comparator) {
/**
* Sets the {@link HelpAppendable}.
*
- * @param helpAppendable the {@link HelpAppendable} to use.
- * @return this
+ * @param helpAppendable The {@link HelpAppendable} to use.
+ * @return {@code this} instance.
*/
public B setHelpAppendable(final HelpAppendable helpAppendable) {
this.helpAppendable = helpAppendable != null ? helpAppendable : TextHelpAppendable.systemOut();
@@ -143,8 +143,8 @@ public B setHelpAppendable(final HelpAppendable helpAppendable) {
/**
* Sets the {@link OptionFormatter.Builder}.
*
- * @param optionFormatBuilder the {@link OptionFormatter.Builder} to use.
- * @return this
+ * @param optionFormatBuilder The {@link OptionFormatter.Builder} to use.
+ * @return {@code this} instance.
*/
public B setOptionFormatBuilder(final OptionFormatter.Builder optionFormatBuilder) {
this.optionFormatBuilder = optionFormatBuilder != null ? optionFormatBuilder : OptionFormatter.builder();
@@ -154,8 +154,8 @@ public B setOptionFormatBuilder(final OptionFormatter.Builder optionFormatBuilde
/**
* Sets the OptionGroup separator. Normally " | " or something similar to denote that only one option may be chosen.
*
- * @param optionGroupSeparator the string to separate option group elements with.
- * @return this
+ * @param optionGroupSeparator The string to separate option group elements with.
+ * @return {@code this} instance.
*/
public B setOptionGroupSeparator(final String optionGroupSeparator) {
this.optionGroupSeparator = Util.defaultValue(optionGroupSeparator, "");
@@ -181,6 +181,7 @@ public B setOptionGroupSeparator(final String optionGroupSeparator) {
/** The comparator for sorting {@link Option} collections */
private final Comparator comparator;
+
/**
* The {@link HelpAppendable} that produces the final output.
*/
@@ -202,7 +203,7 @@ public B setOptionGroupSeparator(final String optionGroupSeparator) {
/**
* Constructs the base formatter.
*
- * @param builder the builder.
+ * @param builder The builder.
*/
protected AbstractHelpFormatter(final Builder, ?> builder) {
this.helpAppendable = Objects.requireNonNull(builder.getHelpAppendable(), "helpAppendable");
@@ -242,7 +243,7 @@ protected OptionFormatter.Builder getOptionFormatBuilder() {
* Constructs an {@link OptionFormatter} for the specified {@link Option}.
*
* @param option The Option to format.
- * @return an {@link OptionFormatter} for the specified {@link Option}.
+ * @return An {@link OptionFormatter} for the specified {@link Option}.
*/
public final OptionFormatter getOptionFormatter(final Option option) {
return optionFormatBuilder.build(option);
@@ -279,23 +280,36 @@ public final String getSyntaxPrefix() {
* Converts a collection of {@link Option}s into a {@link TableDefinition}.
*
* @param options The options to create a table for.
- * @return the TableDefinition.
+ * @return The TableDefinition.
*/
protected abstract TableDefinition getTableDefinition(Iterable options);
+ /**
+ * Prints the help for {@link Options} with the specified command line syntax,
+ * without printing a header, footer, or autoUsage.
+ *
+ * @param cmdLineSyntax The syntax for this application.
+ * @param options The collection of {@link Option} objects to print.
+ * @throws IOException If the output could not be written to the {@link HelpAppendable}.
+ * @since 1.12.0
+ */
+ public void printHelp(final String cmdLineSyntax, final Options options) throws IOException {
+ printHelp(cmdLineSyntax, null, options, null, false);
+ }
+
/**
* Prints the help for {@link Options} with the specified command line syntax.
*
- * @param cmdLineSyntax the syntax for this application.
- * @param header the banner to display at the beginning of the help.
- * @param options the collection of {@link Option} objects to print.
- * @param footer the banner to display at the end of the help.
+ * @param cmdLineSyntax The syntax for this application.
+ * @param header The banner to display at the beginning of the help.
+ * @param options The collection of {@link Option} objects to print.
+ * @param footer The banner to display at the end of the help.
* @param autoUsage whether to print an automatically generated usage statement.
* @throws IOException If the output could not be written to the {@link HelpAppendable}.
*/
public void printHelp(final String cmdLineSyntax, final String header, final Iterable options, final String footer, final boolean autoUsage)
throws IOException {
- Options optionsObject = new Options();
+ final Options optionsObject = new Options();
options.forEach(optionsObject::addOption);
printHelp(cmdLineSyntax, header, optionsObject, footer, autoUsage);
}
@@ -303,10 +317,10 @@ public void printHelp(final String cmdLineSyntax, final String header, final Ite
/**
* Prints the help for a collection of {@link Option}s with the specified command line syntax.
*
- * @param cmdLineSyntax the syntax for this application.
- * @param header the banner to display at the beginning of the help.
- * @param options the collection of {@link Option} objects to print.
- * @param footer the banner to display at the end of the help.
+ * @param cmdLineSyntax The syntax for this application.
+ * @param header The banner to display at the beginning of the help.
+ * @param options The collection of {@link Option} objects to print.
+ * @param footer The banner to display at the end of the help.
* @param autoUsage whether to print an automatically generated usage statement.
* @throws IOException If the output could not be written to the {@link HelpAppendable}.
*/
@@ -332,7 +346,7 @@ public void printHelp(final String cmdLineSyntax, final String header, final Opt
/**
* Prints the option table for a collection of {@link Option} objects to the {@link HelpAppendable}.
*
- * @param options the collection of Option objects to print in the table.
+ * @param options The collection of Option objects to print in the table.
* @throws IOException If the output could not be written to the {@link HelpAppendable}.
*/
public final void printOptions(final Iterable options) throws IOException {
@@ -342,7 +356,7 @@ public final void printOptions(final Iterable options) throws IOExceptio
/**
* Prints the option table for the specified {@link Options} to the {@link HelpAppendable}.
*
- * @param options the Options to print in the table.
+ * @param options The Options to print in the table.
* @throws IOException If the output could not be written to the {@link HelpAppendable}.
*/
public final void printOptions(final Options options) throws IOException {
@@ -352,7 +366,7 @@ public final void printOptions(final Options options) throws IOException {
/**
* Prints a {@link TableDefinition} to the {@link HelpAppendable}.
*
- * @param tableDefinition the {@link TableDefinition} to print.
+ * @param tableDefinition The {@link TableDefinition} to print.
* @throws IOException If the output could not be written to the {@link HelpAppendable}.
*/
public final void printOptions(final TableDefinition tableDefinition) throws IOException {
@@ -362,7 +376,7 @@ public final void printOptions(final TableDefinition tableDefinition) throws IOE
/**
* Sets the syntax prefix. This is the phrase that is printed before the syntax line.
*
- * @param prefix the new value for the syntax prefix.
+ * @param prefix The new value for the syntax prefix.
*/
public final void setSyntaxPrefix(final String prefix) {
this.syntaxPrefix = prefix;
@@ -371,8 +385,8 @@ public final void setSyntaxPrefix(final String prefix) {
/**
* Creates a new list of options ordered by the comparator.
*
- * @param options the Options to sort.
- * @return a new list of options ordered by the comparator.
+ * @param options The Options to sort.
+ * @return A new list of options ordered by the comparator.
*/
public List sort(final Iterable options) {
final List result = new ArrayList<>();
@@ -386,8 +400,8 @@ public List sort(final Iterable options) {
/**
* Creates a new list of options ordered by the comparator.
*
- * @param options the Options to sort.
- * @return a new list of options ordered by the comparator.
+ * @param options The Options to sort.
+ * @return A new list of options ordered by the comparator.
*/
public List sort(final Options options) {
return sort(options == null ? null : options.getOptions());
@@ -396,8 +410,8 @@ public List sort(final Options options) {
/**
* Formats the {@code argName} as an argument a defined in the enclosed {@link OptionFormatter.Builder}.
*
- * @param argName the string to format as an argument.
- * @return the {@code argName} formatted as an argument.
+ * @param argName The string to format as an argument.
+ * @return The {@code argName} formatted as an argument.
*/
public final String toArgName(final String argName) {
return optionFormatBuilder.toArgName(argName);
@@ -410,8 +424,9 @@ public final String toArgName(final String argName) {
* of option groups. To display the option grouping use {@link #toSyntaxOptions(Options)} or
* {@link #toSyntaxOptions(OptionGroup)} for individual groups.
*
+ *
* @param options The collection of {@link Option} instances to create the string representation for.
- * @return the string representation of the options as used in the syntax display.
+ * @return The string representation of the options as used in the syntax display.
*/
public String toSyntaxOptions(final Iterable options) {
return toSyntaxOptions(options, o -> null);
@@ -421,8 +436,8 @@ public String toSyntaxOptions(final Iterable options) {
* Return the string representation of the options as used in the syntax display.
*
* @param options The options to create the string representation for.
- * @param lookup a function to determine if the Option is part of an OptionGroup that has already been processed.
- * @return the string representation of the options as used in the syntax display.
+ * @param lookup A function to determine if the Option is part of an OptionGroup that has already been processed.
+ * @return The string representation of the options as used in the syntax display.
*/
protected String toSyntaxOptions(final Iterable options, final Function lookup) {
// list of groups that have been processed.
@@ -460,7 +475,7 @@ protected String toSyntaxOptions(final Iterable options, final Function<
* Return the string representation of the options as used in the syntax display.
*
* @param group The OptionGroup to create the string representation for.
- * @return the string representation of the options as used in the syntax display.
+ * @return The string representation of the options as used in the syntax display.
*/
public String toSyntaxOptions(final OptionGroup group) {
final StringBuilder buff = new StringBuilder();
@@ -486,7 +501,7 @@ public String toSyntaxOptions(final OptionGroup group) {
* Return the string representation of the options as used in the syntax display.
*
* @param options The {@link Options} to create the string representation for.
- * @return the string representation of the options as used in the syntax display.
+ * @return The string representation of the options as used in the syntax display.
*/
public String toSyntaxOptions(final Options options) {
return toSyntaxOptions(options.getOptions(), options::getOptionGroup);
diff --git a/src/main/java/org/apache/commons/cli/help/FilterHelpAppendable.java b/src/main/java/org/apache/commons/cli/help/FilterHelpAppendable.java
index b583fff81..b3c5a81d0 100644
--- a/src/main/java/org/apache/commons/cli/help/FilterHelpAppendable.java
+++ b/src/main/java/org/apache/commons/cli/help/FilterHelpAppendable.java
@@ -45,7 +45,7 @@ public abstract class FilterHelpAppendable implements HelpAppendable {
/**
* Constructs an appendable filter built on top of the specified underlying appendable.
*
- * @param output the underlying appendable to be assigned to the field {@code this.output} for later use, or {@code null} if this instance is to be created
+ * @param output The underlying appendable to be assigned to the field {@code this.output} for later use, or {@code null} if this instance is to be created
* without an underlying stream.
*/
protected FilterHelpAppendable(final Appendable output) {
diff --git a/src/main/java/org/apache/commons/cli/help/HelpAppendable.java b/src/main/java/org/apache/commons/cli/help/HelpAppendable.java
index 921a0be3c..27c3b27e8 100644
--- a/src/main/java/org/apache/commons/cli/help/HelpAppendable.java
+++ b/src/main/java/org/apache/commons/cli/help/HelpAppendable.java
@@ -61,8 +61,8 @@ default void appendFormat(final String format, final Object... args) throws IOEx
/**
* Appends a header.
*
- * @param level the level of the header. This is equivalent to the "1", "2", or "3" in the HTML "h1", "h2", "h3" tags.
- * @param text the text for the header, null is a noop.
+ * @param level The level of the header. This is equivalent to the "1", "2", or "3" in the HTML "h1", "h2", "h3" tags.
+ * @param text The text for the header, null is a noop.
* @throws IOException If an output error occurs.
*/
void appendHeader(int level, CharSequence text) throws IOException;
@@ -71,7 +71,7 @@ default void appendFormat(final String format, final Object... args) throws IOEx
* Appends a list.
*
* @param ordered {@code true} if the list should be ordered.
- * @param list the list to write, null is a noop.
+ * @param list The list to write, null is a noop.
* @throws IOException If an output error occurs.
*/
void appendList(boolean ordered, Collection list) throws IOException;
@@ -79,7 +79,7 @@ default void appendFormat(final String format, final Object... args) throws IOEx
/**
* Appends a paragraph.
*
- * @param paragraph the paragraph to write, null is a noop.
+ * @param paragraph The paragraph to write, null is a noop.
* @throws IOException If an output error occurs.
*/
void appendParagraph(CharSequence paragraph) throws IOException;
@@ -106,7 +106,7 @@ default void appendParagraphFormat(final String format, final Object... args) th
/**
* Appends a table.
*
- * @param table the table definition to write, null is a noop.
+ * @param table The table definition to write, null is a noop.
* @throws IOException If an output error occurs.
*/
void appendTable(TableDefinition table) throws IOException;
@@ -114,7 +114,7 @@ default void appendParagraphFormat(final String format, final Object... args) th
/**
* Appends a title.
*
- * @param title the title to write, null is a noop.
+ * @param title The title to write, null is a noop.
* @throws IOException If an output error occurs.
*/
void appendTitle(CharSequence title) throws IOException;
diff --git a/src/main/java/org/apache/commons/cli/help/HelpFormatter.java b/src/main/java/org/apache/commons/cli/help/HelpFormatter.java
index c4081ec4b..d47b85265 100644
--- a/src/main/java/org/apache/commons/cli/help/HelpFormatter.java
+++ b/src/main/java/org/apache/commons/cli/help/HelpFormatter.java
@@ -18,7 +18,6 @@ Licensed to the Apache Software Foundation (ASF) under one or more
package org.apache.commons.cli.help;
import java.util.ArrayList;
-import java.util.Arrays;
import java.util.List;
import org.apache.commons.cli.Option;
@@ -31,14 +30,14 @@ Licensed to the Apache Software Foundation (ASF) under one or more
*
*
* 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("help").create('h'));
+ * options.addOption(Option.builder("f").longOpt("file").desc("The file to be processed").hasArg().argName("FILE").required().get());
+ * options.addOption(Option.builder("v").longOpt("version").desc("Print the version of the application").get());
+ * options.addOption(Option.builder("h").longOpt("help").get());
*
* String header = "Do something useful with an input file";
* String footer = "Please report issues at https://example.com/issues";
*
- * HelpFormatter formatter = new HelpFormatter();
+ * HelpFormatter formatter = HelpFormatter.builder().get();
* formatter.printHelp("myapp", header, options, footer, true);
*
*
@@ -93,7 +92,7 @@ public HelpFormatter get() {
/**
* Sets the showSince flag.
*
- * @param showSince the desired value of the showSince flag.
+ * @param showSince The desired value of the showSince flag.
* @return {@code this} instance.
*/
public Builder setShowSince(final boolean showSince) {
@@ -102,6 +101,21 @@ public Builder setShowSince(final boolean showSince) {
}
}
+ /**
+ * The default "Since" column label.
+ */
+ private static final String LABEL_SINCE = "Since";
+
+ /**
+ * The default "Description" column label.
+ */
+ private static final String LABEL_DESCRIPTION = "Description";
+
+ /**
+ * The default "Options" column label.
+ */
+ private static final String LABEL_OPTIONS = "Options";
+
/**
* Default number of characters per line: {@value}.
*/
@@ -120,7 +134,7 @@ public Builder setShowSince(final boolean showSince) {
/**
* Constructs a new builder.
*
- * @return a new builder.
+ * @return A new builder.
*/
public static Builder builder() {
return new Builder();
@@ -132,7 +146,7 @@ public static Builder builder() {
/**
* Constructs the Help formatter.
*
- * @param builder the Builder to build from.
+ * @param builder The Builder to build from.
*/
protected HelpFormatter(final Builder builder) {
super(builder);
@@ -142,7 +156,7 @@ protected HelpFormatter(final Builder builder) {
/**
* Gets the table definition for the options.
*
- * @param options the collection of {@link Option} instances to create the table from.
+ * @param options The collection of {@link Option} instances to create the table from.
* @return A {@link TableDefinition} to display the options.
*/
@Override
@@ -184,6 +198,12 @@ public TableDefinition getTableDefinition(final Iterable options) {
rows.add(row);
});
// return the TableDefinition with the proper column headers.
- return TableDefinition.from("", styles, showSince ? Arrays.asList("Options", "Since", "Description") : Arrays.asList("Options", "Description"), rows);
+ final List headers = new ArrayList<>(3);
+ headers.add(LABEL_OPTIONS);
+ if (showSince) {
+ headers.add(LABEL_SINCE);
+ }
+ headers.add(LABEL_DESCRIPTION);
+ return TableDefinition.from("", styles, headers, rows);
}
}
diff --git a/src/main/java/org/apache/commons/cli/help/OptionFormatter.java b/src/main/java/org/apache/commons/cli/help/OptionFormatter.java
index 54e292fff..8ddc8280b 100644
--- a/src/main/java/org/apache/commons/cli/help/OptionFormatter.java
+++ b/src/main/java/org/apache/commons/cli/help/OptionFormatter.java
@@ -112,8 +112,8 @@ public OptionFormatter get() {
/**
* Specifies the starting and ending argument name delimiters for {@link Option} instances.
*
- * @param begin the beginning delimiter.
- * @param end the ending delimiter.
+ * @param begin The beginning delimiter.
+ * @param end The ending delimiter.
* @return {@code this} instance.
*/
public Builder setArgumentNameDelimiters(final String begin, final String end) {
@@ -125,8 +125,8 @@ public Builder setArgumentNameDelimiters(final String begin, final String end) {
/**
* Sets the default argument name.
*
- * @param name the new value of default argument name.
- * @return this
+ * @param name The new value of default argument name.
+ * @return {@code this} instance.
*/
public Builder setDefaultArgName(final String name) {
this.defaultArgName = Util.defaultValue(name, DEFAULT_ARG_NAME);
@@ -136,7 +136,7 @@ public Builder setDefaultArgName(final String name) {
/**
* Specifies the function to construct the deprecated massage for the Option. Should include the description text if desired.
*
- * @param deprecatedFormatFunction the function to specify the deprecated message for the option.
+ * @param deprecatedFormatFunction The function to specify the deprecated message for the option.
* @return {@code this} instance.
*/
public Builder setDeprecatedFormatFunction(final Function deprecatedFormatFunction) {
@@ -148,7 +148,7 @@ public Builder setDeprecatedFormatFunction(final Function deprec
* Sets the long option prefix.
*
* @param prefix prefix for long options.
- * @return this
+ * @return {@code this} instance.
*/
public Builder setLongOptPrefix(final String prefix) {
this.longOptPrefix = Util.defaultValue(prefix, "");
@@ -158,8 +158,8 @@ public Builder setLongOptPrefix(final String prefix) {
/**
* Sets the separator displayed between a options and the argument name. Typically ' ' or '='.
*
- * @param optArgSeparator the separator.
- * @return this
+ * @param optArgSeparator The separator.
+ * @return {@code this} instance.
* @since 1.3
*/
public Builder setOptArgSeparator(final String optArgSeparator) {
@@ -170,8 +170,8 @@ public Builder setOptArgSeparator(final String optArgSeparator) {
/**
* Specifies the starting and ending delimiters for optional {@link Option} instances.
*
- * @param begin the beginning delimiter.
- * @param end the ending delimiter.
+ * @param begin The beginning delimiter.
+ * @param end The ending delimiter.
* @return {@code this} instance.
*/
public Builder setOptionalDelimiters(final String begin, final String end) {
@@ -183,7 +183,7 @@ public Builder setOptionalDelimiters(final String begin, final String end) {
/**
* Specifies the short option prefix.
*
- * @param optPrefix the prefix for short options.
+ * @param optPrefix The prefix for short options.
* @return {@code this} instance.
*/
public Builder setOptPrefix(final String optPrefix) {
@@ -194,8 +194,8 @@ public Builder setOptPrefix(final String optPrefix) {
/**
* Sets the separator displayed between a long option and short options. Typically ',' or ' '.
*
- * @param optSeparator the separator.
- * @return this
+ * @param optSeparator The separator.
+ * @return {@code this} instance.
* @since 1.3
*/
public Builder setOptSeparator(final String optSeparator) {
@@ -207,7 +207,7 @@ public Builder setOptSeparator(final String optSeparator) {
* Specifies the function to convert an {@link OptionFormatter} into the syntax format for the option.
*
* @param syntaxFormatFunction The function to convert an {@link OptionFormatter} into the syntax format for the option.
- * @return this
+ * @return {@code this} instance.
*/
public Builder setSyntaxFormatFunction(final BiFunction syntaxFormatFunction) {
this.syntaxFormatFunction = syntaxFormatFunction;
@@ -217,8 +217,8 @@ public Builder setSyntaxFormatFunction(final BiFunction columnStyle, final List headers, final Iterable> rows) {
@@ -79,7 +79,7 @@ public Iterable> rows() {
/**
* Gets the list TextStyles. One for each column in order.
*
- * @return the list of TextStyles.
+ * @return The list of TextStyles.
*/
List columnTextStyles();
diff --git a/src/main/java/org/apache/commons/cli/help/TextHelpAppendable.java b/src/main/java/org/apache/commons/cli/help/TextHelpAppendable.java
index 232041436..2b053106c 100644
--- a/src/main/java/org/apache/commons/cli/help/TextHelpAppendable.java
+++ b/src/main/java/org/apache/commons/cli/help/TextHelpAppendable.java
@@ -76,19 +76,22 @@ public static int indexOfWrap(final CharSequence text, final int width, final in
if (width < 1) {
throw new IllegalArgumentException("Width must be greater than 0");
}
+ // width can be Integer.MAX_VALUE (TextStyle.UNSET_MAX_WIDTH), so keep the wrap boundary in a long;
+ // startPos + width as an int overflows to a negative value and yields a negative wrap index.
+ final long end = (long) startPos + width;
// handle case of width > text.
// the line ends before the max wrap pos or a new line char found
- int limit = Math.min(startPos + width, text.length());
+ int limit = (int) Math.min(end, text.length());
for (int idx = startPos; idx < limit; idx++) {
if (BREAK_CHAR_SET.contains(text.charAt(idx))) {
return idx;
}
}
- if (startPos + width >= text.length()) {
+ if (end >= text.length()) {
return text.length();
}
- limit = Math.min(startPos + width, text.length() - 1);
+ limit = (int) Math.min(end, text.length() - 1);
int pos;
// look for the last whitespace character before limit
for (pos = limit; pos >= startPos; --pos) {
@@ -103,7 +106,7 @@ public static int indexOfWrap(final CharSequence text, final int width, final in
/**
* Creates a new TextHelpAppendable on {@link System#out}.
*
- * @return a new TextHelpAppendable on {@link System#out}.
+ * @return A new TextHelpAppendable on {@link System#out}.
*/
protected static TextHelpAppendable systemOut() {
return new TextHelpAppendable(System.out);
@@ -115,7 +118,7 @@ protected static TextHelpAppendable systemOut() {
/**
* Constructs an appendable filter built on top of the specified underlying appendable.
*
- * @param output the underlying appendable to be assigned to the field {@code this.output} for later use, or {@code null} if this instance is to be created
+ * @param output The underlying appendable to be assigned to the field {@code this.output} for later use, or {@code null} if this instance is to be created
* without an underlying stream.
*/
public TextHelpAppendable(final Appendable output) {
@@ -136,15 +139,15 @@ public TextHelpAppendable(final Appendable output) {
*
* The minimum size for a column may not be smaller than the length of the column header
* The maximum size is set to the maximum of the length of the header or the longest line length.
- * If the total size of the columns is greater than the page wight, adjust the size of VARIABLE columns to attempt reduce the width to the the maximum
- * size.
+ * If the total size of the columns is greater than the page wight, adjust the size of VARIABLE columns to attempt reduce the width to the maximum
+ * size.
*
*
* Note: it is possible for the size of the columns to exceed the declared page width. In this case the table will extend beyond the desired page width.
*
*
- * @param table the table to adjust.
- * @return a new TableDefinition with adjusted values.
+ * @param table The table to adjust.
+ * @return A new TableDefinition with adjusted values.
*/
protected TableDefinition adjustTableFormat(final TableDefinition table) {
final List styleBuilders = new ArrayList<>();
@@ -264,7 +267,7 @@ public void appendTitle(final CharSequence title) throws IOException {
/**
* Gets the indent for the output.
*
- * @return the indent of the page.
+ * @return The indent of the page.
*/
public int getIndent() {
return textStyleBuilder.getIndent();
@@ -282,7 +285,7 @@ public int getLeftPad() {
/**
* Gets the maximum width for the output
*
- * @return the maximum width for the output.
+ * @return The maximum width for the output.
*/
public int getMaxWidth() {
return textStyleBuilder.getMaxWidth();
@@ -327,7 +330,7 @@ protected Queue makeColumnQueue(final CharSequence columnData, final Tex
* + the left pad.
*
* @param columnData The column data to output.
- * @param styles the styles to apply.
+ * @param styles The styles to apply.
* @return A list of queues of strings that represent each column in the table.
*/
protected List> makeColumnQueues(final List columnData, final List styles) {
@@ -341,7 +344,7 @@ protected List> makeColumnQueues(final List columnData, fi
/**
* Prints a queue of text.
*
- * @param queue the queue of text to print.
+ * @param queue The queue of text to print.
* @throws IOException on output error.
*/
private void printQueue(final Queue queue) throws IOException {
@@ -353,7 +356,7 @@ private void printQueue(final Queue queue) throws IOException {
/**
* Prints wrapped text using the TextHelpAppendable output style.
*
- * @param text the text to wrap
+ * @param text The text to wrap
* @throws IOException on output error.
*/
public void printWrapped(final String text) throws IOException {
@@ -363,8 +366,8 @@ public void printWrapped(final String text) throws IOException {
/**
* Prints wrapped text.
*
- * @param text the text to wrap
- * @param style the style for the wrapped text.
+ * @param text The text to wrap
+ * @param style The style for the wrapped text.
* @throws IOException on output error.
*/
public void printWrapped(final String text, final TextStyle style) throws IOException {
@@ -374,9 +377,9 @@ public void printWrapped(final String text, final TextStyle style) throws IOExce
/**
* Resizes an original width based on the fractional size it should be.
*
- * @param orig the original size.
- * @param fraction the fractional adjustment.
- * @return the resized value.
+ * @param orig The original size.
+ * @param fraction The fractional adjustment.
+ * @return The resized value.
*/
private int resize(final int orig, final double fraction) {
return (int) (orig * fraction);
@@ -385,9 +388,9 @@ private int resize(final int orig, final double fraction) {
/**
* Resizes a TextStyle builder based on the fractional size.
*
- * @param builder the builder to adjust.
- * @param fraction the fractional size (for example percentage of the current size) that the builder should be.
- * @return the builder with the maximum width and indent values resized.
+ * @param builder The builder to adjust.
+ * @param fraction The fractional size (for example percentage of the current size) that the builder should be.
+ * @return The builder with the maximum width and indent values resized.
*/
protected TextStyle.Builder resize(final TextStyle.Builder builder, final double fraction) {
final double indentFrac = builder.getIndent() * 1.0 / builder.getMaxWidth();
@@ -404,36 +407,39 @@ protected TextStyle.Builder resize(final TextStyle.Builder builder, final double
/**
* Sets the indent for the output.
*
- * @param indent the indent used for paragraphs.
+ * @param indent The indent used for paragraphs.
*/
public void setIndent(final int indent) {
textStyleBuilder.setIndent(indent);
+ // TODO return this in 2.0
}
/**
* Sets the left padding: the number of characters from the left edge to start output.
*
- * @param leftPad the left padding.
+ * @param leftPad The left padding.
*/
public void setLeftPad(final int leftPad) {
textStyleBuilder.setLeftPad(leftPad);
+ // TODO return this in 2.0
}
/**
* Sets the maximum width for the output.
*
- * @param maxWidth the maximum width for the output.
+ * @param maxWidth The maximum width for the output.
*/
public void setMaxWidth(final int maxWidth) {
textStyleBuilder.setMaxWidth(maxWidth);
+ // TODO return this in 2.0
}
/**
* Writes one line from each of the {@code columnQueues} until all the queues are exhausted. If an exhausted queue is encountered while other queues
* continue to have content the exhausted queue will produce empty text for the output width of the column (maximum width + left pad).
*
- * @param columnQueues the List of queues that represent the columns of data.
- * @param styles the TextStyle for each column.
+ * @param columnQueues The List of queues that represent the columns of data.
+ * @param styles The TextStyle for each column.
* @throws IOException on output error.
*/
protected void writeColumnQueues(final List> columnQueues, final List styles) throws IOException {
diff --git a/src/main/java/org/apache/commons/cli/help/TextStyle.java b/src/main/java/org/apache/commons/cli/help/TextStyle.java
index fda8d2d9e..02346daae 100644
--- a/src/main/java/org/apache/commons/cli/help/TextStyle.java
+++ b/src/main/java/org/apache/commons/cli/help/TextStyle.java
@@ -28,7 +28,7 @@ Licensed to the Apache Software Foundation (ASF) under one or more
public final class TextStyle {
/**
- * The alignment possibilities.
+ * Enumerates alignment options.
*/
public enum Alignment {
@@ -144,8 +144,8 @@ public boolean isScalable() {
/**
* Sets the alignment.
*
- * @param alignment the desired alignment.
- * @return this
+ * @param alignment The desired alignment.
+ * @return {@code this} instance.
*/
public Builder setAlignment(final Alignment alignment) {
this.alignment = alignment;
@@ -155,8 +155,8 @@ public Builder setAlignment(final Alignment alignment) {
/**
* Sets the indent value.
*
- * @param indent the new indent value.
- * @return this
+ * @param indent The new indent value.
+ * @return {@code this} instance.
*/
public Builder setIndent(final int indent) {
this.indent = indent;
@@ -166,8 +166,8 @@ public Builder setIndent(final int indent) {
/**
* Sets the left padding.
*
- * @param leftPad the new left padding.
- * @return this
+ * @param leftPad The new left padding.
+ * @return {@code this} instance.
*/
public Builder setLeftPad(final int leftPad) {
this.leftPad = leftPad;
@@ -178,7 +178,7 @@ public Builder setLeftPad(final int leftPad) {
* Sets the currently specified minimum width.
*
* @param maxWidth The currently specified maximum width.
- * @return this
+ * @return {@code this} instance.
*/
public Builder setMaxWidth(final int maxWidth) {
this.maxWidth = maxWidth;
@@ -189,7 +189,7 @@ public Builder setMaxWidth(final int maxWidth) {
* Sets the currently specified minimum width.
*
* @param minWidth The currently specified minimum width.
- * @return this
+ * @return {@code this} instance.
*/
public Builder setMinWidth(final int minWidth) {
this.minWidth = minWidth;
@@ -210,7 +210,7 @@ public Builder setScalable(final boolean scalable) {
/**
* Sets all properties from the given text style.
*
- * @param style the source text style.
+ * @param style The source text style.
* @return {@code this} instance.
*/
public Builder setTextStyle(final TextStyle style) {
@@ -238,7 +238,7 @@ public Builder setTextStyle(final TextStyle style) {
/**
* Creates a new builder.
*
- * @return a new builder.
+ * @return A new builder.
*/
public static Builder builder() {
return new Builder();
@@ -265,7 +265,7 @@ public static Builder builder() {
/**
* Constructs a new instance.
*
- * @param builder the builder to build the text style from.
+ * @param builder The builder to build the text style from.
*/
private TextStyle(final Builder builder) {
this.alignment = builder.alignment;
@@ -279,7 +279,7 @@ private TextStyle(final Builder builder) {
/**
* Gets the alignment.
*
- * @return the alignment.
+ * @return The alignment.
*/
public Alignment getAlignment() {
return alignment;
@@ -288,7 +288,7 @@ public Alignment getAlignment() {
/**
* Gets the indent value.
*
- * @return the indent value.
+ * @return The indent value.
*/
public int getIndent() {
return indent;
@@ -297,7 +297,7 @@ public int getIndent() {
/**
* Gets the left padding.
*
- * @return the left padding.
+ * @return The left padding.
*/
public int getLeftPad() {
return leftPad;
@@ -324,7 +324,7 @@ public int getMinWidth() {
/**
* Specifies if the column can be made wider or to narrower width to fit constraints of the HelpAppendable and formatting.
*
- * @return the scaling value.
+ * @return The scaling value.
*/
public boolean isScalable() {
return scalable;
@@ -338,8 +338,8 @@ public boolean isScalable() {
*
*
* @param addIndent if {@code true} account for the indent when padding the string.
- * @param text the text to pad.
- * @return the padded string.
+ * @param text The text to pad.
+ * @return The padded string.
*/
public CharSequence pad(final boolean addIndent, final CharSequence text) {
if (text.length() >= maxWidth) {
@@ -369,7 +369,7 @@ public CharSequence pad(final boolean addIndent, final CharSequence text) {
rest = "";
} else {
int restLen = maxWidth - text.length();
- if (addIndent && restLen > indent) {
+ if (addIndent && restLen >= indent) {
indentPad = Util.repeatSpace(indent);
restLen -= indent;
} else {
diff --git a/src/main/java/org/apache/commons/cli/help/Util.java b/src/main/java/org/apache/commons/cli/help/Util.java
index 2d8eb3b9c..921f9ad78 100644
--- a/src/main/java/org/apache/commons/cli/help/Util.java
+++ b/src/main/java/org/apache/commons/cli/help/Util.java
@@ -33,9 +33,9 @@ final class Util {
* Returns the {@code defaultValue} if {@code str} is empty.
*
* @param str The string to check.
- * @param defaultValue the default value if the string is empty.
+ * @param defaultValue The default value if the string is empty.
* @param The type of arguments.
- * @return the {@code defaultValue} if {@code str} is empty,
+ * @return The {@code defaultValue} if {@code str} is empty,
*/
static T defaultValue(final T str, final T defaultValue) {
return isEmpty(str) ? defaultValue : str;
@@ -44,9 +44,9 @@ static T defaultValue(final T str, final T defaultValue
/**
* Finds the index of the first non whitespace character.
*
- * @param text the text to search in.
- * @param startPos the starting position to search from.
- * @return the index of the first non whitespace character or -1 if non found.
+ * @param text The text to search in.
+ * @param startPos The starting position to search from.
+ * @return The index of the first non whitespace character or -1 if non found.
*/
static int indexOfNonWhitespace(final CharSequence text, final int startPos) {
if (isEmpty(text)) {
@@ -54,10 +54,11 @@ static int indexOfNonWhitespace(final CharSequence text, final int startPos) {
}
// the line ends before the max wrap pos or a new line char found
int idx = startPos;
- while (idx < text.length() && isWhitespace(text.charAt(idx))) {
+ final int length = text.length();
+ while (idx < length && isWhitespace(text.charAt(idx))) {
idx++;
}
- return idx < text.length() ? idx : NOT_FOUND;
+ return idx < length ? idx : NOT_FOUND;
}
/**
@@ -93,8 +94,8 @@ static String ltrim(final String s) {
/**
* Constructs a string of specified length filled with the specified char.
*
- * @param len the length of the final string.
- * @param fillChar the character to file it will.
+ * @param len The length of the final string.
+ * @param fillChar The character to file it will.
* @return A string of specified length filled with the specified char.
*/
static String repeat(final int len, final char fillChar) {
diff --git a/src/main/javadoc/overview.html b/src/main/javadoc/overview.html
index b1f2cc340..f0f9d58bd 100644
--- a/src/main/javadoc/overview.html
+++ b/src/main/javadoc/overview.html
@@ -26,7 +26,7 @@
1. Introducing Apache Commons CLI
- The Apacahe Commons CLI component parses command-line arguments for your application.
+ The Apache Commons CLI component parses command-line arguments for your application.
Commons CLI parses command-line arguments using a descriptor of
valid options (long and short), potentially with arguments.
@@ -58,9 +58,9 @@ Defining the CLI
to define the interface to the application.
- CLI uses the
+ CLI uses the
Options class, as a container for
-
+
Option instances. There are two ways to create
Options in CLI. One of them is via the constructors,
the other way is via the factory methods defined in
@@ -86,11 +86,11 @@
Parsing the CLI
The parse method defined on
-
+
CommandLineParser takes an Options
instance and a String[] of arguments and
returns a
-
+
CommandLine .
@@ -142,7 +142,7 @@
Using a boolean option
Creating the Options
- An
+ An
Options object must be created and the Option must be
added to it.
@@ -172,18 +172,18 @@ Parsing the command line arguments
of the CommandLineParser interface, the recommended one is the
DefaultParser.
- CommandLineParser parser = new DefaultParser();
-CommandLine cmd = parser.parse(options, args);
+ CommandLineParser parser = new DefaultParser();
+CommandLine cmd = parser.parse(options, args);
Now we need to check if the t option is present. To do
this we will interrogate the
- CommandLine
+ CommandLine
object. The hasOption method takes a
java.lang.String parameter and returns true if the option
represented by the java.lang.String is present, otherwise
it returns false.
- if(cmd.hasOption("t")) {
+ if (cmd.hasOption("t")) {
// print the date and time
} else {
// print the date
@@ -232,7 +232,7 @@ Retrieving the argument value
// get c option value
String countryCode = cmd.getOptionValue("c");
-if(countryCode == null) {
+if (countryCode == null) {
// print default date
} else {
// print date for country specified by countryCode
@@ -288,33 +288,33 @@ Defining Argument Options
.argName("file")
.hasArg()
.desc("use given file for log")
- .build();
+ .get();
Option logger = Option.builder("logger")
.argName("classname")
.hasArg()
.desc("the class which it to perform logging")
- .build();
+ .get();
Option listener = Option.builder("listener")
.argName("classname")
.hasArg()
.desc("add an instance of class as "
+ "a project listener")
- .build();
+ .get();
Option buildFile = Option.builder("buildfile")
.argName("file")
.hasArg()
.desc("use given buildfile")
- .build();
+ .get();
Option find = Option.builder("find")
.argName("file")
.hasArg()
.desc("search for buildfile towards the "
+ "root of the filesystem and use it")
- .build();
+ .get();
Defining Java Property Option
@@ -322,10 +322,10 @@ Defining Java Property Option
The last option to create is the Java property, and it is also created
using the Option class' Builder.
- Option property = Option property = Option.builder("D")
+ Option property = Option.builder("D")
.hasArgs()
.valueSeparator('=')
- .build();
+ .get();
The map of properties specified by this option can later be retrieved by
calling getOptionProperties("D") on the CommandLine.
@@ -335,11 +335,11 @@
Defining Java Property Option
Creating the Options
Now that we have created each
- Option we need
+ Option we need
to create the
- Options
+ Options
instance. This is achieved using the
- addOption
+ addOption
method of Options.
Options options = new Options();
@@ -351,10 +351,10 @@ Creating the Options
options.addOption(verbose);
options.addOption(debug);
options.addOption(emacs);
-options.addOption(logfile);
+options.addOption(logFile);
options.addOption(logger);
options.addOption(listener);
-options.addOption(buildfile);
+options.addOption(buildFile);
options.addOption(find);
options.addOption(property);
@@ -367,7 +367,7 @@
Creating the Parser
We now need to create a CommandLineParser. This will parse the command
line arguments, using the rules specified by the Options and
- return an instance of CommandLine .
+ return an instance of CommandLine .
public static void main(String[] args) {
// create the parser
@@ -399,7 +399,7 @@ Displaying Usage and Help
CLI also provides the means to automatically generate usage
and help information. This is achieved with the
- HelpFormatter
+ HelpFormatter
class.
// automatically generate the help statement
@@ -454,7 +454,7 @@ Options for this example.
+ Options for this example.
// create the command line parser
CommandLineParser parser = new DefaultParser();
@@ -468,7 +468,7 @@
+ .get();
The above will create an option that passes the string value to the Foo constructor when commandLine.getParsedOptionValue(fooOpt) is called.
@@ -595,12 +595,12 @@ Changing Usage Announcement
}
System.err.printf("ERROR: Option %s: %s%n", buf, o.getDeprecated());
};
- DefaultParser parser = DefaultParser.builder().setDeprecatedHandler(deprecatedUsageAnnouncement).build();
+ DefaultParser parser = DefaultParser.builder().setDeprecatedHandler(deprecatedUsageAnnouncement).get();
CommandLine line;
try {
// parse the command line arguments
@@ -728,10 +728,10 @@ Changing help format
7. Defining Option Properties
The following are the properties that each
- Option has. All of these
+ Option has. All of these
can be set using the accessors or using the methods
defined in the
- Option.Builder .
+ Option.Builder .
Option Properties
diff --git a/src/site/site.xml b/src/site/site.xml
index ca1b03bae..0d8b667ec 100644
--- a/src/site/site.xml
+++ b/src/site/site.xml
@@ -36,7 +36,7 @@
-
+
-
diff --git a/src/site/xdoc/index.xml b/src/site/xdoc/index.xml
index e94720f1a..f42231025 100644
--- a/src/site/xdoc/index.xml
+++ b/src/site/xdoc/index.xml
@@ -58,13 +58,13 @@ usage: ls
-C list entries by columns
- Check out the introduction page for a detailed presentation.
+ Check out the introduction page for a detailed presentation.
- A full User's Guide is available
+ A full User's Guide is available
as are various project reports .
diff --git a/src/site/xdoc/security.xml b/src/site/xdoc/security.xml
index 34b02c75d..740c55065 100644
--- a/src/site/xdoc/security.xml
+++ b/src/site/xdoc/security.xml
@@ -47,5 +47,10 @@
+
-
\ No newline at end of file
+
diff --git a/src/test/java/org/apache/commons/cli/ApplicationTest.java b/src/test/java/org/apache/commons/cli/ApplicationTest.java
index 59b32917a..636580926 100644
--- a/src/test/java/org/apache/commons/cli/ApplicationTest.java
+++ b/src/test/java/org/apache/commons/cli/ApplicationTest.java
@@ -40,6 +40,7 @@ Licensed to the Apache Software Foundation (ASF) under one or more
*/
@SuppressWarnings("deprecation") // tests some deprecated classes
class ApplicationTest {
+
/**
* Ant test
*/
diff --git a/src/test/java/org/apache/commons/cli/CommandLineTest.java b/src/test/java/org/apache/commons/cli/CommandLineTest.java
index 6de605a54..98c7eb79a 100644
--- a/src/test/java/org/apache/commons/cli/CommandLineTest.java
+++ b/src/test/java/org/apache/commons/cli/CommandLineTest.java
@@ -374,14 +374,14 @@ void testGetOptionsCtor() {
/**
* Test for get option value with and without default values. Verifies that deprecated options only report as
* deprecated once.
- * @param args the argument strings to parse.
- * @param opt the option to check for values with.
- * @param optionGroup the option group to check for values with.
+ * @param args The argument strings to parse.
+ * @param opt The option to check for values with.
+ * @param optionGroup The option group to check for values with.
* @param optDep {@code true} if the opt is deprecated.
* @param optValue The value expected from opt.
* @param grpDep {@code true} if the group is deprecated.
- * @param grpValue the value expected from the group.
- * @param grpOpt the option that is expected to be processed by the group.
+ * @param grpValue The value expected from the group.
+ * @param grpOpt The option that is expected to be processed by the group.
* @throws ParseException on parse error.
*/
@ParameterizedTest(name = "{0}, {1}")
@@ -480,14 +480,14 @@ void testGetOptionValue(final String[] args, final Option opt, final OptionGroup
/**
* Test for get option values with and without default values. Verifies that deprecated options only report as
* deprecated once.
- * @param args the argument strings to parse.
- * @param opt the option to check for values with.
- * @param optionGroup the option group to check for values with.
+ * @param args The argument strings to parse.
+ * @param opt The option to check for values with.
+ * @param optionGroup The option group to check for values with.
* @param optDep {@code true} if the opt is deprecated.
* @param optValue The value expected from opt.
* @param grpDep {@code true} if the group is deprecated.
- * @param grpValue the value expected from the group.
- * @param grpOpt the option that is expected to be processed by the group.
+ * @param grpValue The value expected from the group.
+ * @param grpOpt The option that is expected to be processed by the group.
* @throws ParseException on parse error.
*/
@ParameterizedTest(name = "{0}, {1}")
@@ -724,14 +724,14 @@ void testGetParsedOptionValues(final String[] args, final Option opt, final Opti
/**
* Tests the hasOption calls.
- * @param args the argument strings to parse.
- * @param opt the option to check for values with.
- * @param optionGroup the option group to check for values with.
+ * @param args The argument strings to parse.
+ * @param opt The option to check for values with.
+ * @param optionGroup The option group to check for values with.
* @param optDep {@code true} if the opt is deprecated.
* @param has {@code true} if the opt is present.
* @param grpDep {@code true} if the group is deprecated.
* @param hasGrp {@code true} if the group is present.
- * @param grpOpt the option that is expected to be processed by the group.
+ * @param grpOpt The option that is expected to be processed by the group.
* @throws ParseException on parsing error.
*/
@ParameterizedTest(name = "{0}, {1}")
@@ -780,14 +780,14 @@ void testHasOption(final String[] args, final Option opt, final OptionGroup opti
/**
* Tests the hasOption calls.
- * @param args the argument strings to parse.
- * @param opt the option to check for values with.
- * @param optionGroup the option group to check for values with.
+ * @param args The argument strings to parse.
+ * @param opt The option to check for values with.
+ * @param optionGroup The option group to check for values with.
* @param optDep {@code true} if the opt is deprecated.
* @param has {@code true} if the opt is present.
* @param grpDep {@code true} if the group is deprecated.
* @param hasGrp {@code true} if the group is present.
- * @param grpOpt the option that is expected to be processed by the group.
+ * @param grpOpt The option that is expected to be processed by the group.
* @throws ParseException on parsing error.
*/
@ParameterizedTest(name = "{0}, {1}")
@@ -831,14 +831,14 @@ void testHasOptionNoDeprecationHandler(final String[] args, final Option opt, fi
/**
* Tests the hasOption calls.
- * @param args the argument strings to parse.
- * @param opt the option to check for values with.
- * @param optionGroup the option group to check for values with.
+ * @param args The argument strings to parse.
+ * @param opt The option to check for values with.
+ * @param optionGroup The option group to check for values with.
* @param optDep {@code true} if the opt is deprecated.
* @param has {@code true} if the opt is present.
* @param grpDep {@code true} if the group is deprecated.
* @param hasGrp {@code true} if the group is present.
- * @param grpOpt the option that is expected to be processed by the group.
+ * @param grpOpt The option that is expected to be processed by the group.
* @throws ParseException on parsing error.
*/
@ParameterizedTest(name = "{0}, {1}")
diff --git a/src/test/java/org/apache/commons/cli/ConverterTests.java b/src/test/java/org/apache/commons/cli/ConverterTests.java
index 8691d0757..57cb63f99 100644
--- a/src/test/java/org/apache/commons/cli/ConverterTests.java
+++ b/src/test/java/org/apache/commons/cli/ConverterTests.java
@@ -14,6 +14,7 @@ Licensed to the Apache Software Foundation (ASF) under one or more
See the License for the specific language governing permissions and
limitations under the License.
*/
+
package org.apache.commons.cli;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -26,12 +27,14 @@ Licensed to the Apache Software Foundation (ASF) under one or more
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
+import java.util.Locale;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
+import org.junitpioneer.jupiter.DefaultLocale;
/**
* Tests for standard Converters.
@@ -40,13 +43,13 @@ public class ConverterTests {
// A class without a default constructor.
public class AClassWithoutADefaultConstructor {
+
public AClassWithoutADefaultConstructor(final int i) {
}
}
private static Stream numberTestParameters() {
final List lst = new ArrayList<>();
-
lst.add(Arguments.of("123", Long.valueOf("123")));
lst.add(Arguments.of("12.3", Double.valueOf("12.3")));
lst.add(Arguments.of("-123", Long.valueOf("-123")));
@@ -56,19 +59,15 @@ private static Stream numberTestParameters() {
lst.add(Arguments.of("0x5F", null));
lst.add(Arguments.of("2,3", null));
lst.add(Arguments.of("1.2.3", null));
-
return lst.stream();
}
@Test
void testClass() throws Exception {
-
assertNotNull(Converter.CLASS.apply(this.getClass().getName()), this.getClass().getName());
assertNotNull(Converter.CLASS.apply(this.getClass().getCanonicalName()), this.getClass().getCanonicalName());
- assertThrows(ClassNotFoundException.class, () -> Converter.CLASS.apply(this.getClass().getSimpleName()),
- this.getClass().getSimpleName());
+ assertThrows(ClassNotFoundException.class, () -> Converter.CLASS.apply(this.getClass().getSimpleName()), this.getClass().getSimpleName());
assertNotNull(Converter.CLASS.apply(this.getClass().getTypeName()), this.getClass().getTypeName());
-
assertThrows(ClassNotFoundException.class, () -> Converter.CLASS.apply("foo.bar"));
assertNotNull(Converter.CLASS.apply(AClassWithoutADefaultConstructor.class.getName()));
}
@@ -76,21 +75,63 @@ void testClass() throws Exception {
@Test
void testDate() throws Exception {
assertThrows(java.text.ParseException.class, () -> Converter.DATE.apply("whatever"));
-
/*
- * Dates calculated from strings are dependent upon configuration and environment settings for the
- * machine on which the test is running. To avoid this problem, convert the time into a string
- * and then unparse that using the converter. This produces strings that always match the correct
- * time zone.
+ * Dates calculated from strings are dependent upon configuration and environment settings for the machine on which the test is running. To avoid this
+ * problem, convert the time into a string and then unparse that using the converter. This produces strings that always match the correct time zone.
*/
final Date expected = new Date(1023400137000L);
final DateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
final String formatted = dateFormat.format(expected);
assertEquals(expected, Converter.DATE.apply(formatted));
-
assertThrows(java.text.ParseException.class, () -> Converter.DATE.apply("Jun 06 17:48:57 EDT 2002"));
}
+ @Test
+ @DefaultLocale(language = "de", country = "DE")
+ void testDateLocaleDe() throws Exception {
+ final Date expected = new Date(1023400137000L);
+ final String formatted = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy").format(expected);
+ assertEquals(expected, Converter.DATE.apply(formatted));
+ }
+
+ @Test
+ @DefaultLocale(language = "de", country = "DE")
+ void testDateLocaleDeEnglishInput() throws Exception {
+ // Date.toString() always emits English month/day names, so the converter must still parse
+ // them when the default locale is not English.
+ final Date expected = new Date(1023400137000L);
+ final String formatted = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH).format(expected);
+ assertEquals(expected, Converter.DATE.apply(formatted));
+ }
+
+ @Test
+ void testDateRejectsInvalid() {
+ // A lenient SimpleDateFormat rolls "Feb 30" over to March 1; the converter must reject
+ // out-of-range fields instead of silently returning a wrong Date.
+ assertThrows(java.text.ParseException.class, () -> Converter.DATE.apply("Fri Feb 30 12:00:00 UTC 2024"));
+ assertThrows(java.text.ParseException.class, () -> Converter.DATE.apply("Mon Jan 32 00:00:00 UTC 2024"));
+ }
+
+ @Test
+ void testDateRejectsTrailingText() throws Exception {
+ final Date expected = new Date(1023400137000L);
+ final String formatted = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy").format(expected);
+ assertEquals(expected, Converter.DATE.apply(formatted));
+ assertThrows(java.text.ParseException.class, () -> Converter.DATE.apply(formatted + " trailing"));
+ }
+
+ @Test
+ @DefaultLocale(language = "de", country = "DE")
+ void testDateRejectsTrailingTextLocaleDe() throws Exception {
+ // Trailing text must be rejected even when a non-English default locale parses the date, and
+ // the reported error position should point past the parsed date rather than at index 0.
+ final Date expected = new Date(1023400137000L);
+ final String formatted = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy").format(expected);
+ assertEquals(expected, Converter.DATE.apply(formatted));
+ final java.text.ParseException e = assertThrows(java.text.ParseException.class, () -> Converter.DATE.apply(formatted + " trailing"));
+ assertEquals(formatted.length(), e.getErrorOffset());
+ }
+
@Test
void testFile() throws Exception {
final URL url = this.getClass().getClassLoader().getResource("./org/apache/commons/cli/existing-readable.file");
@@ -112,10 +153,8 @@ void testNumber(final String str, final Number expected) throws Exception {
void testObject() throws Exception {
assertNotNull(Converter.OBJECT.apply(this.getClass().getName()), this.getClass().getName());
assertNotNull(Converter.OBJECT.apply(this.getClass().getCanonicalName()), this.getClass().getCanonicalName());
- assertThrows(ClassNotFoundException.class, () -> Converter.OBJECT.apply(this.getClass().getSimpleName()),
- this.getClass().getSimpleName());
+ assertThrows(ClassNotFoundException.class, () -> Converter.OBJECT.apply(this.getClass().getSimpleName()), this.getClass().getSimpleName());
assertNotNull(Converter.OBJECT.apply(this.getClass().getTypeName()), this.getClass().getTypeName());
-
assertThrows(ClassNotFoundException.class, () -> Converter.OBJECT.apply("foo.bar"));
assertThrows(NoSuchMethodException.class, () -> Converter.OBJECT.apply(AClassWithoutADefaultConstructor.class.getName()));
}
diff --git a/src/test/java/org/apache/commons/cli/OptionsTest.java b/src/test/java/org/apache/commons/cli/OptionsTest.java
index f0ac95258..d6b2f4667 100644
--- a/src/test/java/org/apache/commons/cli/OptionsTest.java
+++ b/src/test/java/org/apache/commons/cli/OptionsTest.java
@@ -182,6 +182,20 @@ void testGetMatchingOpts() {
assertToStrings(options.getOption("verbose"));
}
+ @Test
+ void testGetMatchingOptsEmptyName() throws Exception {
+ final Options options = new Options();
+ options.addOption(Option.builder("c").longOpt("config-file").hasArg().get());
+ assertTrue(options.getMatchingOptions(null).isEmpty());
+ assertTrue(options.getMatchingOptions("").isEmpty());
+ assertTrue(options.getMatchingOptions("-").isEmpty());
+ assertTrue(options.getMatchingOptions("--").isEmpty());
+ // "--=value" names no option, so it must not bind a value to config-file
+ for (final CommandLineParser parser : new CommandLineParser[] { new DefaultParser(), new PosixParser() }) {
+ assertThrows(UnrecognizedOptionException.class, () -> parser.parse(options, new String[] { "--=/etc/shadow" }));
+ }
+ }
+
@Test
void testGetOptionsGroups() {
final Options options = new Options();
diff --git a/src/test/java/org/apache/commons/cli/TypeHandlerTest.java b/src/test/java/org/apache/commons/cli/TypeHandlerTest.java
index 987450734..fe14877ac 100644
--- a/src/test/java/org/apache/commons/cli/TypeHandlerTest.java
+++ b/src/test/java/org/apache/commons/cli/TypeHandlerTest.java
@@ -134,6 +134,9 @@ private static Stream createValueTestParameters() throws MalformedURL
list.add(Arguments.of("5", Character.class, '5'));
list.add(Arguments.of("5.5", Character.class, '5'));
list.add(Arguments.of("\\u0124", Character.class, Character.toChars(0x0124)[0]));
+ list.add(Arguments.of("\\u1F600", Character.class, ParseException.class));
+ list.add(Arguments.of("\\uD800", Character.class, ParseException.class));
+ list.add(Arguments.of("\\uDFFF", Character.class, ParseException.class));
list.add(Arguments.of("just-a-string", Double.class, ParseException.class));
list.add(Arguments.of("5", Double.class, 5d));
diff --git a/src/test/java/org/apache/commons/cli/bug/BugCLI162Test.java b/src/test/java/org/apache/commons/cli/bug/BugCLI162Test.java
index a1a0e9f06..2db045fcf 100644
--- a/src/test/java/org/apache/commons/cli/bug/BugCLI162Test.java
+++ b/src/test/java/org/apache/commons/cli/bug/BugCLI162Test.java
@@ -32,6 +32,7 @@
import org.junit.jupiter.api.Test;
class BugCLI162Test {
+
/** Constant for the line separator. */
private static final String CR = System.lineSeparator();
diff --git a/src/test/java/org/apache/commons/cli/example/AptHelpAppendable.java b/src/test/java/org/apache/commons/cli/example/AptHelpAppendable.java
index cbedfe225..db335e095 100644
--- a/src/test/java/org/apache/commons/cli/example/AptHelpAppendable.java
+++ b/src/test/java/org/apache/commons/cli/example/AptHelpAppendable.java
@@ -51,7 +51,7 @@ public class AptHelpAppendable extends FilterHelpAppendable {
/**
* Constructs an appendable filter built on top of the specified underlying appendable.
*
- * @param output the underlying appendable to be assigned to the field {@code this.output} for later use, or {@code null} if this instance is to be created
+ * @param output The underlying appendable to be assigned to the field {@code this.output} for later use, or {@code null} if this instance is to be created
* without an underlying stream.
*/
public AptHelpAppendable(final Appendable output) {
diff --git a/src/test/java/org/apache/commons/cli/example/AptHelpAppendableTest.java b/src/test/java/org/apache/commons/cli/example/AptHelpAppendableTest.java
index b4a9408e9..d87de22b0 100644
--- a/src/test/java/org/apache/commons/cli/example/AptHelpAppendableTest.java
+++ b/src/test/java/org/apache/commons/cli/example/AptHelpAppendableTest.java
@@ -91,9 +91,9 @@ void testAppendTableTest() throws IOException {
final String[] headers = { "one", "two", "three" };
// @formatter:off
final List> rows = Arrays.asList(
- Arrays.asList(new String[]{"uno", "dos", "tres"}),
- Arrays.asList(new String[]{"aon", "dhá", "trí"}),
- Arrays.asList(new String[]{"واحد", "اثنين", "ثلاثة"})
+ Arrays.asList("uno", "dos", "tres"),
+ Arrays.asList("aon", "dhá", "trí"),
+ Arrays.asList("واحد", "اثنين", "ثلاثة")
);
// @formatter:on
List expected = new ArrayList<>();
diff --git a/src/test/java/org/apache/commons/cli/example/XhtmlHelpAppendable.java b/src/test/java/org/apache/commons/cli/example/XhtmlHelpAppendable.java
index 51ae058d0..00f901ab6 100644
--- a/src/test/java/org/apache/commons/cli/example/XhtmlHelpAppendable.java
+++ b/src/test/java/org/apache/commons/cli/example/XhtmlHelpAppendable.java
@@ -34,7 +34,7 @@ public class XhtmlHelpAppendable extends FilterHelpAppendable {
/**
* Constructs an appendable filter built on top of the specified underlying appendable.
*
- * @param output the underlying appendable to be assigned to the field {@code this.output} for later use, or {@code null} if this instance is to be created
+ * @param output The underlying appendable to be assigned to the field {@code this.output} for later use, or {@code null} if this instance is to be created
* without an underlying stream.
*/
public XhtmlHelpAppendable(final Appendable output) {
diff --git a/src/test/java/org/apache/commons/cli/example/XhtmlHelpAppendableTest.java b/src/test/java/org/apache/commons/cli/example/XhtmlHelpAppendableTest.java
index db78ee249..808fce1f2 100644
--- a/src/test/java/org/apache/commons/cli/example/XhtmlHelpAppendableTest.java
+++ b/src/test/java/org/apache/commons/cli/example/XhtmlHelpAppendableTest.java
@@ -85,9 +85,9 @@ void testAppendTableTest() throws IOException {
final String[] headers = { "one", "two", "three" };
// @formatter:off
final List> rows = Arrays.asList(
- Arrays.asList(new String[]{"uno", "dos", "tres"}),
- Arrays.asList(new String[]{"aon", "dhá", "trí"}),
- Arrays.asList(new String[]{"واحد", "اثنين", "ثلاثة"})
+ Arrays.asList("uno", "dos", "tres"),
+ Arrays.asList("aon", "dhá", "trí"),
+ Arrays.asList("واحد", "اثنين", "ثلاثة")
);
// @formatter:on
List expected = new ArrayList<>();
diff --git a/src/test/java/org/apache/commons/cli/help/HelpFormatterTest.java b/src/test/java/org/apache/commons/cli/help/HelpFormatterTest.java
index 41e9c08d0..e7b995bca 100644
--- a/src/test/java/org/apache/commons/cli/help/HelpFormatterTest.java
+++ b/src/test/java/org/apache/commons/cli/help/HelpFormatterTest.java
@@ -161,7 +161,27 @@ void testPrintHelpHeader() throws IOException {
}
@Test
- public void testPrintHelpWithIterableOptions() throws IOException {
+ void testPrintHelpWithDefaults() throws IOException {
+ final StringBuilder sb = new StringBuilder();
+ final TextHelpAppendable serializer = new TextHelpAppendable(sb);
+ final HelpFormatter formatter = HelpFormatter.builder().setHelpAppendable(serializer).get();
+
+ final Options options = new Options().addOption(Option.builder("a").since("1853").hasArg().desc("aaaa aaaa aaaa aaaa aaaa").get());
+
+ final List expected = new ArrayList<>();
+ expected.add(" usage: commandSyntax");
+ expected.add("");
+ expected.add(" Options Since Description ");
+ expected.add(" -a 1853 aaaa aaaa aaaa aaaa aaaa");
+ expected.add("");
+
+ formatter.printHelp("commandSyntax", options);
+ final List actual = IOUtils.readLines(new StringReader(sb.toString()));
+ assertEquals(expected, actual);
+ }
+
+ @Test
+ void testPrintHelpWithIterableOptions() throws IOException {
final StringBuilder sb = new StringBuilder();
final TextHelpAppendable serializer = new TextHelpAppendable(sb);
HelpFormatter formatter = HelpFormatter.builder().setHelpAppendable(serializer).get();
@@ -320,6 +340,39 @@ void testPrintOptions() throws IOException {
assertEquals(expected, actual);
}
+ /**
+ * Continuation description lines must share the same indent.
+ *
+ * @see [CLI-354] HelpFormatter: Description indentation is incorrect
+ */
+ @Test
+ void testPrintHelpWrappedDescriptionIndent() throws IOException {
+ final StringBuilder sb = new StringBuilder();
+ final TextHelpAppendable serializer = new TextHelpAppendable(sb);
+ final HelpFormatter formatter = HelpFormatter.builder().setHelpAppendable(serializer).setShowSince(false).get();
+ final String description = "an argument passed to the remote command. The value will be wrapped in double quotes "
+ + "and appended to the command-line. This option can be added multiple times.";
+ final Options options = new Options().addOption(Option.builder("V").longOpt("argument-value").hasArg().desc(description).get());
+
+ final List expected = new ArrayList<>();
+ expected.add(" usage: cs [-V ]");
+ expected.add("");
+ expected.add(" header");
+ expected.add("");
+ expected.add(" Options Description ");
+ expected.add(" -V, --argument-value an argument passed to the remote command. ");
+ expected.add(" The value will be wrapped in double quotes");
+ expected.add(" and appended to the command-line. This ");
+ expected.add(" option can be added multiple times. ");
+ expected.add("");
+ expected.add(" footer");
+ expected.add("");
+
+ formatter.printHelp("cs", "header", options, "footer", true);
+ final List actual = IOUtils.readLines(new StringReader(sb.toString()));
+ assertEquals(expected, actual);
+ }
+
@Test
void testSetOptionFormatBuilderTest() {
final HelpFormatter.Builder underTest = HelpFormatter.builder();
diff --git a/src/test/java/org/apache/commons/cli/help/TextHelpAppendableTest.java b/src/test/java/org/apache/commons/cli/help/TextHelpAppendableTest.java
index d29fcddbc..182cf50fc 100644
--- a/src/test/java/org/apache/commons/cli/help/TextHelpAppendableTest.java
+++ b/src/test/java/org/apache/commons/cli/help/TextHelpAppendableTest.java
@@ -37,13 +37,13 @@ Licensed to the Apache Software Foundation (ASF) under one or more
/**
* Tests {@link TextHelpAppendable}.
*/
-public final class TextHelpAppendableTest {
+final class TextHelpAppendableTest {
private StringBuilder sb;
private TextHelpAppendable underTest;
@BeforeEach
- public void setUp() {
+ void setUp() {
sb = new StringBuilder();
underTest = new TextHelpAppendable(sb);
}
@@ -280,6 +280,10 @@ void testindexOfWrapPos() {
assertThrows(IllegalArgumentException.class, () -> TextHelpAppendable.indexOfWrap("", 0, 0));
assertEquals(3, TextHelpAppendable.indexOfWrap("Hello", 4, 0));
+
+ // startPos + width must not overflow when width is TextStyle.UNSET_MAX_WIDTH
+ assertEquals(30, TextHelpAppendable.indexOfWrap(testString, TextStyle.UNSET_MAX_WIDTH, 0), "did not find break character with unbounded width");
+ assertEquals(testString.length(), TextHelpAppendable.indexOfWrap(testString, TextStyle.UNSET_MAX_WIDTH, 31), "overflow produced a negative wrap index");
}
@ParameterizedTest
diff --git a/src/test/java/org/apache/commons/cli/help/TextStyleTests.java b/src/test/java/org/apache/commons/cli/help/TextStyleTest.java
similarity index 87%
rename from src/test/java/org/apache/commons/cli/help/TextStyleTests.java
rename to src/test/java/org/apache/commons/cli/help/TextStyleTest.java
index e745922a6..2f18ae3ba 100644
--- a/src/test/java/org/apache/commons/cli/help/TextStyleTests.java
+++ b/src/test/java/org/apache/commons/cli/help/TextStyleTest.java
@@ -28,9 +28,9 @@ Licensed to the Apache Software Foundation (ASF) under one or more
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
-public class TextStyleTests {
+class TextStyleTest {
- public static Stream padTestData() {
+ static Stream padTestData() {
final List lst = new ArrayList<>();
final TextStyle.Builder builder = TextStyle.builder();
builder.setIndent(5);
@@ -71,6 +71,17 @@ public static Stream padTestData() {
builder.setAlignment(TextStyle.Alignment.CENTER);
lst.add(Arguments.of(builder.get(), " Hello world ", " Hello world "));
+ // width equal to text length + indent applies indent on continuation lines
+ builder.setMaxWidth(16);
+ builder.setAlignment(TextStyle.Alignment.LEFT);
+ lst.add(Arguments.of(builder.get(), "Hello world ", " Hello world"));
+
+ builder.setAlignment(TextStyle.Alignment.RIGHT);
+ lst.add(Arguments.of(builder.get(), " Hello world", " Hello world"));
+
+ builder.setAlignment(TextStyle.Alignment.CENTER);
+ lst.add(Arguments.of(builder.get(), " Hello world ", " Hello world "));
+
// width greater than text length and less than text length + indent creates result of text length + pad
builder.setMaxWidth(14);
builder.setAlignment(TextStyle.Alignment.LEFT);