Skip to content

Commit

Permalink
Fixes #557: Now validates BEFORE conversion
Browse files Browse the repository at this point in the history
  • Loading branch information
mkarg committed Dec 17, 2023
1 parent d7ec08c commit ec4b06c
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 5 deletions.
12 changes: 7 additions & 5 deletions src/main/java/com/beust/jcommander/JCommander.java
Original file line number Diff line number Diff line change
Expand Up @@ -795,6 +795,13 @@ else if (commands.isEmpty()) {
//
initMainParameterValue(arg);
String value = a; // If there's a non-quoted version, prefer that one

for(final Class<? extends IParameterValidator> validator : mainParameter.annotation.validateWith()
) {
mainParameter.description.validateParameter(validator,
"Default", value);
}

Object convertedValue = value;

// Fix
Expand All @@ -813,11 +820,6 @@ else if (commands.isEmpty()) {
}
}

for(final Class<? extends IParameterValidator> validator : mainParameter.annotation.validateWith()
) {
mainParameter.description.validateParameter(validator,
"Default", value);
}

mainParameter.description.setAssigned(true);
mainParameter.addValue(convertedValue);
Expand Down
21 changes: 21 additions & 0 deletions src/test/java/com/beust/jcommander/JCommanderTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import com.beust.jcommander.command.CommandMain;
import com.beust.jcommander.converters.EnumConverter;
import com.beust.jcommander.converters.FileConverter;
import com.beust.jcommander.converters.PathConverter;
import com.beust.jcommander.internal.Lists;
import com.beust.jcommander.internal.Maps;
import org.testng.Assert;
Expand All @@ -34,6 +35,7 @@
import java.io.*;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
Expand Down Expand Up @@ -822,6 +824,25 @@ class A {
new JCommander(a).parse("b");
}

static class PathValidator implements IParameterValidator {
@Override
public void validate(String name, String value) throws ParameterException {
if (value.contains("\0"))
throw new ParameterException("this message comes from the validator (not from the converter)");
}
}

@Test(expectedExceptions = ParameterException.class, expectedExceptionsMessageRegExp = "this message comes from the validator \\(not from the converter\\)")
public void mainParameterShouldBeValidatedBEFOREConversion() throws Throwable {
class A {
@Parameter(validateWith = PathValidator.class, converter = PathConverter.class)
public Path path;
}

A a = new A();
new JCommander(a).parse("invalid\0/path");
}

@Parameters(commandNames = {"--configure"})
public static class ConfigureArgs {
}
Expand Down

0 comments on commit ec4b06c

Please sign in to comment.