Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confgure IntelliJ to use the same Java formatter as Spotless

I use the Spotless Gradle plugin to ensure consistent formatting of the Java code in my app. The relevant entries in build.gradle are

plugins {
  id "com.diffplug.gradle.spotless" version "3.27.0"
}

spotless {
  java {
    // The available versions of the Eclipse JDT formatter are defined here
    // https://github.com/diffplug/spotless/tree/master/lib-extra/src/main/resources/com/diffplug/spotless/extra/eclipse_jdt_formatter
    eclipse('4.13.0')
    indentWithSpaces()
    removeUnusedImports()
  }
}

Is there some way I can configure IntelliJ to use the same formatting settings?

like image 580
Antonio Dragos Avatar asked Jan 15 '20 15:01

Antonio Dragos


People also ask

How do I use spotless in IntelliJ?

An IntelliJ plugin to allow running the spotless gradle task from within the IDE on the current file selected in the editor. You may find the spotless action via Code > Reformat Code with Spotless.

What is spotless Java?

Keep your code Spotless with Gradle. Spotless is a general-purpose formatting plugin used by 4,000 projects on GitHub (August 2020).

What is Maven spotless apply?

Spotless: Keep your code spotless with Maven. Spotless is a general-purpose formatting plugin. It is completely à la carte, but also includes powerful "batteries-included" if you opt-in. Plugin requires a version of Maven higher or equal to 3.1. 0.

How do I run spotless?

Running Spotless Spotless can be ran using ./gradlew spotlessApply which will apply all formatting options. You can also specify a specific task by just adding the name of formatter. An example is ./gradlew spotlessmiscApply . Spotless can also be used as a CI check.


Video Answer


1 Answers

A not 100% satisfying but working approach:

1. Configure the Spotless tasks

spotless {
    format 'misc', {
        target '*.properties','*.gradle', '*.md', '.gitignore' // etc.
        // code style rules
    }
    java {
        // code style rules
    }
}

2. Add task activation to *Apply tasks

enter image description here

3. Assign convenient keystroke to Build Project

Do this under Settings > Keymap.

Keep in mind that Build Project is using IntelliJ's internal builder. It's incremental (performant), but in case of custom/third-party gradle tasks, the build result might deviate from the $ gradle build result.

In case of a Spring application utilizing DevTools, the build will lead to the changes/updates being served automatically.


With the IDE Hook it should be rather trivial to implement a dedicated Spotless formatter plugin for IntelliJ: https://github.com/diffplug/spotless/blob/master/plugin-gradle/IDE_HOOK.md

So far I wasn't able to find one though.

like image 93
Tob Avatar answered Sep 18 '22 14:09

Tob