Skip to content

Commit

Permalink
fix: printf positional variables
Browse files Browse the repository at this point in the history
  • Loading branch information
Alex Eng committed Nov 17, 2017
1 parent 4be8963 commit b5befe8
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
Expand Up @@ -22,7 +22,7 @@
public class PrintfXSIExtensionValidation extends PrintfVariablesValidation {
// regex to find out whether the variable has position
private static final RegExp POSITIONAL_REG_EXP = RegExp
.compile("%(\\d+\\$)\\w+");
.compile("%(\\d+\\$).+");

public PrintfXSIExtensionValidation(ValidationId id,
ValidationMessages messages) {
Expand Down Expand Up @@ -66,19 +66,25 @@ private static boolean hasPosition(ArrayList<String> variables) {
private static ArrayList<String>
appendPosition(ArrayList<String> sourceVars) {
ArrayList<String> result = Lists.newArrayList();
String regex = buildPosRegex(sourceVars.size());
for (int i = 0; i < sourceVars.size(); i++) {
String sourceVar = sourceVars.get(i);
int position = i + 1;
String replacement = "%" + position + "$";
if (!sourceVar.contains(replacement)) {
result.add(sourceVar.replace("%", replacement));
} else {
if (sourceVar.matches(regex)) {
result.add(sourceVar);
} else {
int position = i + 1;
String replacement = "%" + position + "$";
result.add(sourceVar.replace("%", replacement));
}
}
return result;
}

private static String buildPosRegex(int size) {
String numeric = "[1-" + (size + 1) + "]";
return ".*%" + numeric + "+\\$.*";
}

private List<String> checkPosition(ArrayList<String> variables, int size) {
ArrayList<String> errors = new ArrayList<String>();

Expand Down
Expand Up @@ -60,6 +60,16 @@ public void validExplicitPositionalVariables() {
assertThat(errorList).isEmpty();
}

@Test
public void validExplicitPositionalVariables2() {
String source = "%2$.3f%1$s/day";
String target = "%2$.3f%1$s/jour";
List<String> errorList =
printfXSIExtensionValidation.validate(source, target);

assertThat(errorList).isEmpty();
}

@Test
public void mixPositionalVariablesWithNotPositional() {
String source = "%s: Read error at byte %s, while reading %lu byte";
Expand Down

0 comments on commit b5befe8

Please sign in to comment.