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

Update ChangeType and ChangePackage to work with SourceFileWithReference #4648

Merged
merged 24 commits into from
Nov 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/*
* 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;

import lombok.AccessLevel;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.jspecify.annotations.Nullable;
import org.openrewrite.trait.Reference;

import java.util.*;

@Incubating(since = "8.39.0")
public interface SourceFileWithReferences extends SourceFile {

References getReferences();

@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
@Getter
class References {
private final SourceFile sourceFile;
private final Set<Reference> references;

public Collection<Reference> findMatches(Reference.Matcher matcher) {
return findMatchesInternal(matcher, null);
}

public Collection<Reference> findMatches(Reference.Matcher matcher, Reference.Kind kind) {
return findMatchesInternal(matcher, kind);
}
Comment on lines +41 to +43
Copy link
Contributor

Choose a reason for hiding this comment

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

I think we might as well simplify the API by removing this method. As the caller supplies the matcher that matcher can filter on the kind.

Suggested change
public Collection<Reference> findMatches(Reference.Matcher matcher, Reference.Kind kind) {
return findMatchesInternal(matcher, kind);
}

Instead, we might want to provide something like a containsMatches() returning a boolean. But this isn't high priority.


private List<Reference> findMatchesInternal(Reference.Matcher matcher, Reference.@Nullable Kind kind) {
List<Reference> list = new ArrayList<>();
for (Reference ref : references) {
if ((kind == null || ref.getKind().equals(kind)) && ref.matches(matcher) ) {
list.add(ref);
}
}
return list;
}

public static References build(SourceFile sourceFile) {
Set<Reference> references = new HashSet<>();
ServiceLoader<Reference.Provider> loader = ServiceLoader.load(Reference.Provider.class);
loader.forEach(provider -> {
if (provider.isAcceptable(sourceFile)) {
references.addAll(provider.getReferences(sourceFile));
}
});
return new References(sourceFile, references);
}
}
}

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -15,29 +15,48 @@
*/
package org.openrewrite.trait;

import org.openrewrite.Incubating;
import org.openrewrite.SourceFile;
import org.openrewrite.Tree;
import org.openrewrite.*;

import java.util.Set;

