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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
#![deny(missing_docs)]
extern crate mio;
extern crate mio_extras;
use mio::{Evented, Poll, PollOpt, Ready, Token};
use mio_extras::channel::{channel, Receiver, Sender};
use std::io::{Error, ErrorKind, Read, Result, Write};
use std::process::{Child, Command, ExitStatus};
use std::thread::spawn;
#[cfg(test)]
mod test;
pub trait CommandAsync {
fn spawn_async(&mut self) -> Result<Process>;
}
impl CommandAsync for Command {
fn spawn_async(&mut self) -> Result<Process> {
let child = self.spawn()?;
Ok(Process::from_child(child))
}
}
pub struct Process {
receiver: Receiver<ProcessEvent>,
stdin: Option<std::process::ChildStdin>,
}
impl Process {
pub fn try_recv(&mut self) -> std::result::Result<ProcessEvent, std::sync::mpsc::TryRecvError> {
self.receiver.try_recv()
}
pub fn from_child(mut child: Child) -> Process {
let (sender, receiver) = channel();
if let Some(stdout) = child.stdout.take() {
spawn(create_reader(stdout, sender.clone(), StdioChannel::Stdout));
}
if let Some(stderr) = child.stderr.take() {
spawn(create_reader(stderr, sender.clone(), StdioChannel::Stderr));
}
let stdin = child.stdin.take();
spawn(move || {
let result = match child.wait_with_output() {
Err(e) => {
let _ = sender.send(ProcessEvent::CommandError(e));
return;
}
Ok(r) => r,
};
if !result.stdout.is_empty() {
if SendResult::Abort
== try_send_buffer(&result.stdout, StdioChannel::Stdout, &sender)
{
return;
}
}
if !result.stderr.is_empty() {
if SendResult::Abort
== try_send_buffer(&result.stderr, StdioChannel::Stderr, &sender)
{
return;
}
}
let _ = sender.send(ProcessEvent::Exit(result.status));
});
Process { receiver, stdin }
}
}
impl Write for Process {
fn write(&mut self, buf: &[u8]) -> Result<usize> {
match self.stdin.as_mut() {
Some(ref mut stdin) => stdin.write(buf),
None => Err(Error::from(ErrorKind::NotConnected)),
}
}
fn flush(&mut self) -> Result<()> {
match self.stdin.as_mut() {
Some(ref mut stdin) => stdin.flush(),
None => Err(Error::from(ErrorKind::NotConnected)),
}
}
}
impl Evented for Process {
fn register(&self, poll: &Poll, token: Token, interest: Ready, ops: PollOpt) -> Result<()> {
self.receiver.register(poll, token, interest, ops)
}
fn reregister(&self, poll: &Poll, token: Token, interest: Ready, ops: PollOpt) -> Result<()> {
self.receiver.reregister(poll, token, interest, ops)
}
fn deregister(&self, poll: &Poll) -> Result<()> {
self.receiver.deregister(poll)
}
}
#[derive(PartialEq, Eq, Debug)]
enum SendResult {
Abort,
Ok,
}
fn try_send_buffer(
buffer: &[u8],
channel: StdioChannel,
sender: &Sender<ProcessEvent>,
) -> SendResult {
let str = match std::str::from_utf8(buffer) {
Ok(s) => s,
Err(e) => {
let _ = sender.send(ProcessEvent::Utf8Error(channel, e));
return SendResult::Abort;
}
};
if str.is_empty() {
println!("Aborting try_send_buffer because we're sending empty strings");
println!("Channel: {:?}", channel);
return SendResult::Abort;
}
if let Err(_) = sender.send(ProcessEvent::Data(channel, String::from(str))) {
SendResult::Abort
} else {
SendResult::Ok
}
}
fn create_reader<T: Read + 'static>(
mut stream: T,
sender: Sender<ProcessEvent>,
channel: StdioChannel,
) -> impl FnOnce() {
move || {
let mut buffer = [0u8; 1024];
loop {
match stream.read(&mut buffer[..]) {
Ok(0) => {
break;
}
Ok(n) => {
if SendResult::Abort == try_send_buffer(&buffer[..n], channel, &sender) {
break;
}
}
Err(e) => {
let _ = sender.send(ProcessEvent::IoError(channel, e));
break;
}
}
}
}
}
#[derive(Debug)]
pub enum ProcessEvent {
Data(StdioChannel, String),
CommandError(std::io::Error),
IoError(StdioChannel, std::io::Error),
Utf8Error(StdioChannel, std::str::Utf8Error),
Exit(ExitStatus),
}
#[derive(Copy, Clone, Debug)]
pub enum StdioChannel {
Stdout,
Stderr,
}