If you are working on a codebase with a large team, setting up automated code formatting has many advantages.
- Enforces uniform code style, enhancing readability and collaboration between members instead of fighting over code styles
- Automates formatting tasks, reducing manual effort and minimizing errors.
- Facilitates cleaner code diffs, easing collaboration and code reviews and focusing on lines that matter the most
In this blog, I will talk about how we set up code formatting with Spotless
Compatibility with Build Tools
Spotless can work with maven, gradle, and sbt as build tools. It can also work with other build tools, more details here. I be using Gradle as a build tool and Java Code to set up auto-formatting.
Step 1: Adding to the Build
Add the following to your build.gradle file. If you are using other build tools, use this page to add the appropriate dependency
Enable Plugin Section
Put the following code section as part of your plugins in the build
plugins {
You }
Configure Code Formatting Style
Put the following section as part of your build
spotless {
java {
target fileTree('.') {
include '**/*.java'
exclude '**/build/**', '**/build-*/**'
}
palantirJavaFormat() // One of the styles which I prefer for Java Code, you can choose other styles like Google Style
removeUnusedImports()
trimTrailingWhitespace()
endWithNewline()
}
In the above section, you could choose your own include, and exclude patterns for the files to be formatted in the codebase.
Step 2: Verifying Spotless Formatting Checks
In order to verify if the plugin has been enabled, Make any formatting changes in your codebase and run ./gradlew :spotlessCheck It will report the missing formatting in the codebase and will fail the build. This command comes in handy when you want to integrate your Continuous integration with these checks enabled so that it will fail the build if someone checks in the unformatted code.

Step 3: Fixing Formatting with Spotless
To fix formatting issues, run ./gradlew :spotlessApply and the formatting issues should be fixed. In the example below, the additional lines that were added in the first images are gone and the build is green.

Easy. Wasn’t It!
What Next?
Ideally the spotlessCheck should be part of the first thing in your build as part of the CI pipeline which fails automatically when unformatted code is checked in.