diff --git a/src/main/kotlin/build/buf/gradle/BufSupport.kt b/src/main/kotlin/build/buf/gradle/BufSupport.kt index a4da9ea1..14287ff5 100644 --- a/src/main/kotlin/build/buf/gradle/BufSupport.kt +++ b/src/main/kotlin/build/buf/gradle/BufSupport.kt @@ -16,6 +16,7 @@ package build.buf.gradle import org.gradle.api.Project import org.gradle.kotlin.dsl.dependencies +import org.jetbrains.annotations.VisibleForTesting import java.nio.charset.StandardCharsets const val BUF_BINARY_CONFIGURATION_NAME = "bufTool" @@ -80,15 +81,27 @@ internal fun AbstractBufExecTask.execBuf( logger.info("Running buf from $workingDirValue: `buf ${args.joinToString(" ")}`") val result = ProcessRunner().use { it.shell(workingDirValue, processArgs) } + handleResult(result, customErrorMessage) +} + +@VisibleForTesting +internal fun handleResult( + result: ProcessRunner.Result, + customErrorMessage: ((String) -> String)?, +) { if (result.exitCode != 0) { if (customErrorMessage != null) { val stdOut = result.stdOut.toString(StandardCharsets.UTF_8) val stdErr = result.stdErr.toString(StandardCharsets.UTF_8) - val ex = IllegalStateException(customErrorMessage(stdOut)) - if (stdErr.isNotEmpty()) { - ex.addSuppressed(IllegalStateException(result.toString())) + if (stdOut.isEmpty()) { + error(result.toString()) + } else { + val ex = IllegalStateException(customErrorMessage(stdOut)) + if (stdErr.isNotEmpty()) { + ex.addSuppressed(IllegalStateException(result.toString())) + } + throw ex } - throw ex } else { error(result.toString()) } diff --git a/src/test/kotlin/build/buf/gradle/BufSupportTest.kt b/src/test/kotlin/build/buf/gradle/BufSupportTest.kt new file mode 100644 index 00000000..df10e4f6 --- /dev/null +++ b/src/test/kotlin/build/buf/gradle/BufSupportTest.kt @@ -0,0 +1,38 @@ +// Copyright 2024 Buf Technologies, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package build.buf.gradle + +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertThrows + +class BufSupportTest { + @Test + fun `handleResult includes stderr when stdout is empty and custom error message is specified`() { + val thrown = + assertThrows { + handleResult( + ProcessRunner.Result( + emptyList(), + 1, + "".toByteArray(), + "error that would be hidden".toByteArray(), + ), + ) { "foo" } + } + + assertThat(thrown).hasMessageThat().contains("error that would be hidden") + } +}