Skip to content

Instantly share code, notes, and snippets.

@tazzledazzle
Created February 5, 2018 22:30

Revisions

  1. tazzledazzle created this gist Feb 5, 2018.
    27 changes: 27 additions & 0 deletions kotlinExecFromString.gradle
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,27 @@
    // redirect to stderr/stdout
    fun String.runCommand(workingDir: File) {
    ProcessBuilder(*split(" ").toTypedArray())
    .directory(workingDir)
    .redirectOutput(Redirect.INHERIT)
    .redirectError(Redirect.INHERIT)
    .start()
    .waitFor(60, TimeUnit.MINUTES)
    }

    // capture output as string
    fun String.runCommand(workingDir: File): String? {
    try {
    val parts = this.split("\\s".toRegex())
    val proc = ProcessBuilder(*parts.toTypedArray())
    .directory(workingDir)
    .redirectOutput(ProcessBuilder.Redirect.PIPE)
    .redirectError(ProcessBuilder.Redirect.PIPE)
    .start()

    proc.waitFor(60, TimeUnit.MINUTES)
    return proc.inputStream.bufferedReader().readText()
    } catch(e: IOException) {
    e.printStackTrace()
    return null
    }
    }