From d35e68726ec276ff7a64aec42af0fa595fd008d5 Mon Sep 17 00:00:00 2001 From: Michael Comella Date: Thu, 4 Nov 2021 15:14:17 -0700 Subject: [PATCH] For #21084: add Runtime.execReadStandardOutOrThrow. This command makes it a one liner to execute an external command, which will allow us to easily run git commands in the next section. Sample error output: ``` * What went wrong: Execution failed for task ':app:gitHash'. > command exited with non-zero exit value: 1. cmd: git reev-parse --short HEAD stderr: git: 'reev-parse' is not a git command. See 'git --help'. The most similar command is rev-parse ``` --- .../org/mozilla/fenix/gradle/ext/Runtime.kt | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 buildSrc/src/main/java/org/mozilla/fenix/gradle/ext/Runtime.kt diff --git a/buildSrc/src/main/java/org/mozilla/fenix/gradle/ext/Runtime.kt b/buildSrc/src/main/java/org/mozilla/fenix/gradle/ext/Runtime.kt new file mode 100644 index 000000000..bee4e8629 --- /dev/null +++ b/buildSrc/src/main/java/org/mozilla/fenix/gradle/ext/Runtime.kt @@ -0,0 +1,29 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +package org.mozilla.fenix.gradle.ext + +import java.util.concurrent.TimeUnit + +/** + * Executes the given command with [Runtime.exec], throwing if the command returns a non-zero exit + * code or times out. If successful, returns the command's stdout. + * + * @return stdout of the command + * @throws [IllegalStateException] if the command returns a non-zero exit code or times out. + */ +fun Runtime.execReadStandardOutOrThrow(cmd: Array, timeoutSeconds: Long = 30): String { + val process = Runtime.getRuntime().exec(cmd) + + check(process.waitFor(timeoutSeconds, TimeUnit.SECONDS)) { "command unexpectedly timed out: `$cmd`" } + check(process.exitValue() == 0) { + val stderr = process.errorStream.bufferedReader().readText().trim() + """command exited with non-zero exit value: ${process.exitValue()}. + |cmd: ${cmd.joinToString(separator = " ")} + |stderr: + |${stderr}""".trimMargin() + } + + return process.inputStream.bufferedReader().readText().trim() +}