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
275
276
277
278
279
280
281
282
283
284
use std::{
collections::HashMap,
env,
ffi::{OsStr, OsString},
path::{Path, PathBuf},
process::Command,
sync::{Arc, Mutex},
time::Duration,
};
use crate::{Error, Result, ShellTaskLog};
use crossbeam_channel::{unbounded, Receiver, Sender};
mod behavior;
mod output;
mod runner;
pub use behavior::ShellTaskBehavior;
pub use output::ShellTaskOutput;
use runner::ShellTaskRunner;
/// A [`ShellTask`] runs commands and provides a passthrough log handler
/// for each log line.
#[derive(Debug)]
pub struct ShellTask {
bin: String,
args: Vec<String>,
current_dir: PathBuf,
envs: HashMap<OsString, OsString>,
full_command: String,
log_sender: Sender<ShellTaskLog>,
log_receiver: Receiver<ShellTaskLog>,
}
impl ShellTask {
/// Create a new [`ShellTask`] with a log line handler.
pub fn new(command: &str) -> Result<Self> {
let current_dir =
env::current_dir().map_err(|source| Error::CouldNotFindCurrentDirectory { source })?;
let command = command.to_string();
let args: Vec<&str> = command.split(' ').collect();
let (bin, args) = match args.len() {
0 => Err(Error::InvalidTask {
task: command.to_string(),
reason: "an empty string is not a command".to_string(),
}),
1 => Ok((args[0], Vec::new())),
_ => Ok((args[0], Vec::from_iter(args[1..].iter()))),
}?;
if which::which(bin).is_err() {
Err(Error::InvalidTask {
task: command.to_string(),
reason: format!("'{}' is not installed on this machine", &bin),
})
} else {
let (log_sender, log_receiver) = unbounded();
Ok(Self {
bin: bin.to_string(),
args: args.iter().map(|s| s.to_string()).collect(),
full_command: command,
envs: HashMap::new(),
current_dir,
log_sender,
log_receiver,
})
}
}
/// Adds an environment variable to the command run by [`ShellTask`].
pub fn env<K, V>(&mut self, key: K, value: V) -> &mut ShellTask
where
K: AsRef<OsStr>,
V: AsRef<OsStr>,
{
self.envs
.insert(key.as_ref().to_os_string(), value.as_ref().to_os_string());
self
}
/// Sets the directory the command should be run in.
pub fn current_dir<P>(&mut self, path: P)
where
P: AsRef<Path>,
{
self.current_dir = path.as_ref().to_path_buf();
}
/// Returns the full command that was used to instantiate this [`ShellTask`].
pub fn descriptor(&self) -> String {
self.full_command.to_string()
}
/// Returns the [`ShellTask::descriptor`] with the classic `$` shell prefix.
pub fn bash_descriptor(&self) -> String {
format!("$ {}", self.descriptor())
}
/// Returns the [`ShellTaskRunner`] from the internal configuration.
fn get_command(&self) -> Command {
let mut command = Command::new(&self.bin);
command
.args(&self.args)
.envs(&self.envs)
.current_dir(&self.current_dir);
command
}
/// Run a [`ShellTask`], applying the log handler to each line.
///
/// You can make the task terminate early if your `log_handler`
/// returns [`ShellTaskBehavior::EarlyReturn<T>`]. When this variant
/// is returned from a log handler, [`ShellTask::run`] will return [`Some<T>`].
///
/// # Example
///
/// ```
/// use anyhow::anyhow;
/// use shell_candy::{ShellTask, ShellTaskLog, ShellTaskOutput, ShellTaskBehavior};
///
/// fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
/// let result = ShellTask::new("rustc --version")?.run(|line| {
/// match line {
/// ShellTaskLog::Stderr(_) => {
/// ShellTaskBehavior::Passthrough
/// },
/// ShellTaskLog::Stdout(message) => {
/// eprintln!("{}", &message);
/// ShellTaskBehavior::EarlyReturn(Ok(message))
/// }
/// }
/// })?;
/// assert!(matches!(result, ShellTaskOutput::EarlyReturn { .. }));
/// Ok(())
/// }
/// ```
///
/// If your `log_handler` returns [`ShellTaskBehavior::Passthrough`] for
/// the entire lifecycle of the task, [`ShellTask::run`] will return [`ShellTaskOutput::CompleteOutput`].
///
/// # Example
///
/// ```
/// use anyhow::anyhow;
/// use shell_candy::{ShellTask, ShellTaskLog, ShellTaskOutput, ShellTaskBehavior};
///
/// fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
/// let result = ShellTask::new("rustc --version")?.run(|line| {
/// match line {
/// ShellTaskLog::Stderr(message) | ShellTaskLog::Stdout(message) => {
/// eprintln!("info: {}", &message);
/// ShellTaskBehavior::<()>::Passthrough
/// }
/// }
/// })?;
/// assert!(matches!(result, ShellTaskOutput::CompleteOutput { .. }));
/// Ok(())
/// }
/// ```
pub fn run<F, T>(&self, log_handler: F) -> Result<ShellTaskOutput<T>>
where
F: Fn(ShellTaskLog) -> ShellTaskBehavior<T> + Send + Sync + 'static,
T: Send + Sync + 'static,
{
let log_drain: Arc<Mutex<Vec<ShellTaskLog>>> = Arc::new(Mutex::new(Vec::new()));
let log_drainer = log_drain.clone();
let log_drain_filler = log_drain.clone();
let log_receiver = self.log_receiver.clone();
let full_command = self.full_command.to_string();
let maybe_result = Arc::new(Mutex::new(None));
let early_terminator = maybe_result.clone();
let collected_stdout_lines = Arc::new(Mutex::new(Vec::new()));
let collected_stderr_lines = Arc::new(Mutex::new(Vec::new()));
let stdout_collector = collected_stdout_lines.clone();
let stderr_collector = collected_stderr_lines.clone();
rayon::spawn(move || {
while let Ok(line) = log_receiver.recv() {
match &line {
ShellTaskLog::Stderr(stderr) => {
if let Ok(mut stderr_lines) = stderr_collector.clone().lock() {
stderr_lines.push(stderr.to_string())
}
}
ShellTaskLog::Stdout(stdout) => {
if let Ok(mut stdout_lines) = stdout_collector.clone().lock() {
stdout_lines.push(stdout.to_string())
}
}
}
if let Ok(mut log_decrementer) = log_drainer.clone().lock() {
if let Some(stderr_pos) = log_decrementer
.iter()
.position(|e| matches!(e, ShellTaskLog::Stderr(_)))
{
log_decrementer.remove(stderr_pos);
} else if let Some(stdout_pos) = log_decrementer
.iter()
.position(|e| matches!(e, ShellTaskLog::Stdout(_)))
{
log_decrementer.remove(stdout_pos);
}
match (log_handler)(line) {
ShellTaskBehavior::EarlyReturn(early_return) => {
if let Ok(mut maybe_result) = early_terminator.lock() {
if maybe_result.is_none() {
*maybe_result = Some(early_return);
break;
}
}
}
ShellTaskBehavior::Passthrough => continue,
}
} else if let Ok(mut maybe_result) = early_terminator.lock() {
if maybe_result.is_none() {
*maybe_result =
Some(Err(Box::new(Error::PoisonedLog { task: full_command })));
break;
}
} else {
continue;
}
}
});
let task = ShellTaskRunner::run(
self.get_command(),
self.full_command.to_string(),
self.log_sender.clone(),
log_drain_filler,
)?;
let output = task
.child
.wait_with_output()
.map_err(|source| Error::CouldNotWait {
task: self.full_command.to_string(),
source,
})?;
// wait until the log drain is empty so we know they've all been processed
loop {
std::thread::sleep(Duration::from_millis(200));
match log_drain.try_lock() {
Ok(log_drain) => {
if log_drain.is_empty() {
break;
} else {
continue;
}
}
_ => continue,
}
}
if output.status.success() {
let collected_stderr_lines = collected_stderr_lines.lock().unwrap().to_vec();
let collected_stdout_lines = collected_stdout_lines.lock().unwrap().to_vec();
if let Some(result) = maybe_result.clone().lock().unwrap().take() {
result
.map(|t| ShellTaskOutput::EarlyReturn {
stderr_lines: collected_stderr_lines,
stdout_lines: collected_stdout_lines,
return_value: t,
})
.map_err(|e| e.into())
} else {
Ok(ShellTaskOutput::CompleteOutput {
status: output.status,
stdout_lines: collected_stdout_lines,
stderr_lines: collected_stderr_lines,
})
}
} else {
Err(Error::TaskFailure {
task: self.full_command.to_string(),
exit_status: output.status,
})
}
}
}