Skip to content

Commit

Permalink
Only change package declaration if the source path needs updating
Browse files Browse the repository at this point in the history
  • Loading branch information
kennytv committed May 10, 2024
1 parent fb6e863 commit 2988966
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -1823,7 +1823,9 @@ public class Test {
java(
"""
package org.openrewrite;
import org.openrewrite.Test;
public class Sibling {
public Test test() {
return new Test();
Expand All @@ -1832,9 +1834,9 @@ public Test test() {
""",
"""
package org.openrewrite;
import org.openrewrite.subpackage.Test;
public class Sibling {
public Test test() {
return new Test();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -491,6 +491,7 @@ private static class ChangeClassDefinition extends JavaIsoVisitor<ExecutionConte
private final JavaType.Class originalType;
private final JavaType.Class targetType;
private final MethodMatcher originalConstructor;
private boolean updatePath;

private ChangeClassDefinition(String oldFullyQualifiedTypeName, String newFullyQualifiedTypeName) {
this.originalType = JavaType.ShallowClass.build(oldFullyQualifiedTypeName);
Expand All @@ -508,7 +509,8 @@ public J visit(@Nullable Tree tree, ExecutionContext ctx) {
String newFqn = fqnToPath(targetType.getFullyQualifiedName());

Path newPath = Paths.get(oldPath.replaceFirst(oldFqn, newFqn));
if (updatePath(cu, oldPath, newPath.toString())) {
updatePath = updatePath(cu, oldPath, newPath.toString());
if (updatePath) {
cu = cu.withSourcePath(newPath);
}
return super.visit(cu, ctx);
Expand All @@ -532,7 +534,7 @@ private boolean updatePath(JavaSourceFile sf, String oldPath, String newPath) {
@Override
public J.Package visitPackage(J.Package pkg, ExecutionContext ctx) {
String original = pkg.getExpression().printTrimmed(getCursor()).replaceAll("\\s", "");
if (original.equals(originalType.getPackageName())) {
if (updatePath && original.equals(originalType.getPackageName())) {
JavaType.FullyQualified fq = TypeUtils.asFullyQualified(targetType);
if (fq != null) {
if (fq.getPackageName().isEmpty()) {
Expand Down

0 comments on commit 2988966

Please sign in to comment.