All Downloads are FREE. Search and download functionalities are using the official Maven repository.

ru.tinkoff.plugins.buildmetrics.android.utils.ExecUtils.kt Maven / Gradle / Ivy

package ru.tinkoff.plugins.buildmetrics.android.utils

import java.io.IOException

/**
 * Standard exit code when `command not found`
 */
private const val EXIT_CODE_COMMAND_NOT_FOUND = 127

@Throws(CommandNotFoundException::class, IOException::class)
internal fun execCommandAndWait(command: String): Process {
    try {
        val process = Runtime.getRuntime().exec(command)
        process.waitFor()
        process.checkExitCode()
        return process
    } catch (e: IOException) {
        if (e.message?.contains("No such file or directory") == true) {
            val binaryName = command.substringBefore(' ')
            throw CommandNotFoundException(binaryName, cause = e)
        }
        throw e
    }
}

private fun Process.checkExitCode() {
    val command = info().command().orElse("unknown")
    when (val exitCode = exitValue()) {
        0 -> return
        EXIT_CODE_COMMAND_NOT_FOUND -> throw CommandNotFoundException(command)
        else -> throw IllegalStateException("Command '$command' has exited with code $exitCode")
    }
}

private class CommandNotFoundException(command: String, cause: Throwable? = null) : IllegalStateException(
    "Command '$command' not found, make sure it's accessible via 'PATH'",
    cause
)




© 2015 - 2025 Weber Informatics LLC | Privacy Policy