Auto code formatting Java/Kotlin

Posted by

Context:

We are working on a Java project. Our typical day has a lot of code review tasks that need to be done. Before pushing our source code, we usually do the code format by the local tool such as Eclipse, or IntelliJ. But sometimes, the developer forgets to format the code. And the result of PR (pull request) contains the mess from the formatting.

Solution:

We add a required step for every code push which is spotlessCheck, it prevents the code push if the local code is invalid format.

Spotless with Gradle

plugins {
    id("com.diffplug.spotless") version "6.11.0"
}

spotless {
    kotlin {
        ktfmt().googleStyle()
    }
}

Check the version at https://mvnrepository.com/artifact/com.diffplug.spotless/spotless-plugin-gradle

Testing

gradlew build
Execution failed for task ':backend:spotlessKotlinCheck'.
> The following files had format violations:
      src\main\kotlin\io\nettable\config\MongoConfiguration.kt
          @@ -9,21 +9,19 @@

Fixing your code

gradlew spotlessApply

Now local code is ready to push in beautiful format (google style)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.