Skip to content

Commit

Permalink
Add InputSource.FromParent (#21)
Browse files Browse the repository at this point in the history
  • Loading branch information
pgreze authored Jun 27, 2024
1 parent 3f0fb93 commit 8f833c4
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 12 deletions.
7 changes: 7 additions & 0 deletions src/main/kotlin/com/github/pgreze/process/InputSource.kt
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@ sealed class InputSource {
*/
class FromStream(val handler: suspend (OutputStream) -> Unit) : InputSource()

/**
* Natively supported parent provided redirection.
* @see ProcessBuilder.Redirect.INHERIT
*/
object FromParent : InputSource()

@Suppress("BlockingMethodInNonBlockingContext")
companion object {
@JvmStatic
Expand All @@ -41,4 +47,5 @@ sealed class InputSource {
internal fun InputSource.toNative() = when (this) {
is InputSource.FromFile -> ProcessBuilder.Redirect.from(file)
is InputSource.FromStream -> ProcessBuilder.Redirect.PIPE
is InputSource.FromParent -> ProcessBuilder.Redirect.INHERIT
}
34 changes: 22 additions & 12 deletions src/test/kotlin/com/github/pgreze/process/InputSourceTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -23,40 +23,50 @@ class InputSourceTest {
}

@Test
fun fromString() = runSuspendTest {
fun fromFile(@TempDir dir: Path) = runSuspendTest {
val input = dir.resolve("input.txt").toFile()
input.writeText(STRING)

val output = process(
"cat",
stdin = InputSource.fromString(STRING),
stdout = Redirect.CAPTURE
stdin = InputSource.FromFile(input),
stdout = Redirect.CAPTURE,
).unwrap()

output shouldBeEqualTo listOf(STRING)
}

@Test
fun fromFile(@TempDir dir: Path) = runSuspendTest {
val input = dir.resolve("input.txt").toFile()
input.writeText(STRING)

fun fromString() = runSuspendTest {
val output = process(
"cat",
stdin = InputSource.FromFile(input),
stdin = InputSource.fromString(STRING),
stdout = Redirect.CAPTURE,
).unwrap()

output shouldBeEqualTo listOf(STRING)
}

@Test
fun fromStream() = runSuspendTest {
fun fromInputStream() = runSuspendTest {
val inputStream = ByteArrayInputStream(STRING.toByteArray())
val output = process(
"cat",
stdin = InputSource.fromInputStream(inputStream),
stdout = Redirect.CAPTURE
stdout = Redirect.CAPTURE,
).unwrap()
output shouldBeEqualTo listOf(STRING)
}

@Test
fun fromParent() = runSuspendTest {
val output = process(
"cat",
stdin = InputSource.FromParent,
stdout = Redirect.CAPTURE,
).unwrap()
output shouldBeEqualTo listOf()
}

@Nested
@DisplayName("ensure that input and output are concurrently processed")
inner class AsyncStreams {
Expand All @@ -77,7 +87,7 @@ class InputSourceTest {
}
},
stdout = Redirect.CAPTURE,
consumer = consumer::add
consumer = consumer::add,
)
}

Expand Down

0 comments on commit 8f833c4

Please sign in to comment.