Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add HCL FindAndReplaceLiteral Recipe #4362

Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
/*
* Copyright 2022 the original author or authors.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openrewrite.hcl.search;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.openrewrite.ExecutionContext;
import org.openrewrite.FindSourceFiles;
import org.openrewrite.Option;
import org.openrewrite.Preconditions;
import org.openrewrite.Recipe;
import org.openrewrite.TreeVisitor;
import org.openrewrite.hcl.HclIsoVisitor;
import org.openrewrite.hcl.tree.Hcl;
import org.openrewrite.internal.lang.Nullable;
import org.openrewrite.marker.AlreadyReplaced;
import org.openrewrite.marker.Marker;

import java.util.Arrays;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static org.openrewrite.Tree.randomId;

public class FindAndReplaceLiteral extends Recipe {

@Override
public String getDisplayName() {
return "Find and replace literals in HCL files";
}

@Override
public String getDescription() {
return "Find and replace literal values in HCL files. This recipe parses the source files on which it runs"
+ "as HCL, meaning you can execute HCL language-specific recipes before and after this recipe in a single recipe run.";
}

@Option(
displayName = "Find", description= "The literal to find (and replace)", example = "blacklist"
)
private final String find;

@Option(displayName = "Replace",
description = "The replacement literal for `find`. This snippet can be multiline.",
example = "denylist",
required = false)
private final @Nullable String replace;

@Option(displayName = "Regex",
description = "Default false. If true, `find` will be interpreted as a Regular Expression, and capture group contents will be available in `replace`.",
required = false)
private final @Nullable Boolean regex;

@Option(displayName = "Case sensitive",
description = "If `true` the search will be sensitive to case. Default `false`.", required = false)
private final @Nullable Boolean caseSensitive;

@Option(displayName = "Regex multiline mode", description =
"When performing a regex search setting this to `true` allows \"^\" and \"$\" to match the beginning and end of lines, respectively. "
+ "When performing a regex search when this is `false` \"^\" and \"$\" will match only the beginning and ending of the entire source file, respectively."
+ "Has no effect when not performing a regex search. Default `false`.", required = false)
private final @Nullable Boolean multiline;

@Option(displayName = "Regex dot all", description =
"When performing a regex search setting this to `true` allows \".\" to match line terminators."
+ "Has no effect when not performing a regex search. Default `false`.", required = false)
private final @Nullable Boolean dotAll;

@Option(displayName = "File pattern", description =
"A glob expression that can be used to constrain which directories or source files should be searched. "
+ "Multiple patterns may be specified, separated by a semicolon `;`. "
+ "If multiple patterns are supplied any of the patterns matching will be interpreted as a match. "
+ "When not set, all source files are searched. ", required = false, example = "**/*.tf")
private final @Nullable String filePattern;

@JsonCreator
public FindAndReplaceLiteral(@JsonProperty("find") final String find, @JsonProperty("replace") final @Nullable String replace, @JsonProperty("regex") final @Nullable Boolean regex,
@JsonProperty("caseSensitive") final @Nullable Boolean caseSensitive, @JsonProperty("multiline") final @Nullable Boolean multiline, @JsonProperty("dotAll") final @Nullable Boolean dotAll,
@JsonProperty("filePattern") final @Nullable String filePattern) {
this.find = find;
this.replace = replace;
this.regex = regex;
this.caseSensitive = caseSensitive;
this.multiline = multiline;
this.dotAll = dotAll;
this.filePattern = filePattern;
}

@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
TreeVisitor<?, ExecutionContext> visitor = new HclIsoVisitor<ExecutionContext>(){

@Override
public Hcl.Literal visitLiteral(final Hcl.Literal literal, final ExecutionContext executionContext) {
l-ferguson marked this conversation as resolved.
Show resolved Hide resolved
for(Marker marker : literal.getMarkers().getMarkers()) {
if (marker instanceof AlreadyReplaced) {
AlreadyReplaced alreadyReplaced = (AlreadyReplaced) marker;
if (Objects.equals(find, alreadyReplaced.getFind()) && Objects.equals(replace,
alreadyReplaced.getReplace())) {
return literal;
}
}
}
String searchStr = find;
if (!Boolean.TRUE.equals(regex)) {
searchStr = Pattern.quote(searchStr);
}
int patternOptions = 0;
if (!Boolean.TRUE.equals(caseSensitive)) {
patternOptions |= Pattern.CASE_INSENSITIVE;
}
if (Boolean.TRUE.equals(multiline)) {
patternOptions |= Pattern.MULTILINE;
}
if (Boolean.TRUE.equals(dotAll)) {
patternOptions |= Pattern.DOTALL;
}
Pattern pattern = Pattern.compile(searchStr, patternOptions);
Matcher matcher = pattern.matcher(literal.getValue().toString());
if(!matcher.find()){
return literal;
}
String replacement = replace == null ? "" : replace;
if (!Boolean.TRUE.equals(regex)) {
replacement = replacement.replace("$", "\\$");
}
String newLiteral = matcher.replaceAll(replacement);
return literal.withValue(newLiteral).withValueSource(newLiteral)
.withMarkers(literal.getMarkers().add(new AlreadyReplaced(randomId(), find, replace)));
}
};
//noinspection DuplicatedCode
if (filePattern != null) {
//noinspection unchecked
TreeVisitor<?, ExecutionContext> check = Preconditions.or(Arrays.stream(filePattern.split(";"))
.map(FindSourceFiles::new)
.map(Recipe::getVisitor)
.toArray(TreeVisitor[]::new));

visitor = Preconditions.check(check, visitor);
}
return visitor;
}
}
l-ferguson marked this conversation as resolved.
Show resolved Hide resolved
timtebeek marked this conversation as resolved.
Show resolved Hide resolved
Loading