sormuras
(Christian Stein)
September 28, 2016, 2:49pm
1
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
Ned_Twigg
(Ned Twigg)
October 6, 2016, 5:28pm
2
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 .
sormuras
(Christian Stein)
October 7, 2016, 10:13am
3
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.
Ned_Twigg
(Ned Twigg)
October 7, 2016, 3:48pm
4
Good to know. I’ve added an issue to Spotless for handling this.
Ned_Twigg
(Ned Twigg)
October 7, 2016, 5:41pm
5
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) }
}
}
}
sormuras
(Christian Stein)
October 7, 2016, 6:58pm
6
Ned_Twigg:
customLazyGroovy
Fresh from spotless 2.1.0 Looks promising,
Ned_Twigg
(Ned Twigg)
October 7, 2016, 7:11pm
7
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.
sormuras
(Christian Stein)
October 7, 2016, 10:51pm
9
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()
}
}