all: add gradle format checker

This PR adds an automatic gradle format checker and reformats all the *.gradle files. After this, new changes to *.gradle files will fail to build if not in good format, just like checkStyle failure.
diff --git a/build.gradle b/build.gradle
index 39491a8..4c25986 100644
--- a/build.gradle
+++ b/build.gradle
@@ -1,18 +1,17 @@
 buildscript {
-  repositories {
-    mavenLocal()
-    maven {
-      url "https://plugins.gradle.org/m2/"
+    repositories {
+        mavenLocal()
+        maven { url "https://plugins.gradle.org/m2/" }
     }
-  }
-  dependencies {
-    classpath 'com.google.gradle:osdetector-gradle-plugin:1.4.0'
-    classpath 'ru.vyarus:gradle-animalsniffer-plugin:1.4.0'
-    classpath 'net.ltgt.gradle:gradle-errorprone-plugin:0.0.13'
-    classpath 'net.ltgt.gradle:gradle-apt-plugin:0.13'
-    classpath "me.champeau.gradle:jmh-gradle-plugin:0.4.5"
-    classpath 'me.champeau.gradle:japicmp-gradle-plugin:0.2.5'
-  }
+    dependencies {
+        classpath "com.diffplug.spotless:spotless-plugin-gradle:3.13.0"
+        classpath 'com.google.gradle:osdetector-gradle-plugin:1.4.0'
+        classpath 'ru.vyarus:gradle-animalsniffer-plugin:1.4.0'
+        classpath 'net.ltgt.gradle:gradle-errorprone-plugin:0.0.13'
+        classpath 'net.ltgt.gradle:gradle-apt-plugin:0.13'
+        classpath "me.champeau.gradle:jmh-gradle-plugin:0.4.5"
+        classpath 'me.champeau.gradle:japicmp-gradle-plugin:0.2.5'
+    }
 }
 
 subprojects {
@@ -28,24 +27,24 @@
     // The plugin only has an effect if a signature is specified
     apply plugin: "ru.vyarus.animalsniffer"
     if (!rootProject.hasProperty('errorProne') || rootProject.errorProne.toBoolean()) {
-      apply plugin: "net.ltgt.errorprone"
-      apply plugin: "net.ltgt.apt"
+        apply plugin: "net.ltgt.errorprone"
+        apply plugin: "net.ltgt.apt"
 
-      dependencies {
-        // The ErrorProne plugin defaults to the latest, which would break our
-        // build if error prone releases a new version with a new check
-        errorprone 'com.google.errorprone:error_prone_core:2.2.0'
-        apt 'com.google.guava:guava-beta-checker:1.0'
-      }
-    } else {
-      // Remove per-project error-prone checker config
-      allprojects {
-        afterEvaluate { project ->
-          project.tasks.withType(JavaCompile) {
-            options.compilerArgs.removeAll { it.startsWith("-Xep") }
-          }
+        dependencies {
+            // The ErrorProne plugin defaults to the latest, which would break our
+            // build if error prone releases a new version with a new check
+            errorprone 'com.google.errorprone:error_prone_core:2.2.0'
+            apt 'com.google.guava:guava-beta-checker:1.0'
         }
-      }
+    } else {
+        // Remove per-project error-prone checker config
+        allprojects {
+            afterEvaluate { project ->
+                project.tasks.withType(JavaCompile) {
+                    options.compilerArgs.removeAll { it.startsWith("-Xep") }
+                }
+            }
+        }
     }
     // TODO(zpencer): remove when intellij 2017.2 is released
     // https://github.com/gradle/gradle/issues/2315
@@ -58,15 +57,21 @@
     targetCompatibility = 1.6
 
     repositories {
-        maven {
-            // The google mirror is less flaky than mavenCentral()
-            url "https://maven-central.storage-download.googleapis.com/repos/central/data/"
-        }
+        maven { // The google mirror is less flaky than mavenCentral()
+            url "https://maven-central.storage-download.googleapis.com/repos/central/data/" }
         mavenLocal()
     }
 
-    [compileJava, compileTestJava, compileJmhJava].each() {
-        it.options.compilerArgs += ["-Xlint:all", "-Xlint:-options", "-Xlint:-path"]
+    [
+        compileJava,
+        compileTestJava,
+        compileJmhJava
+    ].each() {
+        it.options.compilerArgs += [
+            "-Xlint:all",
+            "-Xlint:-options",
+            "-Xlint:-path"
+        ]
         it.options.encoding = "UTF-8"
         if (rootProject.hasProperty('failOnWarnings') && rootProject.failOnWarnings.toBoolean()) {
             it.options.compilerArgs += ["-Werror"]
@@ -74,18 +79,21 @@
     }
 
     compileTestJava {
-      // serialVersionUID is basically guaranteed to be useless in our tests
-      // LinkedList doesn't hurt much in tests and has lots of usages
-      options.compilerArgs += ["-Xlint:-serial", "-Xep:JdkObsolete:OFF"]
+        // serialVersionUID is basically guaranteed to be useless in our tests
+        // LinkedList doesn't hurt much in tests and has lots of usages
+        options.compilerArgs += [
+            "-Xlint:-serial",
+            "-Xep:JdkObsolete:OFF"
+        ]
     }
 
     jar.manifest {
         attributes('Implementation-Title': name,
-                'Implementation-Version': version,
-                'Built-By': System.getProperty('user.name'),
-                'Built-JDK': System.getProperty('java.version'),
-                'Source-Compatibility': sourceCompatibility,
-                'Target-Compatibility': targetCompatibility)
+        'Implementation-Version': version,
+        'Built-By': System.getProperty('user.name'),
+        'Built-JDK': System.getProperty('java.version'),
+        'Source-Compatibility': sourceCompatibility,
+        'Target-Compatibility': targetCompatibility)
     }
 
     javadoc.options {
@@ -107,79 +115,75 @@
         opencensusVersion = '0.12.3'
 
         configureProtoCompilation = {
-          String generatedSourcePath = "${projectDir}/src/generated"
-          if (rootProject.childProjects.containsKey('grpc-compiler')) {
-            // Only when the codegen is built along with the project, will we be able to recompile
-            // the proto files.
-            project.apply plugin: 'com.google.protobuf'
-            project.protobuf {
-              protoc {
-                if (project.hasProperty('protoc')) {
-                  path = project.protoc
-                } else {
-                  artifact = "com.google.protobuf:protoc:${protocVersion}"
-                }
-              }
-              plugins {
-                grpc {
-                  path = javaPluginPath
-                }
-              }
-              generateProtoTasks {
-                all().each { task ->
-                  task.dependsOn ':grpc-compiler:java_pluginExecutable'
-                  // Delete the generated sources first, so that we can be alerted if they are not re-compiled.
-                  task.dependsOn 'deleteGeneratedSource' + task.sourceSet.name
-                  // Recompile protos when the codegen has been changed
-                  task.inputs.file javaPluginPath
-                  // Recompile protos when build.gradle has been changed, because
-                  // it's possible the version of protoc has been changed.
-                  task.inputs.file "${rootProject.projectDir}/build.gradle"
-                  task.plugins {
-                    grpc {
-                      option 'noversion'
+            String generatedSourcePath = "${projectDir}/src/generated"
+            if (rootProject.childProjects.containsKey('grpc-compiler')) {
+                // Only when the codegen is built along with the project, will we be able to recompile
+                // the proto files.
+                project.apply plugin: 'com.google.protobuf'
+                project.protobuf {
+                    protoc {
+                        if (project.hasProperty('protoc')) {
+                            path = project.protoc
+                        } else {
+                            artifact = "com.google.protobuf:protoc:${protocVersion}"
+                        }
                     }
-                  }
+                    plugins { grpc { path = javaPluginPath } }
+                    generateProtoTasks {
+                        all().each { task ->
+                            task.dependsOn ':grpc-compiler:java_pluginExecutable'
+                            // Delete the generated sources first, so that we can be alerted if they are not re-compiled.
+                            task.dependsOn 'deleteGeneratedSource' + task.sourceSet.name
+                            // Recompile protos when the codegen has been changed
+                            task.inputs.file javaPluginPath
+                            // Recompile protos when build.gradle has been changed, because
+                            // it's possible the version of protoc has been changed.
+                            task.inputs.file "${rootProject.projectDir}/build.gradle"
+                            task.plugins { grpc { option 'noversion' } }
+                        }
+                    }
+                    generatedFilesBaseDir = generatedSourcePath
                 }
-              }
-              generatedFilesBaseDir = generatedSourcePath
+
+                sourceSets.each { sourceSet ->
+                    task "deleteGeneratedSource${sourceSet.name}" {
+                        doLast {
+                            project.delete project.fileTree(dir: generatedSourcePath + '/' + sourceSet.name)
+                        }
+                    }
+                }
+            } else {
+                // Otherwise, we just use the checked-in generated code.
+                project.sourceSets {
+                    main {
+                        java {
+                            srcDir "${generatedSourcePath}/main/java"
+                            srcDir "${generatedSourcePath}/main/javanano"
+                            srcDir "${generatedSourcePath}/main/grpc"
+                        }
+                    }
+                    test {
+                        java {
+                            srcDir "${generatedSourcePath}/test/java"
+                            srcDir "${generatedSourcePath}/test/javanano"
+                            srcDir "${generatedSourcePath}/test/grpc"
+                        }
+                    }
+                }
             }
 
-            sourceSets.each { sourceSet ->
-              task "deleteGeneratedSource${sourceSet.name}" {
-                doLast {
-                  project.delete project.fileTree(dir: generatedSourcePath + '/' + sourceSet.name)
-                }
-              }
+            [
+                compileJava,
+                compileTestJava,
+                compileJmhJava
+            ].each() {
+                // Protobuf-generated code produces some warnings.
+                // https://github.com/google/protobuf/issues/2718
+                it.options.compilerArgs += [
+                    "-Xlint:-cast",
+                    "-XepExcludedPaths:.*/src/generated/[^/]+/java/.*",
+                ]
             }
-          } else {
-            // Otherwise, we just use the checked-in generated code.
-            project.sourceSets {
-              main {
-                java {
-                  srcDir "${generatedSourcePath}/main/java"
-                  srcDir "${generatedSourcePath}/main/javanano"
-                  srcDir "${generatedSourcePath}/main/grpc"
-                }
-              }
-              test {
-                java {
-                  srcDir "${generatedSourcePath}/test/java"
-                  srcDir "${generatedSourcePath}/test/javanano"
-                  srcDir "${generatedSourcePath}/test/grpc"
-                }
-              }
-            }
-          }
-
-          [compileJava, compileTestJava, compileJmhJava].each() {
-            // Protobuf-generated code produces some warnings.
-            // https://github.com/google/protobuf/issues/2718
-            it.options.compilerArgs += [
-                "-Xlint:-cast",
-                "-XepExcludedPaths:.*/src/generated/[^/]+/java/.*",
-            ]
-          }
         }
 
         def epoll_suffix = "";
@@ -188,50 +192,50 @@
             epoll_suffix = ":" + osdetector.classifier
         }
         libraries = [
-                errorprone: "com.google.errorprone:error_prone_annotations:2.1.2",
-                gson: "com.google.code.gson:gson:2.7",
-                guava: "com.google.guava:guava:${guavaVersion}",
-                hpack: 'com.twitter:hpack:0.10.1',
-                javax_annotation: 'javax.annotation:javax.annotation-api:1.2',
-                jsr305: 'com.google.code.findbugs:jsr305:3.0.0',
-                oauth_client: 'com.google.auth:google-auth-library-oauth2-http:0.9.0',
-                google_api_protos: 'com.google.api.grpc:proto-google-common-protos:1.0.0',
-                google_auth_credentials: 'com.google.auth:google-auth-library-credentials:0.9.0',
-                okhttp: 'com.squareup.okhttp:okhttp:2.5.0',
-                okio: 'com.squareup.okio:okio:1.13.0',
-                opencensus_api: "io.opencensus:opencensus-api:${opencensusVersion}",
-                opencensus_contrib_grpc_metrics: "io.opencensus:opencensus-contrib-grpc-metrics:${opencensusVersion}",
-                opencensus_impl: "io.opencensus:opencensus-impl:${opencensusVersion}",
-                opencensus_impl_lite: "io.opencensus:opencensus-impl-lite:${opencensusVersion}",
-                instrumentation_api: 'com.google.instrumentation:instrumentation-api:0.4.3',
-                protobuf: "com.google.protobuf:protobuf-java:${protobufVersion}",
-                protobuf_lite: "com.google.protobuf:protobuf-lite:3.0.1",
-                protoc_lite: "com.google.protobuf:protoc-gen-javalite:3.0.0",
-                protobuf_nano: "com.google.protobuf.nano:protobuf-javanano:${protobufNanoVersion}",
-                protobuf_plugin: 'com.google.protobuf:protobuf-gradle-plugin:0.8.5',
-                protobuf_util: "com.google.protobuf:protobuf-java-util:${protobufVersion}",
-                lang: "org.apache.commons:commons-lang3:3.5",
+            errorprone: "com.google.errorprone:error_prone_annotations:2.1.2",
+            gson: "com.google.code.gson:gson:2.7",
+            guava: "com.google.guava:guava:${guavaVersion}",
+            hpack: 'com.twitter:hpack:0.10.1',
+            javax_annotation: 'javax.annotation:javax.annotation-api:1.2',
+            jsr305: 'com.google.code.findbugs:jsr305:3.0.0',
+            oauth_client: 'com.google.auth:google-auth-library-oauth2-http:0.9.0',
+            google_api_protos: 'com.google.api.grpc:proto-google-common-protos:1.0.0',
+            google_auth_credentials: 'com.google.auth:google-auth-library-credentials:0.9.0',
+            okhttp: 'com.squareup.okhttp:okhttp:2.5.0',
+            okio: 'com.squareup.okio:okio:1.13.0',
+            opencensus_api: "io.opencensus:opencensus-api:${opencensusVersion}",
+            opencensus_contrib_grpc_metrics: "io.opencensus:opencensus-contrib-grpc-metrics:${opencensusVersion}",
+            opencensus_impl: "io.opencensus:opencensus-impl:${opencensusVersion}",
+            opencensus_impl_lite: "io.opencensus:opencensus-impl-lite:${opencensusVersion}",
+            instrumentation_api: 'com.google.instrumentation:instrumentation-api:0.4.3',
+            protobuf: "com.google.protobuf:protobuf-java:${protobufVersion}",
+            protobuf_lite: "com.google.protobuf:protobuf-lite:3.0.1",
+            protoc_lite: "com.google.protobuf:protoc-gen-javalite:3.0.0",
+            protobuf_nano: "com.google.protobuf.nano:protobuf-javanano:${protobufNanoVersion}",
+            protobuf_plugin: 'com.google.protobuf:protobuf-gradle-plugin:0.8.5',
+            protobuf_util: "com.google.protobuf:protobuf-java-util:${protobufVersion}",
+            lang: "org.apache.commons:commons-lang3:3.5",
 
-                netty: "io.netty:netty-codec-http2:[${nettyVersion}]",
-                netty_epoll: "io.netty:netty-transport-native-epoll:${nettyVersion}" + epoll_suffix,
-                netty_proxy_handler: "io.netty:netty-handler-proxy:${nettyVersion}",
-                netty_tcnative: 'io.netty:netty-tcnative-boringssl-static:2.0.8.Final',
+            netty: "io.netty:netty-codec-http2:[${nettyVersion}]",
+            netty_epoll: "io.netty:netty-transport-native-epoll:${nettyVersion}" + epoll_suffix,
+            netty_proxy_handler: "io.netty:netty-handler-proxy:${nettyVersion}",
+            netty_tcnative: 'io.netty:netty-tcnative-boringssl-static:2.0.8.Final',
 
-                conscrypt: 'org.conscrypt:conscrypt-openjdk-uber:1.0.1',
-                re2j: 'com.google.re2j:re2j:1.2',
+            conscrypt: 'org.conscrypt:conscrypt-openjdk-uber:1.0.1',
+            re2j: 'com.google.re2j:re2j:1.2',
 
-                // Test dependencies.
-                junit: 'junit:junit:4.12',
-                mockito: 'org.mockito:mockito-core:1.9.5',
-                truth: 'com.google.truth:truth:0.36',
-                guava_testlib: 'com.google.guava:guava-testlib:20.0',
+            // Test dependencies.
+            junit: 'junit:junit:4.12',
+            mockito: 'org.mockito:mockito-core:1.9.5',
+            truth: 'com.google.truth:truth:0.36',
+            guava_testlib: 'com.google.guava:guava-testlib:20.0',
 
-                // Benchmark dependencies
-                hdrhistogram: 'org.hdrhistogram:HdrHistogram:2.1.10',
-                math: 'org.apache.commons:commons-math3:3.6',
+            // Benchmark dependencies
+            hdrhistogram: 'org.hdrhistogram:HdrHistogram:2.1.10',
+            math: 'org.apache.commons:commons-math3:3.6',
 
-                // Jetty ALPN dependencies
-                jetty_alpn_agent: 'org.mortbay.jetty.alpn:jetty-alpn-agent:2.0.7'
+            // Jetty ALPN dependencies
+            jetty_alpn_agent: 'org.mortbay.jetty.alpn:jetty-alpn-agent:2.0.7'
         ]
     }
 
@@ -242,7 +246,10 @@
         compile {
             // Detect Maven Enforcer's dependencyConvergence failures. We only
             // care for artifacts used as libraries by others.
-            if (!(project.name in ['grpc-benchmarks', 'grpc-interop-testing'])) {
+            if (!(project.name in [
+                'grpc-benchmarks',
+                'grpc-interop-testing'
+            ])) {
                 resolutionStrategy.failOnVersionConflict()
             }
         }
@@ -250,14 +257,14 @@
 
     dependencies {
         testCompile libraries.junit,
-                    libraries.mockito,
-                    libraries.truth
+                libraries.mockito,
+                libraries.truth
 
         // Configuration for modules that use Jetty ALPN agent
         alpnagent libraries.jetty_alpn_agent
 
         jmh 'org.openjdk.jmh:jmh-core:1.19',
-            'org.openjdk.jmh:jmh-generator-bytecode:1.19'
+                'org.openjdk.jmh:jmh-generator-bytecode:1.19'
     }
 
     signing {
@@ -267,11 +274,11 @@
 
     // Disable JavaDoc doclint on Java 8. It's annoying.
     if (JavaVersion.current().isJava8Compatible()) {
-      allprojects {
-        tasks.withType(Javadoc) {
-          options.addStringOption('Xdoclint:none', '-quiet')
+        allprojects {
+            tasks.withType(Javadoc) {
+                options.addStringOption('Xdoclint:none', '-quiet')
+            }
         }
-      }
     }
 
     checkstyle {
@@ -303,7 +310,9 @@
         // depends on core; core's testCompile depends on testing)
         includeTests = false
         if (project.hasProperty('jmhIncludeSingleClass')) {
-          include = [project.property('jmhIncludeSingleClass')]
+            include = [
+                project.property('jmhIncludeSingleClass')
+            ]
         }
     }
 
@@ -317,36 +326,34 @@
         from sourceSets.main.allSource
     }
 
-    artifacts {
-        archives javadocJar, sourcesJar
-    }
+    artifacts { archives javadocJar, sourcesJar }
 
     uploadArchives.repositories.mavenDeployer {
         beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) }
         if (rootProject.hasProperty('repositoryDir')) {
-          repository(url: new File(rootProject.repositoryDir).toURI())
+            repository(url: new File(rootProject.repositoryDir).toURI())
         } else {
-          String stagingUrl
-          if (rootProject.hasProperty('repositoryId')) {
-            stagingUrl = 'https://oss.sonatype.org/service/local/staging/deployByRepositoryId/' +
-               rootProject.repositoryId
-          } else {
-            stagingUrl = 'https://oss.sonatype.org/service/local/staging/deploy/maven2/'
-          }
-          def configureAuth = {
-            if (rootProject.hasProperty('ossrhUsername') && rootProject.hasProperty('ossrhPassword')) {
-              authentication(userName: rootProject.ossrhUsername, password: rootProject.ossrhPassword)
+            String stagingUrl
+            if (rootProject.hasProperty('repositoryId')) {
+                stagingUrl = 'https://oss.sonatype.org/service/local/staging/deployByRepositoryId/' +
+                        rootProject.repositoryId
+            } else {
+                stagingUrl = 'https://oss.sonatype.org/service/local/staging/deploy/maven2/'
             }
-          }
-          repository(url: stagingUrl, configureAuth)
-          snapshotRepository(url: 'https://oss.sonatype.org/content/repositories/snapshots/', configureAuth)
+            def configureAuth = {
+                if (rootProject.hasProperty('ossrhUsername') && rootProject.hasProperty('ossrhPassword')) {
+                    authentication(userName: rootProject.ossrhUsername, password: rootProject.ossrhPassword)
+                }
+            }
+            repository(url: stagingUrl, configureAuth)
+            snapshotRepository(url: 'https://oss.sonatype.org/content/repositories/snapshots/', configureAuth)
         }
     }
     uploadArchives.onlyIf { !name.contains("grpc-gae-interop-testing") }
 
     [
-      install.repositories.mavenInstaller,
-      uploadArchives.repositories.mavenDeployer,
+        install.repositories.mavenInstaller,
+        uploadArchives.repositories.mavenDeployer,
     ]*.pom*.whenConfigured { pom ->
         pom.project {
             name "$project.group:$project.name"
@@ -379,12 +386,17 @@
             }
         }
         if (!(project.name in
-            ["grpc-stub", "grpc-protobuf", "grpc-protobuf-lite", "grpc-protobuf-nano"])) {
-          def core = pom.dependencies.find {dep -> dep.artifactId == 'grpc-core'}
-          if (core != null) {
-            // Depend on specific version of grpc-core because internal package is unstable
-            core.version = "[" + core.version + "]"
-          }
+        [
+            "grpc-stub",
+            "grpc-protobuf",
+            "grpc-protobuf-lite",
+            "grpc-protobuf-nano"
+        ])) {
+            def core = pom.dependencies.find {dep -> dep.artifactId == 'grpc-core'}
+            if (core != null) {
+                // Depend on specific version of grpc-core because internal package is unstable
+                core.version = "[" + core.version + "]"
+            }
         }
     }
     // At a test failure, log the stack trace to the console so that we don't
@@ -403,19 +415,19 @@
 // Run with: ./gradlew japicmp --continue
 def baselineGrpcVersion = '1.6.1'
 def publicApiSubprojects = [
-        // TODO: uncomment after grpc-alts artifact is published.
-        // ':grpc-alts',
-        ':grpc-auth',
-        ':grpc-context',
-        ':grpc-core',
-        ':grpc-grpclb',
-        ':grpc-netty',
-        ':grpc-okhttp',
-        ':grpc-protobuf',
-        ':grpc-protobuf-lite',
-        ':grpc-protobuf-nano',
-        ':grpc-stub',
-        ':grpc-testing',
+    // TODO: uncomment after grpc-alts artifact is published.
+    // ':grpc-alts',
+    ':grpc-auth',
+    ':grpc-context',
+    ':grpc-core',
+    ':grpc-grpclb',
+    ':grpc-netty',
+    ':grpc-okhttp',
+    ':grpc-protobuf',
+    ':grpc-protobuf-lite',
+    ':grpc-protobuf-nano',
+    ':grpc-stub',
+    ':grpc-testing',
 ]
 
 publicApiSubprojects.each { name ->
@@ -435,7 +447,7 @@
             String depJar = "${project.name}-${baselineGrpcVersion}.jar"
             Configuration configuration = configurations.detachedConfiguration(
                     dependencies.create(depModule)
-            )
+                    )
             baselineArtifact = files(configuration.files).filter {
                 it.name.equals(depJar)
             }.singleFile
@@ -468,3 +480,15 @@
         }
     }
 }
+
+// format checkers
+apply plugin: "com.diffplug.gradle.spotless"
+apply plugin: 'groovy'
+spotless {
+    groovyGradle {
+        target '**/*.gradle'
+        greclipse()
+        indentWithSpaces()
+        paddedCell()
+    }
+}