Skip to content

Commit

Permalink
Fix shared CST state for injected method (#411)
Browse files Browse the repository at this point in the history
This method fixes a subtle bug that occurs when the CST for a pre-cached
node is shared between codemod uses.
  • Loading branch information
nahsra authored Jul 4, 2024
1 parent 35978f5 commit 7db059c
Showing 1 changed file with 7 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,19 +25,17 @@
final class DefaultHeaderInjectionRemediator implements HeaderInjectionRemediator {

private static final Set<String> setHeaderNames = Set.of("setHeader", "addHeader");
private final MethodDeclaration fixMethod;

private static final String validatorMethodName = "stripNewlines";
private final String fixMethodCode;

DefaultHeaderInjectionRemediator() {
String fixMethodCode =
this.fixMethodCode =
"""
private static String stripNewlines(final String s) {
return s.replaceAll("[\\n\\r]", "");
}
""";

this.fixMethod = StaticJavaParser.parseMethodDeclaration(fixMethodCode);
}

@Override
Expand Down Expand Up @@ -89,6 +87,11 @@ public <T> CodemodFileScanningResult remediateAll(
&& md.getParameters().get(0).getTypeAsString().equals("String"));

if (!alreadyHasResourceValidationCallPresent) {
// one might be tempted to cache this result, but then it will be a shared resource with
// shared CST metadata and cause bugs
MethodDeclaration fixMethod = StaticJavaParser.parseMethodDeclaration(fixMethodCode);

// add the method to the class
parentClass.addMember(fixMethod);
}
}
Expand Down

0 comments on commit 7db059c

Please sign in to comment.