1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
use std::io;
use std::process::Stdio;
use futures::channel::mpsc;
use futures::{stream, FutureExt, SinkExt, StreamExt, TryStreamExt};
use tokio::process::Command;
use nails::execution::{self, sink_for, stream_for, ChildInput, ChildOutput, ExitCode};
use nails::{Child, Nail};
#[derive(Clone)]
pub struct ForkNail;
impl Nail for ForkNail {
fn spawn(
&self,
cmd: execution::Command,
input_stream: mpsc::Receiver<ChildInput>,
) -> Result<Child, io::Error> {
let mut child = Command::new(cmd.command.clone())
.args(cmd.args)
.env_clear()
.envs(cmd.env)
.current_dir(cmd.working_dir)
.kill_on_drop(true)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.stdin(Stdio::piped())
.spawn()?;
let stdin = child.stdin.take().unwrap();
tokio::spawn(async move {
let mut input_stream = input_stream.filter_map(|child_input| {
Box::pin(async move {
match child_input {
ChildInput::Stdin(bytes) => Some(Ok(bytes)),
ChildInput::StdinEOF => None,
}
})
});
sink_for(stdin)
.send_all(&mut input_stream)
.map(|_| ())
.await;
});
let stdout_stream = stream_for(child.stdout.take().unwrap())
.map_ok(|bytes| ChildOutput::Stdout(bytes.into()));
let stderr_stream = stream_for(child.stderr.take().unwrap())
.map_ok(|bytes| ChildOutput::Stderr(bytes.into()));
let exit_stream = child
.into_stream()
.map_ok(|exit_status| ChildOutput::Exit(ExitCode(exit_status.code().unwrap_or(-1))));
let output_stream = stream::select(stdout_stream, stderr_stream)
.chain(exit_stream)
.map(|res| match res {
Ok(o) => o,
Err(e) => {
log::warn!("IO error interacting with child process: {:?}", e);
ChildOutput::Exit(ExitCode(-1))
}
})
.boxed();
Ok(Child {
output_stream,
accepts_stdin: true,
})
}
}