Files
shell.kt/src/nativeMain/kotlin/com/infendro/shell/Shell.native.kt
Infendro 3565632465
Some checks failed
/ publish (push) Failing after 53s
initial commit
2025-07-12 20:23:00 +02:00

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
}