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 RegExp support to ChangeTagValue recipe #4733

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 25 additions & 4 deletions rewrite-xml/src/main/java/org/openrewrite/xml/ChangeTagValue.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,21 @@
*/
package org.openrewrite.xml;

import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Value;
import lombok.NoArgsConstructor;
import lombok.Data;
import org.jspecify.annotations.Nullable;
import org.openrewrite.ExecutionContext;
import org.openrewrite.Option;
import org.openrewrite.Recipe;
import org.openrewrite.TreeVisitor;
import org.openrewrite.xml.tree.Xml;

@Value
@AllArgsConstructor
@EqualsAndHashCode(callSuper = false)
@NoArgsConstructor
@Data
public class ChangeTagValue extends Recipe {

@Option(displayName = "Element name",
Expand All @@ -45,6 +49,12 @@ public class ChangeTagValue extends Recipe {
example = "user")
String newValue;

@Option(displayName = "Regex",
description = "Default false. If true, `find` will be interpreted as a [Regular Expression](https://en.wikipedia.org/wiki/Regular_expression), and capture group contents will be available in `replace`.",
required = false)
@Nullable
Boolean regex;

@Override
public String getDisplayName() {
return "Change XML tag value";
Expand All @@ -65,12 +75,23 @@ public Xml visitTag(Xml.Tag tag, ExecutionContext ctx) {
if (xPathMatcher.matches(getCursor())) {
// if either no oldValue is supplied OR oldValue equals the value of this tag
// then change the value to the newValue supplied
if (oldValue == null || oldValue.equals(tag.getValue().orElse(null))) {
doAfterVisit(new ChangeTagValueVisitor<>(tag, newValue));
if (!Boolean.TRUE.equals(regex) &&
(oldValue == null || oldValue.equals(tag.getValue().orElse(null)))) {
doAfterVisit(new ChangeTagValueVisitor<>(tag, oldValue, newValue, Boolean.FALSE));
} else if (Boolean.TRUE.equals(regex) && oldValue != null) {
doAfterVisit(new ChangeTagValueVisitor<>(tag, oldValue, newValue, Boolean.TRUE));
}
}
return super.visitTag(tag, ctx);
}
};
}

public ChangeTagValue(final String elementName, final @javax.annotation.Nullable String oldValue,
anthochristen marked this conversation as resolved.
Show resolved Hide resolved
final String newValue) {
this.elementName = elementName;
this.oldValue = oldValue;
this.regex = Boolean.FALSE;
this.newValue = newValue;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,44 +14,85 @@
* limitations under the License.
*/
package org.openrewrite.xml;

import org.jspecify.annotations.Nullable;
import org.openrewrite.marker.AlreadyReplaced;
import org.openrewrite.marker.Markers;
import org.openrewrite.xml.tree.Xml;

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

import static java.util.Collections.singletonList;
import static org.openrewrite.Tree.randomId;

public class ChangeTagValueVisitor<P> extends XmlVisitor<P> {

private final Xml.Tag scope;
private final String value;
private final String newValue;
@Nullable
private final String oldValue;
private final boolean regexp;

public ChangeTagValueVisitor(Xml.Tag scope, String value) {
public ChangeTagValueVisitor(final Xml.Tag scope, final @javax.annotation.Nullable String oldValue,
anthochristen marked this conversation as resolved.
Show resolved Hide resolved
final String newValue, final Boolean regexp) {
this.scope = scope;
this.value = value;
this.oldValue = oldValue;
this.newValue = newValue;
this.regexp = Boolean.TRUE.equals(regexp);
}

public ChangeTagValueVisitor(final Xml.Tag scope, final String newValue) {
this.scope = scope;
this.oldValue = null;
this.newValue = newValue;
this.regexp = Boolean.FALSE;
}

@Override
public Xml visitTag(Xml.Tag tag, P p) {
Xml.Tag t = (Xml.Tag) super.visitTag(tag, p);

if (scope.isScope(t)) {
if(Objects.equals(newValue, oldValue)) {
return tag;
}

String prefix = "";
String afterText = "";
if (t.getContent() != null && t.getContent().size() == 1 && t.getContent().get(0) instanceof Xml.CharData) {
Xml.CharData existingValue = (Xml.CharData) t.getContent().get(0);
final Xml.CharData existingValue = (Xml.CharData) t.getContent().get(0);
final String text = existingValue.getText();

final boolean alreadyProcessed = this.regexp && existingValue.getMarkers()
.findAll(AlreadyReplaced.class)
.stream()
.anyMatch(m -> m.getFind().equals(oldValue) && newValue.equals(m.getReplace()));

if (existingValue.getText().equals(value)) {
if (alreadyProcessed || (!regexp && text.equals(newValue))) {
return tag;
}

// if the previous content was also character data, preserve its prefix and afterText
prefix = existingValue.getPrefix();
afterText = existingValue.getAfterText();

if(regexp && oldValue != null && Pattern.compile(oldValue).matcher(text).find()) {
final String newContent = text.replaceAll(oldValue, Matcher.quoteReplacement(newValue));
final Markers markers = Markers.build(
singletonList( new AlreadyReplaced(randomId(),oldValue, newValue))
);
t = t.withContent(singletonList(new Xml.CharData(randomId(),
prefix, markers, false, newContent, afterText)));
}

}
if(!regexp) {
t = t.withContent(singletonList(new Xml.CharData(randomId(),
prefix, Markers.EMPTY, false, newValue, afterText)));
}
t = t.withContent(singletonList(new Xml.CharData(randomId(),
prefix, Markers.EMPTY, false, value, afterText)));
}

return t;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
/*
* Copyright 2024 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.xml;
import org.junit.jupiter.api.Test;
import org.openrewrite.DocumentExample;
import org.openrewrite.test.RewriteTest;
import static org.openrewrite.xml.Assertions.xml;

class ChangeTagValueTest implements RewriteTest {

@DocumentExample
@Test
void rewriteEmptyTagValue() {
rewriteRun(
spec -> spec.recipe(
new ChangeTagValue("/dependency/version",
null, "2.0", null)),
xml(
"""
<dependency>
<version/>
</dependency>
""",
"""
<dependency>
<version>2.0</version>
</dependency>
"""
, spec -> spec.path("pom.xml"))
);
}

@Test
void rewriteTagValueSubstring() {
rewriteRun(
spec -> spec.recipe(
new ChangeTagValue("/dependency/version",
"SNAPSHOT", "RELEASE", Boolean.TRUE)
),
xml("""
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
xml("""
xml(
"""

<dependency>
<group>com.company.project</group>
<group>artifact</group>
<version>1.2.3-SNAPSHOT</version>
</dependency>
""",
"""
<dependency>
<group>com.company.project</group>
<group>artifact</group>
anthochristen marked this conversation as resolved.
Show resolved Hide resolved
<version>1.2.3-RELEASE</version>
</dependency>
""", spec -> spec.path("pom.xml")
)
);
}


@Test
void appendTagValue() {
rewriteRun(
spec -> spec.recipe(
new ChangeTagValue("/dependency/version",
"$", "-RELEASE", Boolean.TRUE)
),
xml("""
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
xml("""
xml(
"""

<dependency>
<group>com.company.project</group>
<group>artifact</group>
<version>1.2.3</version>
</dependency>
""",
"""
<dependency>
<group>com.company.project</group>
<group>artifact</group>
<version>1.2.3-RELEASE</version>
anthochristen marked this conversation as resolved.
Show resolved Hide resolved
</dependency>
""", spec -> spec.path("pom.xml")
)
);
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
}
}

Loading