Search code examples
gradleintellij-ideagoogle-java-format

How can I configure Gradle google-java-format plugin to run goJF in the build step?


We wired https://github.com/sherter/google-java-format-gradle-plugin into our project per the readme.

We also wired in a pre-commit hook to run the plugin before committing, which ensures that all of the code in a changelist is formatted before pushing it, which avoids errors in Jenkins when we run the verGJF task.

But we have to keep remembering to run goJF locally before running ./gradlew build, or the build fails with formatting errors.

We worked around this by adding the https://plugins.jetbrains.com/plugin/8527-google-java-format and https://plugins.jetbrains.com/plugin/7642-save-actions plugins for IntelliJ, enabling the google-java-format plugin, and configuring the save-actions plugin to format on save.

But that's a lot of extra configuration a developer has to remember to go through, plus it means they can't format code the way they want while working on it, and only have it be reformatted at the point of build or commit.

We'd prefer an all-Gradle solution, so that the goJF task is run before the build task (and before the verGJF task, which is already bound to the build task by the google-java-format Gradle plugin).

We couldn't figure out how to do that. Does someone else know?


Solution

  • It sounds like you want to essentially always ensure that the code is properly formatted before the verifyGoogleJavaFormat task is run (and could complain). In that case, I’d simply make the googleJavaFormat task a dependency of the verifyGoogleJavaFormat task. In your build.gradle file, after you have applied the google-java-format plugin, simply add the following:

    verifyGoogleJavaFormat.dependsOn(tasks.googleJavaFormat)
    

    Alternatively, if you really only want to run the code formatter when the build task is run (as opposed to when the verifyGoogleJavaFormat task is run only), you could add this instead:

    build.dependsOn(tasks.googleJavaFormat)
    verifyGoogleJavaFormat.mustRunAfter(tasks.googleJavaFormat)