Files
shell.kt/src/nativeMain/kotlin/com/infendro/shell/Shell.native.kt
2025-12-14 00:07:46 +01:00

32 lines
837 B
Kotlin

package com.infendro.shell
import kotlinx.cinterop.CPointer
import kotlinx.cinterop.refTo
import kotlinx.cinterop.toKString
import platform.posix.*
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)
}
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
}