Running build_log_simplifier.py for build server builds

Hopefully this will allow build failure emails to be more than just the bottom of a stacktrace

Bug: 157734343
Bug: 154755010
Test: ./gradlew && echo ok
Test: ./gradlew nonexistenttask && echo ok # and see that this fails
Test: echo "syntaxerror" >> core/core/src/main/java/androidx/core/app/AppComponentFactory.java && ./gradlew :core:core:assembleDebug --stacktrace -Pandroidx.summarizeStderr >/dev/null # and see that the stacktrace at the end of the build is short, but that a fuller stacktrace appears above

Change-Id: Id6164ae6a644dd0f7c595c5dc619778066520d53
diff --git a/gradlew b/gradlew
index 83c53c4..49facc3 100755
--- a/gradlew
+++ b/gradlew
@@ -1,4 +1,6 @@
 #!/usr/bin/env bash
+set -o pipefail
+set -e
 
 ##############################################################################
 ##
@@ -234,7 +236,41 @@
     # so that this message still prints even if buildSrc itself fails
     echo
     echo See also development/diagnose-build-failure for help with build failures in this project.
-    exit 1
+    return 1
+  fi
+}
+
+# Runs a build and possibly modifies the output before displaying it, to make it easier to
+# interpret, and to make the relevant error messages fit inside of build failure emails.
+function runBuild() {
+  if [[ " ${@} " =~ " -Pandroidx.summarizeStderr " ]]; then
+    # run Gradle and save stdout and stderr into $logFile
+    if [ -n "$DIST_DIR" ]; then
+      LOG_DIR="$DIST_DIR"
+    else
+      LOG_DIR="$OUT_DIR/dist"
+    fi
+    mkdir -p "$LOG_DIR"
+    logFile="$LOG_DIR/gradle.log"
+    rm -f "$logFile"
+    if runGradle "$@" > >(tee -a "$logFile") 2> >(tee -a "$logFile" >&2); then
+      echo Gradle success
+    else
+      echo >&2
+      echo Gradle failure >&2
+      echo Attempting to locate the relevant error messages via build_log_simplifier.py >&2
+      echo >&2
+      # Try to identify the most relevant lines of output, and put them at the bottom of the
+      # output where they will also be placed into the build failure email.
+      # TODO: We may be able to stop cleaning up Gradle's output after Gradle can do this on its own:
+      # https://github.com/gradle/gradle/issues/1005
+      # and https://github.com/gradle/gradle/issues/13090
+      summaryLog="$LOG_DIR/error_summary.log"
+      $SCRIPT_PATH/development/build_log_simplifier.py $logFile | tail -n 100 | tee "$summaryLog" >&2
+      return 1
+    fi
+  else
+    runGradle "$@"
   fi
 }
 
@@ -244,9 +280,9 @@
   exit 1
 fi
 
-runGradle "$@"
+runBuild "$@"
 # Check whether we were given the "-PverifyUpToDate" argument
 if [[ " ${@} " =~ " -PverifyUpToDate " ]]; then
   # Re-run Gradle, and find all tasks that are unexpectly out of date
-  runGradle "$@" -PdisallowExecution --continue --info
+  runBuild "$@" -PdisallowExecution --continue --info
 fi