Google Java Formatter as external application

Running the current snapshot version of Google-Java-Formatter against all source sets, I frist tried the plugin https://github.com/sherter/google-java-format-gradle-plugin. It does not support the current snapshot API. Here’s my hand-crafted solution. Download with dependencies and execute as a Java program:

configurations {
    format
}

dependencies {
    format "com.google.googlejavaformat:google-java-format:1.2-SNAPSHOT"
}

task downloadFormat(type: Copy) {
    from configurations.format
    into "$buildDir/format"
}

task runFormat(type: JavaExec) {

    def mainJavaFiles = sourceSets.main.allJava.files
    mainJavaFiles.removeIf{ file -> file.name.endsWith('module-info.java') }

    classpath = fileTree(dir: "$buildDir/format", include: '*.jar')

    main 'com.google.googlejavaformat.java.Main'
    args '--replace'
    args mainJavaFiles
    args sourceSets.test.allJava.files
}

runFormat.dependsOn downloadFormat

Is there a more Gradle-way to solve this?

1 Like

Don’t mean to sidetrack you, but it might be easier to accomplish this using the spotless plugin, which formats code using the Eclipse formatter.

plugins {
    id 'com.diffplug.gradle.spotless' version '2.0.0'
}

spotless {
    java {
        eclipseFormatFile 'googlestyle.xml'
    }
}

Google maintains an eclipse formatter for their style.

Hi Ned, Google maintain-ed it until 4 Feb 2014.

The sweet thing about google-java-format is that it does not require any configuration - just run it out of the box.

Good to know. I’ve added an issue to Spotless for handling this.

Turns out someone is using Spotless to do what you want. Here’s a code snippet:

buildscript {
    repositories {
        jcenter()
        maven { url 'https://oss.sonatype.org/content/repositories/snapshots' }
    }
    dependencies {
        classpath 'com.google.googlejavaformat:google-java-format:1.2-SNAPSHOT'
    }
}

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

spotless {
    java {
        customLazyGroovy('google-java-format') {
            com.google.googlejavaformat.java.Formatter formatter = new com.google.googlejavaformat.java.Formatter()
            return { source -> formatter.formatSource(source) }
        }
    }
}

Fresh from spotless 2.1.0 :wink: Looks promising,

:laughing: Yeah. I’ve long told people "use customLazy", but turns out that Groovy and Java 8 functional interfaces only sort of get along, so I finally found out today that we needed a groovy-workaround for Groovy buildscripts.

:spotlessApplied

Thanks.

1 Like

Since spotless 2.2.0 Ned added support for google-java-format directly. See https://github.com/diffplug/spotless#applying-to-java-source-google-java-format

spotless {
    java {
        googleJavaFormat()
    }
}