Improve code formatting on every commit

Arun Yogeshwaran
3 min readApr 27, 2019

--

Many a times you will see nit-picks in your code pointed out by fellow team mates, like remove empty line, correct indentation and other minor fomatting mistakes.

Photo by Lee Campbell on Unsplash

The intention of this post is to give a solution to such formatting issues right at the stage of every commit. Doing this will reduce turn around time in addressing code review comments because of minor formatting issues.

For this purpose, we have a tool/plugin called “Spotless”

Spotless — In its own words - can format <java | kotlin | scala | sql | groovy | javascript | flow | typeScript | css | scss | less | jsx | vue | graphql | json | yaml | markdown | license headers | anything> using <gradle | maven | anything>.

Google is using this tool internally to reduce common issues that are found during code reviews. Though spotless provides support for a variety of languages, in this post, i will walk you through integrating spotless tool in the context of Gradle/Android.

To start integration with Gradle

Add the following dependency to your build.gradle file

classpath(“com.diffplug.spotless:spotless-plugin-gradle:$spotlessVersion”)

Apply the following plugin

apply plugin: ‘com.diffplug.gradle.spotless’

Then add the actual spotless java task to your gradle file

Applying to Java source

spotless {
java {
target project.fileTree(dir: 'src', include: '**/*.java',

indentWithSpaces()
trimTrailingWhitespace()

replaceRegex 'Remove empty lines before end of block', '\\n[\\n]+(\\s*})(?=\\n)', '\n$1'
replaceRegex 'Remove trailing empty comment lines.', '\n\\s*\\*(\n\\s*\\*/\n)', '$1'
}
}

The above gradle script does some auto-formatting to the code like removing empty lines, cutting trailing white spaces when this gradle task is run.

Applying to Kotlin code

It also provides support for kotlin. To add kotlin support, add the following code to the above spotless task

kotlin {
target project.fileTree(dir: ‘src’, include: ‘**/*.kt’)
trimTrailingWhitespace()
ktlint(ktlintVersion)
}

Be sure to add the versions of spotless and ktlint to the gradle file:

ext {
ktlintVersion = "0.30.0"
spotlessVersion = "3.13.0"
}

Applying to Android Java source

Be sure to add target '**/*.java' otherwise spotless will not detect Java code inside Android modules.

spotless {
java {
// ...
target '**/*.java'
// ...
}
}

To people who use your build, it looks like this:

cmd> gradlew build
...
:spotlessJavaCheck FAILED
> The following files had format violations:
src\main\java\com\diffplug\gradle\spotless\FormatExtension.java
@@ -109,7 +109,7 @@
...
-\t\t····if·(targets.length·==·0)·{
+\t\tif·(targets.length·==·0)·{
...
Run 'gradlew spotlessApply' to fix these violations.

cmd> gradlew spotlessApply
:spotlessApply
BUILD SUCCESSFUL

cmd> gradlew build
BUILD SUCCESSFUL

The command above is pretty self explanatory. Running the build after integrating spotless will point out violations in code based on the rules that we specify inside the spotless task.

Then running

gradlew spotlessApply

will fix those violations for us.

Demo:

One such example of auto formatting is shown below

Spotless fixing javadoc

I intentionally formatting mistake(Shown in the left) in the javadoc in a file called Constants.

Running ./gradlew spotlessCheck pointed me to the formatting issue as below:

FAILURE: Build failed with an exception.

* What went wrong:

Execution failed for task ‘:spotlessJava’.

> The following files had format violations:

src/main/java/com/airwatch/contentuiframework/common/Constants.java

@@ -7,7 +7,6 @@

public·class·Constants·{

····/**

·····*·The·id

-·····*

·····*/

····public·static·final·String·ID·=·”id”;

}

Run ‘gradlew spotlessApply’ to fix these violations.

* Try:

Run with — stacktrace option to get the stack trace. Run with — info or — debug option to get more log output. Run with — scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 0s

1 actionable task: 1 executed

Then running ‘gradlew spotlessApply’ fixed it for me as shown in the right side of the above image “Spoltess fixing javadoc”.

To hook this to the build process. Add the below code to your gradle file:


gradle.projectsEvaluated {
if (project.automatedBuild) {
preBuild.dependsOn(spotlessCheck)
} else {
preBuild.dependsOn(spotlessApply)
}
}

Thanks!

--

--