Implement google-java-format check and vote on code-style label

Change-Id: Ia9f2ab0f36c70a644f27ba3305be566a445f0773
diff --git a/jenkins/gerrit-verifier-change.groovy b/jenkins/gerrit-verifier-change.groovy
index 68567f1..faff1ed 100644
--- a/jenkins/gerrit-verifier-change.groovy
+++ b/jenkins/gerrit-verifier-change.groovy
@@ -76,7 +76,7 @@
   return 0
 }
 
-def gerritReview(change, sha1, verified) {
+def gerritLabelVerify(change, sha1, verified, builds) {
   if(verified == 0) {
     return;
   }
@@ -84,7 +84,7 @@
   def changeNum = change._number
   def resTicks = [ 'ABORTED':'\u26aa', 'SUCCESS':'\u2705', 'FAILURE':'\u274c' ]
 
-  def msgList = Globals.buildsList.collect { type,build ->
+  def msgList = builds.collect { type,build ->
     [ 'type': type, 'res': build.getResult().toString(), 'url': build.getBuildUrl() + "console" ]
   } sort { a,b -> a['res'].compareTo(b['res']) }
 
@@ -92,13 +92,6 @@
     "${resTicks[it.res]} ${it.type} : ${it.res}\n    (${it.url})"
   } .join('\n')
 
-  def addReviewerExit = gerritPost("a/changes/" + changeNum + "/reviewers", '{ "reviewer" : "' +
-                                   Globals.gerritReviewer + "\" , ${Globals.addReviewerTag} }")
-  if(addReviewerExit != 0) {
-    println "**** ERROR: cannot add myself as reviewer of change " + changeNum + " *****"
-    return addReviewerExit
-  }
-
   def addVerifiedExit = gerritLabel(changeNum, sha1, 'Verified', verified, msgBody)
   if(addVerifiedExit == 0) {
     println "----------------------------------------------------------------------------"
@@ -106,16 +99,39 @@
     println "----------------------------------------------------------------------------"
   }
 
-  if(Globals.codeStyleBranches.contains(change.branch)) {
-    def addCodeStyleExit = gerritLabel(changeNum, sha1, 'Code-Style', verified)
-    if(addVerifiedExit == 0) {
-      println "----------------------------------------------------------------------------"
-      println "Gerrit Review: Code-Style=" + verified + " to change " + changeNum + "/" + sha1
-      println "----------------------------------------------------------------------------"
+  return addVerifiedExit
+}
+
+def findCodestyleFilesInLog() {
+  def codestyleFiles = []
+  def needsFormatting = false
+  def codestyleLogReader = Globals.buildsList["codestyle"].getLogReader()
+  codestyleLogReader.eachLine {
+    needsFormatting = needsFormatting || (it ==~ /.*Need Formatting.*/)
+    if(needsFormatting && it ==~ /\[.*\]/) {
+      codestyleFiles += it.substring(1,it.length()-1)
     }
   }
 
-  return addVerifiedExit
+  return codestyleFiles
+}
+
+def gerritLabelCodestyle(change, sha1, cs, files) {
+  if(cs == 0) {
+    return
+  }
+
+  def changeNum = change._number
+  def msgBody = "The following files need formatting:\n" + files.join('\n')
+
+  def addCodeStyleExit = gerritLabel(changeNum, sha1, 'Code-Style', cs, msgBody)
+  if(addCodeStyleExit == 0) {
+    println "----------------------------------------------------------------------------"
+    println "Gerrit Review: Code-Style=" + cs + " to change " + changeNum + "/" + sha1
+    println "----------------------------------------------------------------------------"
+  }
+
+  return addCodeStyleExit
 }
 
 def gerritLabel(changeNum, sha1, label, score, msgBody = "") {
@@ -174,8 +190,20 @@
   filesJson.keySet().findAll { it != "/COMMIT_MSG" }
 }
 
-def buildsForMode(refspec,sha1,changeUrl,mode,tools,targetBranch,retryTimes) {
+def buildsForMode(refspec,sha1,changeUrl,mode,tools,targetBranch,retryTimes,codestyle) {
     def builds = []
+    if(codestyle) {
+      builds += {
+        Globals.buildsList.put("codestyle", build("Gerrit-codestyle",
+                               REFSPEC: refspec, BRANCH: sha1, CHANGE_URL: changeUrl, MODE: mode,
+                               TARGET_BRANCH: targetBranch))
+                     println "Builds status:"
+                     Globals.buildsList.each {
+                       n, v -> println "  $n : ${v.getResult()}\n    (${v.getBuildUrl() + "console"})"
+                     }
+      }
+    }
+
     for (tool in tools) {
       def buildName = "Gerrit-verifier-$tool"
       def key = "$tool/$mode"
@@ -259,11 +287,18 @@
 
   def builds = []
   println "Running validation jobs using $tools builds for $modes ..."
-  modes.collect { buildsForMode(refspec,sha1,changeUrl,it,tools,branch,1) }.each { builds += it }
+  modes.collect {
+    buildsForMode(refspec,sha1,changeUrl,it,tools,branch,1,Globals.codeStyleBranches.contains(branch))
+  }.each { builds += it }
 
   def buildsWithResults = parallelBuilds(builds)
+  def codestyleResult = buildsWithResults.find{ it[0] == "codestyle" }
+  if(codestyleResult) {
+    def resCodeStyle = getVerified(1, codestyleResult[1])
+    gerritLabelCodestyle(change, sha1, resCodeStyle, findCodestyleFilesInLog())
+  }
 
-  flaky = flakyBuilds(buildsWithResults)
+  flaky = flakyBuilds(buildsWithResults.findAll { it[0] != "codestyle" })
   if(flaky.size > 0) {
     println "** FLAKY Builds detected: ${flaky}"
 
@@ -279,11 +314,13 @@
     buildsWithResults = parallelBuilds(retryBuilds)
   }
 
-  def res = buildsWithResults.inject(1) { acc, buildResult -> getVerified(acc, buildResult[1]) }
+  def resVerify = buildsWithResults.findAll{ it != codestyleResult }.inject(1) { acc, buildResult -> getVerified(acc, buildResult[1]) }
 
-  gerritReview(change, sha1, res)
+  def resAll = getVerified(resVerify, codestyleResult[1])
 
-  switch(res) {
+  gerritLabelVerify(change, sha1, resVerify, Globals.buildsList.findAll { key,build -> key != "codestyle" })
+
+  switch(resAll) {
     case 0: build.state.result = ABORTED
             break
     case 1: build.state.result = SUCCESS
diff --git a/jenkins/gerrit-verifier.yaml b/jenkins/gerrit-verifier.yaml
index 7fc0bc0..d7f7d49 100644
--- a/jenkins/gerrit-verifier.yaml
+++ b/jenkins/gerrit-verifier.yaml
@@ -150,6 +150,20 @@
          excludes: 'gerrit/bazel-genfiles/plugins/core*/**/*.jar'
 
 - job:
+    name: Gerrit-codestyle
+    description: "Gerrit code-style checker for an open change\n"
+    defaults: verifier-defaults
+
+    builders:
+      - merge-target-branch
+      - fetch-all-submodules
+      - shell: |
+         #!/bin/bash -xe
+         cd gerrit
+         echo 'Running google-java-format check...'
+         git show --diff-filter=AM --name-only HEAD | grep java$ | xargs -r ~/format/google-java-format --dry-run
+
+- job:
     name: 'Gerrit-verifier-change'
     project-type: flow
     concurrent: true