Skip to content

Commit

Permalink
439 expand dynamic arg expands non dynamic args (#440)
Browse files Browse the repository at this point in the history
* Added failing test when DynamicParameter name is beginning of Parameter name

* JCommander.expandDynamicArg, assignment string should be present in arg
  • Loading branch information
npetzall authored Dec 22, 2023
1 parent c04d6a3 commit eaac195
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/main/java/com/beust/jcommander/JCommander.java
Original file line number Diff line number Diff line change
Expand Up @@ -495,7 +495,7 @@ private List<String> expandDynamicArg(String arg) {
for (ParameterDescription pd : descriptions.values()) {
if (pd.isDynamicParameter()) {
for (String name : pd.getParameter().names()) {
if (arg.startsWith(name) && !arg.equals(name)) {
if (arg.startsWith(name) && !arg.equals(name) && arg.contains(pd.getParameter().getAssignment())) {
return Arrays.asList(name, arg.substring(name.length()));
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import com.beust.jcommander.JCommander;
import com.beust.jcommander.ParameterException;
import com.beust.jcommander.internal.Maps;

import org.testng.Assert;
import org.testng.annotations.Test;

Expand Down Expand Up @@ -55,4 +54,12 @@ public static void main(String[] args) {
DynamicParameterTest dpt = new DynamicParameterTest();
dpt.simpleWithSpaces();
}

@Test
public void shouldNotBreakSimilarParameter() {
ShadowingParameter shadowingParameter = new ShadowingParameter();
new JCommander(shadowingParameter).parse("-abc", "abc", "-ab", "a=b");
Assert.assertEquals(shadowingParameter.abc, "abc");
Assert.assertEquals(shadowingParameter.ab.get("a"), "b");
}
}
20 changes: 20 additions & 0 deletions src/test/java/com/beust/jcommander/dynamic/ShadowingParameter.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package com.beust.jcommander.dynamic;

import com.beust.jcommander.DynamicParameter;
import com.beust.jcommander.Parameter;

import java.util.HashMap;
import java.util.Map;

public class ShadowingParameter {

@Parameter(
names = "-abc"
)
String abc;
@DynamicParameter(
names = "-ab"
)
Map<String,String> ab = new HashMap<>();

}

0 comments on commit eaac195

Please sign in to comment.