openrewrite / rewrite

Automated mass refactoring of source code.
https://docs.openrewrite.org
Apache License 2.0
2.23k stars 334 forks source link

EmptyNewlineAtEndOfFile in groovy files ending with constructor and an empty line damages compilation by removing closing bracket #4216

Open iMckify opened 5 months ago

iMckify commented 5 months ago

I am using

How are you running OpenRewrite?

I am using the Gradle plugin, and my project is a single module project.

plugins {
    id 'groovy'
    id 'org.openrewrite.rewrite' version '6.13.0'
}

group = 'x'
version = '0.0.1-SNAPSHOT'

java {
    sourceCompatibility = JavaVersion.VERSION_21
}

sourceSets {
    main {
        java { srcDirs = [] }
        groovy { srcDirs = ['src/main/java', 'src/main/groovy'] }
    }
}

project.layout.buildDirectory = outDir

rewrite {
    activeRecipe("org.openrewrite.staticanalysis.CodeCleanup")
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.apache.groovy:groovy-all:4.0.21'
    rewrite("org.openrewrite.recipe:rewrite-static-analysis:1.8.1")
}

What is the smallest, simplest way to reproduce the problem?

Create POGO class with final fields and constructor only, key thing is that last two closing brackets should be separated by empty line like

    }

}

full file here:

class TryClass {
    private String field1
    private String field2

    TryClass() {

    }

}

What did you expect to see?

Last closing bracket '}' should exist

class TryClass {
    private String field1
    private String field2

    TryClass() {

    }

}

What did you see instead?

Last '}' missing

class TryClass {
    private String field1
    private String field2

    TryClass() {

    }

What is the full stack trace of any errors you encountered?

Changes have been made to x/src/main/groovy/y.z/TryClass.groovy by:
    org.openrewrite.staticanalysis.CodeCleanup
        org.openrewrite.java.format.EmptyNewlineAtEndOfFile
timtebeek commented 5 months ago

Thanks for reporting in such detail! From the examples you've given it should be possible to create a unit test in EmptyNewlineAtEndOfFileTest, using Assertions.groovy, similar to this one. https://github.com/openrewrite/rewrite/blob/133e56af0fdd3e1c96d4e98b5ae8e8503c6c2507/rewrite-java-test/src/test/java/org/openrewrite/java/format/EmptyNewlineAtEndOfFileTest.java#L67-L77

Then from there we can hopefully add a fix to the recipe implementation as seen here https://github.com/openrewrite/rewrite/blob/133e56af0fdd3e1c96d4e98b5ae8e8503c6c2507/rewrite-java/src/main/java/org/openrewrite/java/format/EmptyNewlineAtEndOfFile.java#L62-L81

Or if that fails, add an exception to the recipe to not run on Groovy files (not ideal).