Skip to content

Fix optional argument without an argument count - #454

Open
SonicHedghog wants to merge 1 commit into
apache:masterfrom
SonicHedghog:patch-optional-arg-npe
Open

SonicHedghog wants to merge 1 commit into
apache:masterfrom
SonicHedghog:patch-optional-arg-npe

Conversation

@SonicHedghog

Copy link
Copy Markdown

Option.setOptionalArg(true) can leave an option in the inconsistent state optionalArg=true with argCount=UNINITIALIZED. When that option receives an equals-form value, DefaultParser treats it as accepting an argument but leaves currentOption unset, so a NullPointerException escapes parse() instead of producing a parsed value or a ParseException.

Reproducer against 1.11.0 and current master:

Option option = new Option("o", "opt", false, "optional");
option.setOptionalArg(true);
Options options = new Options().addOption(option);
new DefaultParser().parse(options, new String[] { "-o=x" });

Actual result:

java.lang.NullPointerException: Cannot invoke "org.apache.commons.cli.Option.processValue(String)" because "this.currentOption" is null

Option.Builder.optionalArg(boolean) already initializes an uninitialized argument count to one. This change makes the public setter consistent with the builder, so the option behaves as an optional single-argument option and -o=x parses as x. The regression test in DefaultParserTest fails without the production change and passes with it.

Verification: the default Maven build (mvn) passes locally.

  • Read the contribution guidelines for this project.
  • Read the ASF Generative Tooling Guidance if you use Artificial Intelligence (AI).
  • 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? Devin prepared the change, regression test, commit, and this description under human direction.
  • Run a successful build using the default Maven 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.
  • Each commit in the pull request should have a meaningful subject line and body. Note that a maintainer may squash commits during the merge process.

Initialize an uninitialized argument count when setOptionalArg(true) is
called, matching Option.Builder.optionalArg(boolean). This keeps the
option state consistent when equals-form values are parsed.

Assisted-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant