35 lines
932 B
Kotlin
35 lines
932 B
Kotlin
package com.infendro.shell
|
|
|
|
import kotlinx.cinterop.CPointer
|
|
import kotlinx.cinterop.ExperimentalForeignApi
|
|
import kotlinx.cinterop.refTo
|
|
import kotlinx.cinterop.toKString
|
|
import platform.posix.*
|
|
|
|
@ExperimentalForeignApi
|
|
internal actual suspend fun execute(
|
|
command: Array<String>,
|
|
directory: String?,
|
|
): Shell.Result {
|
|
val command = command.joinToString(" ") { "\"$it\"" }
|
|
if (directory != null) {
|
|
chdir(directory)
|
|
}
|
|
val stream = popen(command, "r")!!
|
|
val value = stream.readLines().joinToString("")
|
|
val code = pclose(stream)
|
|
return Shell.Result(code, value)
|
|
}
|
|
|
|
@ExperimentalForeignApi
|
|
private fun CPointer<FILE>.readLines(): List<String> {
|
|
val lines = mutableListOf<String>()
|
|
val buffer = ByteArray(4096)
|
|
while (true) {
|
|
val line = fgets(buffer.refTo(0), buffer.size, this)
|
|
if (line == null) break
|
|
lines.add(line.toKString())
|
|
}
|
|
return lines
|
|
}
|