Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
Original file line number Diff line number Diff line change
Expand Up @@ -1427,6 +1427,55 @@ public class Target {
);
}

@Test
void doNotRenameFileWhenPathAlreadyHasNewTypeName() {
rewriteRun(
spec -> spec.recipe(new ChangeType("a.A", "a.ANew", false)),
java(
"""
package a;
public class A {
}
""",
"""
package a;
public class ANew {
}
""",
spec -> spec.path("a/ANew.java").afterRecipe(cu -> {
assertThat(PathUtils.separatorsToUnix(cu.getSourcePath().toString())).isEqualTo("a/ANew.java");
assertThat(TypeUtils.isOfClassType(cu.getClasses().getFirst().getType(), "a.ANew")).isTrue();
})
)
);
}

@Test
void doNotCorruptPathWhenDirectoryMatchesOldFqn() {
String pathWithOriginalDir = "src/main/java/com/example/Original/Original.java";
rewriteRun(
spec -> spec.recipe(new ChangeType("com.example.Original", "com.example.NewName", false)),
java(
"""
package com.example;
public class Original {
}
""",
"""
package com.example;
public class NewName {
}
""",
spec -> spec.path(pathWithOriginalDir).afterRecipe(cu -> {
String path = PathUtils.separatorsToUnix(cu.getSourcePath().toString());
assertThat(path).isEqualTo(pathWithOriginalDir);
assertThat(path).doesNotContain("NewName/Original.java");
assertThat(TypeUtils.isOfClassType(cu.getClasses().getFirst().getType(), "com.example.NewName")).isTrue();
})
)
);
}

@Issue("https://github.com/openrewrite/rewrite/issues/1904")
@Test
void updateImportPrefixWithEmptyPackage() {
Expand Down
10 changes: 7 additions & 3 deletions rewrite-java/src/main/java/org/openrewrite/java/ChangeType.java
Original file line number Diff line number Diff line change
Expand Up @@ -647,11 +647,15 @@ public J visit(@Nullable Tree tree, ExecutionContext ctx) {
}

String oldPath = cu.getSourcePath().toString().replace('\\', '/');
// The old FQN must exist in the path.
String oldFqn = fqnToPath(originalType.getFullyQualifiedName());
String newFqn = fqnToPath(targetType.getFullyQualifiedName());

Path newPath = Paths.get(oldPath.replaceFirst(oldFqn, newFqn));
int lastDot = oldPath.lastIndexOf('.');
String extension = lastDot >= 0 ? oldPath.substring(lastDot) : "";
String newPathStr = oldPath;
if (!extension.isEmpty() && oldPath.endsWith(oldFqn + extension)) {
newPathStr = oldPath.substring(0, oldPath.length() - (oldFqn + extension).length()) + newFqn + extension;
}
Path newPath = Paths.get(newPathStr);
if (updatePath(cu, oldPath, newPath.toString())) {
cu = cu.withSourcePath(newPath);
}
Expand Down
Loading