Running Spotless Automagically with Gradle

Featured image for sharing metadata for article

If you're using Gradle and are using Spotless to manage your code style (which I'd strongly recommend) you may find it annoying to manually run Spotless each time you make changes to your codebase.

I've got mine set up so with my Gradle projects, Spotless is enforced after the compilation phase (JavaCompile). The alternative, more developer-friendly method would be to have spotlessApply always running before JavaCompile, which means that you'd always have well-formatted code.

However, this unfortunately means that you're relying on developers to be good. If, for whatever reason, the developer in question didn't run their code locally before pushing their code, you may not notice. The pipeline would run, and would automagically apply Spotless therefore the code would be well-formed when it then runs spotlessCheck. But in the actual Merge Request, you'd see inconsistent/bad code style. This isn't great, and can make things a bit painful.

We could, instead, have a slightly different Gradle configuration between local and our pipeline, but that seems like it'd risk things being inconsistent, and eventually drifting.

However, this can be a bit painful, because it means you're going through a regular loop of making sure you run i.e. ./gradlew clean spotlessApply test.

Today, Jack Gough mentioned that you are able to set global Gradle configuration, which allows you to always apply Spotless, if it's configured.

We can create a file i.e. ~/.gradle/init.d/spotless.gradle:

allprojects {
  afterEvaluate {
    def spotless = tasks.findByName('spotlessApply')
    if (spotless) {
      tasks.withType(JavaCompile) {

This will apply your Spotless configuration, after the code has successfully compiled, but will run before any other configured tasks like spotlessCheck, if that's configured in the project.

And of course we only want to apply this if Spotless is found in the project, otherwise we risk breaking non-Spotless project builds.

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

#blogumentation #gradle #spotless #java.

This post was filed under articles.

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.