@Incubating(since = "8.39.0")
public interface TypeReference extends Trait<Tree> {
public interface Reference extends Trait<Tree> {

String getName();
enum Kind {
TYPE,
PACKAGE
}

Kind getKind();

String getValue();

default boolean supportsRename() {
return false;
}

default boolean matches(Matcher matcher) {
return matcher.matchesName(getName());
return matcher.matchesReference(this);
}

default TreeVisitor<Tree, ExecutionContext> rename(Renamer renamer, String replacement) {
return renamer.rename(replacement);
}

interface Provider {

Set<TypeReference> getTypeReferences(SourceFile sourceFile);
Set<Reference> getReferences(SourceFile sourceFile);

boolean isAcceptable(SourceFile sourceFile);
}

interface Matcher {
boolean matchesName(String name);
boolean matchesReference(Reference value);
}

interface Renamer {
default TreeVisitor<Tree, ExecutionContext> rename(String replacement) {
throw new UnsupportedOperationException();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@

import static org.assertj.core.api.Assertions.assertThat;
import static org.openrewrite.java.Assertions.java;
import static org.openrewrite.xml.Assertions.xml;

@SuppressWarnings("ConstantConditions")
class ChangePackageTest implements RewriteTest {
Expand Down Expand Up @@ -1702,4 +1703,26 @@ public enum MyEnum {
)
);
}

@Test
void changePackageInSpringXml() {
rewriteRun(
spec -> spec.recipe(new ChangePackage("test.type", "test.test.type", true)),
xml(
"""
<?xml version="1.0" encoding="UTF-8"?>
<beans xsi:schemaLocation="www.springframework.org/schema/beans">
<bean id="abc" class="test.type.A"/>
</beans>
""",
"""
<?xml version="1.0" encoding="UTF-8"?>
<beans xsi:schemaLocation="www.springframework.org/schema/beans">
<bean id="abc" class="test.test.type.A"/>
</beans>
"""
)
);

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@

import static org.assertj.core.api.Assertions.assertThat;
import static org.openrewrite.java.Assertions.java;
import static org.openrewrite.xml.Assertions.xml;

@SuppressWarnings("ConstantConditions")
class ChangeTypeTest implements RewriteTest {
Expand Down Expand Up @@ -2019,4 +2020,26 @@ class Letters {
);
}

@Test
void changeTypeInSpringXml() {
rewriteRun(
spec -> spec.recipe(new ChangeType("test.type.A", "test.type.B", true)),
xml(
"""
<?xml version="1.0" encoding="UTF-8"?>
<beans xsi:schemaLocation="www.springframework.org/schema/beans">
<bean id="abc" class="test.type.A"/>
</beans>
""",
"""
<?xml version="1.0" encoding="UTF-8"?>
<beans xsi:schemaLocation="www.springframework.org/schema/beans">
<bean id="abc" class="test.type.B"/>
</beans>
"""
)
);

}

}
67 changes: 60 additions & 7 deletions rewrite-java/src/main/java/org/openrewrite/java/ChangePackage.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,10 @@
import org.openrewrite.internal.ListUtils;
import org.openrewrite.java.tree.*;
import org.openrewrite.marker.SearchResult;
import org.openrewrite.trait.Reference;

import java.nio.file.Paths;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Map;

Expand Down Expand Up @@ -83,11 +85,12 @@ public Validated<Object> validate() {

@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
JavaIsoVisitor<ExecutionContext> condition = new JavaIsoVisitor<ExecutionContext>() {
TreeVisitor<?, ExecutionContext> condition = new TreeVisitor<Tree, ExecutionContext>() {
@Override
public @Nullable J preVisit(J tree, ExecutionContext ctx) {
public @Nullable Tree preVisit(@Nullable Tree tree, ExecutionContext ctx) {
stopAfterPreVisit();
if (tree instanceof JavaSourceFile) {
JavaSourceFile cu = (JavaSourceFile) requireNonNull(tree);
JavaSourceFile cu = (JavaSourceFile) tree;
if (cu.getPackageDeclaration() != null) {
String original = cu.getPackageDeclaration().getExpression()
.printTrimmed(getCursor()).replaceAll("\\s", "");
Expand All @@ -111,16 +114,48 @@ public TreeVisitor<?, ExecutionContext> getVisitor() {
}
}
}
stopAfterPreVisit();
} else if (tree instanceof SourceFileWithReferences) {
SourceFileWithReferences cu = (SourceFileWithReferences) tree;
boolean recursive = Boolean.TRUE.equals(ChangePackage.this.recursive);
String recursivePackageNamePrefix = oldPackageName + ".";
for (Reference ref : cu.getReferences().getReferences()) {
if (ref.getValue().equals(oldPackageName) || recursive && ref.getValue().startsWith(recursivePackageNamePrefix)) {
return SearchResult.found(cu);
knutwannheden marked this conversation as resolved.
Show resolved Hide resolved
}
}
}
return super.preVisit(tree, ctx);
return tree;
}
};

return Preconditions.check(condition, new ChangePackageVisitor());
return Preconditions.check(condition, new TreeVisitor<Tree, ExecutionContext>() {
@Override
public boolean isAcceptable(SourceFile sourceFile, ExecutionContext ctx) {
return sourceFile instanceof JavaSourceFile || sourceFile instanceof SourceFileWithReferences;
}

@Override
public @Nullable Tree preVisit(@Nullable Tree tree, ExecutionContext ctx) {
Laurens-W marked this conversation as resolved.
Show resolved Hide resolved
stopAfterPreVisit();
if (tree instanceof JavaSourceFile) {
return new JavaChangePackageVisitor().visit(tree, ctx, requireNonNull(getCursor().getParent()));
} else if (tree instanceof SourceFileWithReferences) {
SourceFileWithReferences sourceFile = (SourceFileWithReferences) tree;
SourceFileWithReferences.References references = sourceFile.getReferences();
boolean recursive = Boolean.TRUE.equals(ChangePackage.this.recursive);
PackageMatcher matcher = new PackageMatcher(oldPackageName, recursive);
Map<Tree, Reference> matches = new HashMap<>();
for (Reference ref : references.findMatches(matcher)) {
matches.put(ref.getTree(), ref);
}
return new ReferenceChangePackageVisitor(matches, matcher, newPackageName).visit(tree, ctx, requireNonNull(getCursor().getParent()));
}
return tree;
}
});
}

private class ChangePackageVisitor extends JavaVisitor<ExecutionContext> {
private class JavaChangePackageVisitor extends JavaVisitor<ExecutionContext> {
private static final String RENAME_TO_KEY = "renameTo";
private static final String RENAME_FROM_KEY = "renameFrom";

Expand Down Expand Up @@ -349,4 +384,22 @@ private boolean isTargetRecursivePackageName(String packageName) {
}

}

@Value
@EqualsAndHashCode(callSuper = false)
private static class ReferenceChangePackageVisitor extends TreeVisitor<Tree, ExecutionContext> {
Map<Tree, Reference> matches;
Reference.Renamer renamer;
String newPackageName;

@Override
public @Nullable Tree preVisit(@Nullable Tree tree, ExecutionContext ctx) {
Laurens-W marked this conversation as resolved.
Show resolved Hide resolved
Reference reference = matches.get(tree);
if (reference != null && reference.supportsRename()) {
return reference.rename(renamer, newPackageName).visit(tree, ctx, getCursor().getParent());
}
return tree;
}
}

}
Loading