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
use std::{
io::{self, BufRead, BufReader, LineWriter, Read},
iter,
process::{Command, Stdio},
sync::mpsc,
thread,
time::Duration,
};
use super::ShellOptions;
use crate::{
traits::{ShellProcess, SpawnShell, SpawnedShell},
Captured, Interaction, Transcript, UserInput,
};
#[derive(Debug)]
struct Timeouts {
inner: iter::Chain<iter::Once<Duration>, iter::Repeat<Duration>>,
}
impl Timeouts {
fn new<Cmd: SpawnShell>(options: &ShellOptions<Cmd>) -> Self {
Self {
inner: iter::once(options.init_timeout + options.io_timeout)
.chain(iter::repeat(options.io_timeout)),
}
}
fn next(&mut self) -> Duration {
self.inner.next().unwrap()
}
}
impl Transcript {
#[cfg(not(windows))]
fn write_line(writer: &mut impl io::Write, line: &str) -> io::Result<()> {
writeln!(writer, "{}", line)
}
#[cfg(windows)]
fn write_line(writer: &mut impl io::Write, line: &str) -> io::Result<()> {
writeln!(writer, "{}\r", line)
}
fn read_echo(
input_line: &str,
lines_recv: &mpsc::Receiver<Vec<u8>>,
io_timeout: Duration,
) -> io::Result<()> {
if lines_recv.recv_timeout(io_timeout).is_ok() {
Ok(())
} else {
let err = format!(
"could not read all input `{}` back from an echoing terminal",
input_line
);
Err(io::Error::new(io::ErrorKind::BrokenPipe, err))
}
}
#[allow(clippy::missing_panics_doc)]
pub fn from_inputs<Cmd: SpawnShell>(
options: &mut ShellOptions<Cmd>,
inputs: impl IntoIterator<Item = UserInput>,
) -> io::Result<Self> {
let SpawnedShell {
mut shell,
reader,
writer,
} = options.spawn_shell()?;
let stdout = BufReader::new(reader);
let (out_lines_send, out_lines_recv) = mpsc::channel();
let io_handle = thread::spawn(move || {
let mut lines = stdout.split(b'\n');
while let Some(Ok(line)) = lines.next() {
if out_lines_send.send(line).is_err() {
break;
}
}
});
let mut stdin = LineWriter::new(writer);
let mut timeouts = Timeouts::new(options);
if shell.is_echoing() {
for cmd in &options.init_commands {
Self::write_line(&mut stdin, cmd)?;
Self::read_echo(cmd, &out_lines_recv, timeouts.next())?;
while out_lines_recv.recv_timeout(timeouts.next()).is_ok() {
}
}
} else {
for cmd in &options.init_commands {
Self::write_line(&mut stdin, cmd)?;
}
}
while out_lines_recv.recv_timeout(timeouts.next()).is_ok() {
}
let mut transcript = Self::new();
for input in inputs {
shell.check_is_alive()?;
let input_lines = input.text.split('\n');
for input_line in input_lines {
Self::write_line(&mut stdin, input_line)?;
if shell.is_echoing() {
Self::read_echo(input_line, &out_lines_recv, options.io_timeout)?;
}
}
let mut output = String::new();
while let Ok(mut line) = out_lines_recv.recv_timeout(options.io_timeout) {
if line.last() == Some(&b'\r') {
line.pop();
}
let line = String::from_utf8(line)
.map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err.utf8_error()))?;
if let Some(mapped_line) = (options.line_mapper)(line) {
output.push_str(&mapped_line);
output.push('\n');
}
}
if output.ends_with('\n') {
output.truncate(output.len() - 1);
}
transcript.interactions.push(Interaction {
input,
output: Captured::new(output),
});
}
drop(stdin);
thread::sleep(options.io_timeout / 4);
shell.terminate()?;
io_handle.join().ok();
Ok(transcript)
}
pub fn capture_output(
&mut self,
input: UserInput,
command: &mut Command,
) -> io::Result<&mut Self> {
let (mut pipe_reader, pipe_writer) = os_pipe::pipe()?;
let mut child = command
.stdin(Stdio::null())
.stdout(pipe_writer.try_clone()?)
.stderr(pipe_writer)
.spawn()?;
command.stdout(Stdio::null()).stderr(Stdio::null());
let mut output = vec![];
pipe_reader.read_to_end(&mut output)?;
child.wait()?;
let output = String::from_utf8(output)
.map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err.utf8_error()))?;
self.interactions.push(Interaction {
input,
output: Captured::new(output),
});
Ok(self)
}
}