Skip to content

(re)activate rewrite capability #4708

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

Closed
wants to merge 1 commit into from
Closed
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
13 changes: 13 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,19 @@ Eclipse settings.
It is forbidden to use _wildcard imports_ (e.g., `import static org.junit.jupiter.api.Assertions.*;`)
in Java code.

### 🚀 Code Transformation & Automated Rewriting
*(Advanced Refactoring, Modernization, and Bulk Code Changes)*

#### 🔧 Automated rewriting of source code to
- **Refactor** safely (e.g., rename methods, migrate APIs)
- **Modernize** (e.g., Java 8 → Java 17 features)
- **Fix anti-patterns** (e.g., replace `Vector` with `ArrayList`)
- **Enforce conventions** (e.g., JUnit's naming rules)

The build system incorporates [Moderne](https://moderne.io/) rewrite capabilities for automated code transformations. These modifications are environment-driven enlisted in the [junitbuild.java-library-conventions.gradle.kts](gradle/plugins/common/src/main/kotlin/junitbuild.java-library-conventions.gradle.kts)

You can use `gradle rewriteRun` to apply these changes.

#### Documentation

Text in `*.adoc` and `*.md` files should be wrapped at 90 characters whenever technically
Expand Down
4 changes: 2 additions & 2 deletions documentation/src/test/java/example/ClassTemplateDemo.java
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,9 @@ void wellKnown() {
}

// end::user_guide[]
static
public
// tag::user_guide[]
public class MyClassTemplateInvocationContextProvider
static class MyClassTemplateInvocationContextProvider
// tag::custom_line_break[]
implements ClassTemplateInvocationContextProvider {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@ public class ParameterizedMigrationDemo {
// tag::before[]
@RunWith(Parameterized.class)
// end::before[]
static
public
// tag::before[]
public class JUnit4ParameterizedClassTests {
static class JUnit4ParameterizedClassTests {

@Parameterized.Parameters
public static Iterable<Object[]> data() {
Expand Down
26 changes: 13 additions & 13 deletions documentation/src/test/java/example/ParameterizedTestDemo.java
Original file line number Diff line number Diff line change
Expand Up @@ -357,9 +357,9 @@ void testWithArgumentsSource(String argument) {
}

// end::ArgumentsSource_example[]
static
public
// tag::ArgumentsProvider_example[]
public class MyArgumentsProvider implements ArgumentsProvider {
static class MyArgumentsProvider implements ArgumentsProvider {

@Override
public Stream<? extends Arguments> provideArguments(ParameterDeclarations parameters,
Expand All @@ -375,9 +375,9 @@ void testWithArgumentsSourceWithConstructorInjection(String argument) {
assertNotNull(argument);
}

static
public
// tag::ArgumentsProviderWithConstructorInjection_example[]
public class MyArgumentsProviderWithConstructorInjection implements ArgumentsProvider {
static class MyArgumentsProviderWithConstructorInjection implements ArgumentsProvider {

private final TestInfo testInfo;

Expand Down Expand Up @@ -427,9 +427,9 @@ void testWithImplicitFallbackArgumentConversion(Book book) {
}

// end::implicit_fallback_conversion_example[]
static
public
// tag::implicit_fallback_conversion_example_Book[]
public class Book {
static class Book {

private final String title;

Expand Down Expand Up @@ -458,10 +458,10 @@ void testWithExplicitArgumentConversion(
}

// end::explicit_conversion_example[]
static
public
@SuppressWarnings({ "NullableProblems", "NullAway" })
// tag::explicit_conversion_example_ToStringArgumentConverter[]
public class ToStringArgumentConverter extends SimpleArgumentConverter {
static class ToStringArgumentConverter extends SimpleArgumentConverter {

@Override
protected Object convert(Object source, Class<?> targetType) {
Expand All @@ -474,10 +474,10 @@ protected Object convert(Object source, Class<?> targetType) {
}
// end::explicit_conversion_example_ToStringArgumentConverter[]

static
public
@SuppressWarnings({ "NullableProblems", "NullAway", "ConstantValue" })
// tag::explicit_conversion_example_TypedArgumentConverter[]
public class ToLengthArgumentConverter extends TypedArgumentConverter<String, Integer> {
static class ToLengthArgumentConverter extends TypedArgumentConverter<String, Integer> {

protected ToLengthArgumentConverter() {
super(String.class, Integer.class);
Expand Down Expand Up @@ -516,7 +516,7 @@ void testWithArgumentsAccessor(ArgumentsAccessor arguments) {
arguments.get(2, Gender.class),
arguments.get(3, LocalDate.class));

if (person.getFirstName().equals("Jane")) {
if ("Jane".equals(person.getFirstName())) {
assertEquals(Gender.F, person.getGender());
}
else {
Expand All @@ -540,9 +540,9 @@ void testWithArgumentsAggregator(@AggregateWith(PersonAggregator.class) Person p
}

// end::ArgumentsAggregator_example[]
static
public
// tag::ArgumentsAggregator_example_PersonAggregator[]
public class PersonAggregator extends SimpleArgumentsAggregator {
static class PersonAggregator extends SimpleArgumentsAggregator {
@Override
protected Person aggregateArguments(ArgumentsAccessor arguments, Class<?> targetType,
AnnotatedElementContext context, int parameterIndex) {
Expand Down
4 changes: 2 additions & 2 deletions documentation/src/test/java/example/TestInfoDemo.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,13 @@ static void beforeAll(TestInfo testInfo) {

TestInfoDemo(TestInfo testInfo) {
String displayName = testInfo.getDisplayName();
assertTrue(displayName.equals("TEST 1") || displayName.equals("test2()"));
assertTrue("TEST 1".equals(displayName) || "test2()".equals(displayName));
}

@BeforeEach
void init(TestInfo testInfo) {
String displayName = testInfo.getDisplayName();
assertTrue(displayName.equals("TEST 1") || displayName.equals("test2()"));
assertTrue("TEST 1".equals(displayName) || "test2()".equals(displayName));
}

@Test
Expand Down
4 changes: 2 additions & 2 deletions documentation/src/test/java/example/TestTemplateDemo.java
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,10 @@ void testTemplate(String fruit) {
}

// end::user_guide[]
static
public
// @formatter:off
// tag::user_guide[]
public class MyTestTemplateInvocationContextProvider
static class MyTestTemplateInvocationContextProvider
implements TestTemplateInvocationContextProvider {

@Override
Expand Down
2 changes: 1 addition & 1 deletion documentation/src/test/resources/log4j2-test.xml
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,4 @@
<AppenderRef ref="Console" />
</Root>
</Loggers>
</Configuration>
</Configuration>
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,46 @@ plugins {
id("org.openrewrite.rewrite")
}

/**
* activeRecipe("org.openrewrite.java.RemoveUnusedImports") // there are (non); fails to analyze
* activeRecipe("org.openrewrite.java.format.AutoFormat") // could remove check, spot, and all other recipes if working
* activeRecipe("org.openrewrite.java.format.BlankLines") // IndexOutOfBoundsException: Index 0 out of bounds for length 0
* activeRecipe("org.openrewrite.java.format.NormalizeFormat")
* activeRecipe("org.openrewrite.java.format.NormalizeLineBreaks")
* activeRecipe("org.openrewrite.java.format.RemoveTrailingWhitespace")
* activeRecipe("org.openrewrite.java.format.Spaces")
* activeRecipe("org.openrewrite.java.format.TabsAndIndents")
* activeRecipe("org.openrewrite.java.format.WrappingAndBraces")
* activeRecipe("org.openrewrite.java.migrate.UpgradeToJava17")
* activeRecipe("org.openrewrite.java.testing.assertj.Assertj")
* activeRecipe("org.openrewrite.java.testing.cleanup.AssertTrueNullToAssertNull")
* activeRecipe("org.openrewrite.java.testing.cleanup.TestsShouldNotBePublic")
* activeRecipe("org.openrewrite.java.testing.junit5.JUnit5BestPractices") // exclude legacy
* activeRecipe("org.openrewrite.staticanalysis.CodeCleanup")
* activeRecipe("org.openrewrite.staticanalysis.CommonStaticAnalysis")
* activeRecipe("org.openrewrite.staticanalysis.FinalizeLocalVariables")
* activeRecipe("org.openrewrite.staticanalysis.RedundantFileCreation")
* activeRecipe("org.openrewrite.staticanalysis.RemoveUnusedLocalVariables")
* activeRecipe("org.openrewrite.staticanalysis.RemoveUnusedPrivateFields")
* activeRecipe("org.openrewrite.staticanalysis.RemoveUnusedPrivateMethods") // there are non; fails to analyze (even tho it worked once)
* activeRecipe("org.openrewrite.staticanalysis.StringLiteralEquality")
* activeRecipe("org.openrewrite.text.EndOfLineAtEndOfFile")
* activeRecipe("org.openrewrite.java.migrate.UpgradeToJava21")
*/
rewrite {
activeRecipe("org.openrewrite.java.migrate.UpgradeToJava17")
activeRecipe("org.openrewrite.staticanalysis.EqualsAvoidsNull")
Copy link
Author

@Pankraz76 Pankraz76 Jul 10, 2025

Choose a reason for hiding this comment

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

Suggested change
activeRecipe("org.openrewrite.staticanalysis.EqualsAvoidsNull")

how do you prefer, might avoid this?

activeRecipe("org.openrewrite.staticanalysis.MissingOverrideAnnotation")
activeRecipe("org.openrewrite.staticanalysis.ModifierOrder")
failOnDryRunResults = true
}

/**
* rewrite("org.openrewrite.recipe:rewrite-testing-frameworks")
* rewrite("org.openrewrite.recipe:rewrite-migrate-java")
*/
dependencies {
rewrite(platform(dependencyFromLibs("openrewrite-recipe-bom")))
rewrite("org.openrewrite.recipe:rewrite-migrate-java")
rewrite("org.openrewrite.recipe:rewrite-static-analysis")
}

val mavenizedProjects: List<Project> by rootProject.extra
Expand Down Expand Up @@ -281,6 +314,9 @@ tasks {
checkstyleTest {
config = resources.text.fromFile(checkstyle.configDirectory.file("checkstyleTest.xml"))
}
check {
dependsOn(rewriteDryRun)
}
}

pluginManager.withPlugin("java-test-fixtures") {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,11 @@ spotless {
targetExclude("gradle/plugins/**/build/**")
leadingSpacesToTabs()
trimTrailingWhitespace()
endWithNewline()
}

format("documentation") {
target("*.adoc", "*.md", "src/**/*.adoc", "src/**/*.md")
trimTrailingWhitespace()
endWithNewline()
}

pluginManager.withPlugin("java") {
Expand All @@ -36,7 +34,6 @@ spotless {
val majorMinorVersion = "([0-9]+\\.[0-9]+).*".toRegex().matchEntire(fullVersion)!!.let { it.groups[1]!!.value }
eclipse(majorMinorVersion).configFile(javaFormatterConfigFile)
trimTrailingWhitespace()
endWithNewline()
removeUnusedImports()
}

Expand All @@ -46,7 +43,6 @@ spotless {
})
licenseHeaderFile(license.headerFile, "^$")
trimTrailingWhitespace()
endWithNewline()
}
}

Expand All @@ -56,7 +52,6 @@ spotless {
ktlint(requiredVersionFromLibs("ktlint"))
licenseHeaderFile(license.headerFile)
trimTrailingWhitespace()
endWithNewline()
}
configurations.named { it.startsWith("spotless") }.configureEach {
// Workaround for CVE-2024-12798 and CVE-2024-12801
Expand All @@ -74,7 +69,6 @@ spotless {
groovy {
licenseHeaderFile(license.headerFile)
trimTrailingWhitespace()
endWithNewline()
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ private ScheduledExecutorService getThreadExecutorForSameThreadInvocation() {
}

@SuppressWarnings({ "deprecation", "try" })
private static abstract class ExecutorResource implements Store.CloseableResource, AutoCloseable {
private abstract static class ExecutorResource implements Store.CloseableResource, AutoCloseable {

protected final ScheduledExecutorService executor;

Expand Down
Original file line number Diff line number Diff line change
@@ -1 +1 @@
org.junit.jupiter.engine.JupiterTestEngine
org.junit.jupiter.engine.JupiterTestEngine
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ static ParameterizedInvocationNameFormatter create(ExtensionContext extensionCon
ParameterizedDeclarationContext<?> declarationContext) {

String name = declarationContext.getDisplayNamePattern();
String pattern = name.equals(DEFAULT_DISPLAY_NAME)
String pattern = DEFAULT_DISPLAY_NAME.equals(name)
? extensionContext.getConfigurationParameter(DISPLAY_NAME_PATTERN_KEY) //
.orElse(DEFAULT_DISPLAY_NAME_PATTERN)
: name;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -381,7 +381,7 @@ private static boolean isRepeatableAnnotationContainer(Class<? extends Annotatio
return repeatableAnnotationContainerCache.computeIfAbsent(candidateContainerType, candidate -> {
// @formatter:off
Repeatable repeatable = Arrays.stream(candidate.getMethods())
.filter(attribute -> attribute.getName().equals("value") && attribute.getReturnType().isArray())
.filter(attribute -> "value".equals(attribute.getName()) && attribute.getReturnType().isArray())
.findFirst()
.map(attribute -> attribute.getReturnType().getComponentType().getAnnotation(Repeatable.class))
.orElse(null);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ List<Class<?>> scan(ModuleReference reference) {
// @formatter:off
return names.filter(name -> name.endsWith(".class"))
.map(this::className)
.filter(name -> !name.equals("module-info"))
.filter(name -> !"module-info".equals(name))
.filter(classFilter::match)
.<Class<?>> map(this::loadClassUnchecked)
.filter(classFilter::match)
Expand Down
Original file line number Diff line number Diff line change
@@ -1 +1 @@
org.junit.vintage.engine.VintageTestEngine
org.junit.vintage.engine.VintageTestEngine
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ void abstractClass() {
assertFalse(isPotentialJUnit4TestClass.test(Baz.class));
}

public static abstract class Baz {
public abstract static class Baz {
}

@Test
Expand Down
2 changes: 1 addition & 1 deletion junit-vintage-engine/src/test/resources/log4j2-test.xml
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,4 @@
<AppenderRef ref="Console" />
</Root>
</Loggers>
</Configuration>
</Configuration>
Original file line number Diff line number Diff line change
Expand Up @@ -333,7 +333,7 @@ public String generateDisplayNameForMethod(List<Class<?>> enclosingInstanceTypes
}

@DisplayNameGeneration(NoNameGenerator.class)
static abstract class AbstractTestCase {
abstract static class AbstractTestCase {
@Test
void test() {
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -417,7 +417,7 @@ void notExecutedByImplementingClass() {

}

static abstract class AbstractSuperClass implements InterfaceWithNestedClass {
abstract static class AbstractSuperClass implements InterfaceWithNestedClass {

@Nested
class NestedInAbstractClass {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ void sealedTestClassesAreTestClasses() {
.assertStatistics(stats -> stats.finished(2).succeeded(1).failed(1));
}

sealed abstract static class AbstractTestCase permits TestCase {
abstract static sealed class AbstractTestCase permits TestCase {

@Test
void succeedingTest() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ void beforeAndAfterMethodsInTestClassHierarchy() {

// -------------------------------------------------------------------

private static abstract class AbstractTestCase {
private abstract static class AbstractTestCase {

static int countSuperBeforeInvoked = 0;
static int countSuperAfterInvoked = 0;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -529,7 +529,7 @@ private TestMethodTestDescriptor nestedMethodDescriptor() {
}
}

static abstract class BaseNestedTestCase {
abstract static class BaseNestedTestCase {
@Test
void nestedMethod() {
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,7 @@ void enclosingClassesAreDerivedFromParent() {
}

@Tag("inherited-class-level-tag")
private static abstract class AbstractTestCase {
private abstract static class AbstractTestCase {
}

@Tag("classTag1")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -412,7 +412,7 @@ void reportsWarningsForBlankDisplayNames() throws Exception {
// -------------------------------------------------------------------

@SuppressWarnings("unused")
static abstract class AbstractTestCase {
abstract static class AbstractTestCase {

@Test
void test() {
Expand Down Expand Up @@ -465,7 +465,7 @@ void testTemplate() {

}

static abstract class AbstractSuperClass {
abstract static class AbstractSuperClass {
@Nested
class NestedInAbstractClass {
@Test
Expand Down
Loading