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

in.specmatic.core.utilities.ExternalCommand.kt Maven / Gradle / Ivy

Go to download

Turn your contracts into executable specifications. Contract Driven Development - Collaboratively Design & Independently Deploy MicroServices & MicroFrontends. Deprecation Notice for group ID "in.specmatic" ****************************************************************************************************** Updates for "specmatic-core" will no longer be available under the deprecated group ID "in.specmatic". Please update your dependencies to use the new group ID "io.specmatic". ******************************************************************************************************

There is a newer version: 1.3.39
Show newest version
package `in`.specmatic.core.utilities

import `in`.specmatic.core.git.NonZeroExitError
import `in`.specmatic.core.pattern.ContractException
import java.io.File

class ExternalCommand(
    private val command: Array,
    private val workingDirect: String,
    private val environmentParameters: Map
) {
    constructor (
        command: String,
        workingDirect: String,
        environmentParameters: Map
    ) : this(command.split(" ").toTypedArray(), workingDirect, environmentParameters)

    constructor (
        command: Array,
        workingDirect: String,
    ) : this(command, workingDirect, emptyMap())

    fun executeAsSeparateProcess(): String {
        val commandWithParameters = command.joinToString(" ")
        return try {
            val procBuilder = ProcessBuilder(command.asList()).directory(File(workingDirect))
            val env = procBuilder.environment()
            env.putAll(environmentParameters)
            val proc = procBuilder.start()
            val out = proc.inputStream.bufferedReader().readText()
            val err = proc.errorStream.bufferedReader().readText()
            val exitCode = proc.waitFor()

            if (exitCode != 0)
                throw NonZeroExitError("""Error executing $commandWithParameters${System.lineSeparator()}ERRORS: $err${System.lineSeparator()}${System.lineSeparator()}$out${System.lineSeparator()}${System.lineSeparator()}""", exitCode)

            out
        } catch (otherExceptions: Exception) {
            throw ContractException("""Error running $commandWithParameters: ${otherExceptions.message}""",
                exceptionCause = otherExceptions)
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy