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
//! The [`Error`] type used in the return type of [`run_result!`].
use crate::config::Config;
use std::{ffi::OsString, fmt::Display, io, process::ExitStatus, string::FromUtf8Error};
/// Error type returned when an error occurs while using [`run_result!`]
/// or [`crate::input::Input::run_result`].
///
/// [`run!`], [`crate::input::Input::run`], [`run_output!`],
/// and [`crate::input::Input::run_output`] will turn these errors
/// into panics.
#[derive(Debug)]
pub enum Error {
/// The [`Input`](crate::Input)s to a command must produce
/// at least one argument: the executable to run.
///
/// ```
/// use cradle::prelude::*;
///
/// let result: Result<(), cradle::Error> = run_result!(());
/// match result {
/// Err(Error::NoExecutableGiven) => {}
/// _ => panic!(),
/// }
/// ```
NoExecutableGiven,
/// A `file not found` error occurred while trying to spawn
/// the child process:
///
/// ```
/// use cradle::prelude::*;
///
/// let result: Result<(), Error> = run_result!("does-not-exist");
/// match result {
/// Err(Error::FileNotFound { .. }) => {}
/// _ => panic!(),
/// }
/// ```
///
/// Note that this error doesn't necessarily mean that the executable file
/// could not be found.
/// A few other circumstances in which this can occur are:
///
/// - a binary is dynamically linked against a library,
/// but that library cannot be found, or
/// - the executable starts with a
/// [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)),
/// but the interpreter specified in the shebang cannot be found.
FileNotFound {
executable: OsString,
source: io::Error,
},
/// An IO error during execution. A few circumstances in which this can occur are:
///
/// - spawning the child process fails (for another reason than
/// [`FileNotFound`](Error::FileNotFound)),
/// - writing to `stdin` of the child process fails,
/// - reading from `stdout` or `stderr` of the child process fails,
/// - writing to the parent's `stdout` or `stderr` fails,
/// - the given executable doesn't have the executable flag set.
CommandIoError { message: String, source: io::Error },
/// The child process exited with a non-zero exit code.
///
/// ```
/// use cradle::prelude::*;
///
/// let result: Result<(), cradle::Error> = run_result!("false");
/// match result {
/// Err(Error::NonZeroExitCode { .. }) => {}
/// _ => panic!(),
/// }
/// ```
///
/// This error will be suppressed when [`Status`](crate::Status) is used.
NonZeroExitCode {
full_command: String,
exit_status: ExitStatus,
},
/// The child process's `stdout` is being captured,
/// (e.g. with [`StdoutUntrimmed`](crate::StdoutUntrimmed)),
/// but the process wrote bytes to its `stdout` that are not
/// valid utf-8.
InvalidUtf8ToStdout {
full_command: String,
source: FromUtf8Error,
},
/// The child process's `stderr` is being captured,
/// (with [`Stderr`](crate::Stderr)),
/// but the process wrote bytes to its `stderr` that are not
/// valid utf-8.
InvalidUtf8ToStderr {
full_command: String,
source: FromUtf8Error,
},
/// This error is raised when an internal invariant of `cradle` is broken,
/// and likely indicates a bug.
Internal {
message: String,
full_command: String,
config: Config,
},
}
impl Error {
pub(crate) fn command_io_error(config: &Config, source: io::Error) -> Error {
Error::CommandIoError {
message: format!("{}:\n {}", config.full_command(), source),
source,
}
}
pub(crate) fn internal(message: &str, config: &Config) -> Error {
Error::Internal {
message: message.to_string(),
full_command: config.full_command(),
config: config.clone(),
}
}
}
#[doc(hidden)]
#[rustversion::attr(since(1.46), track_caller)]
pub fn panic_on_error<T>(result: Result<T, Error>) -> T {
match result {
Ok(t) => t,
Err(error) => panic!("cradle error: {}", error),
}
}
fn english_list(list: &[&str]) -> String {
let mut result = String::new();
for (i, word) in list.iter().enumerate() {
let is_first = i == 0;
let is_last = i == list.len() - 1;
if !is_first {
result.push_str(if is_last { " and " } else { ", " });
}
result.push('\'');
result.push_str(word);
result.push('\'');
}
result
}
fn executable_with_whitespace_note(executable: &str) -> Option<String> {
let words = executable.split_whitespace().collect::<Vec<&str>>();
if words.len() >= 2 {
let intended_executable = words[0];
let intended_arguments = &words[1..];
let mut result = format!(
"note: Given executable name '{}' contains whitespace.\n",
executable
);
result.push_str(&format!(
" Did you mean to run '{}', with {} as {}?\n",
intended_executable,
english_list(intended_arguments),
if intended_arguments.len() == 1 {
"the argument"
} else {
"arguments"
},
));
result.push_str(concat!(
" Consider using Split: ",
"https://docs.rs/cradle/latest/cradle/input/struct.Split.html"
));
Some(result)
} else {
None
}
}
impl Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
use Error::*;
match self {
NoExecutableGiven => write!(f, "no arguments given"),
FileNotFound { executable, .. } => {
let executable = executable.to_string_lossy();
write!(f, "File not found error when executing '{}'", executable)?;
if let Some(whitespace_note) = executable_with_whitespace_note(executable.as_ref())
{
write!(f, "\n{}", whitespace_note)?;
}
Ok(())
}
CommandIoError { message, .. } => write!(f, "{}", message),
NonZeroExitCode {
full_command,
exit_status,
} => {
if let Some(exit_code) = exit_status.code() {
write!(
f,
"{}:\n exited with exit code: {}",
full_command, exit_code
)
} else {
write!(f, "{}:\n exited with {}", full_command, exit_status)
}
}
InvalidUtf8ToStdout { full_command, .. } => {
write!(f, "{}:\n invalid utf-8 written to stdout", full_command)
}
InvalidUtf8ToStderr { full_command, .. } => {
write!(f, "{}:\n invalid utf-8 written to stderr", full_command)
}
Internal { .. } => {
let snippets = vec![
"Congratulations, you've found a bug in cradle! :/",
"Please, open an issue on https://github.com/soenkehahn/cradle/issues",
"with the following information:",
];
writeln!(f, "{}\n{:#?}", snippets.join(" "), self)
}
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
use Error::*;
match self {
FileNotFound { source, .. } | CommandIoError { source, .. } => Some(source),
InvalidUtf8ToStdout { source, .. } | InvalidUtf8ToStderr { source, .. } => Some(source),
NoExecutableGiven | NonZeroExitCode { .. } | Internal { .. } => None,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::prelude::*;
use executable_path::executable_path;
#[test]
fn invalid_utf8_to_stdout_has_source() {
let result: Result<StdoutUntrimmed, crate::Error> = run_result!(
executable_path("cradle_test_helper").to_str().unwrap(),
"invalid utf-8 stdout"
);
assert!(std::error::Error::source(&result.unwrap_err()).is_some());
}
#[test]
fn invalid_utf8_to_stderr_has_source() {
let result: Result<Stderr, crate::Error> = run_result!(
executable_path("cradle_test_helper").to_str().unwrap(),
"invalid utf-8 stderr"
);
assert!(std::error::Error::source(&result.unwrap_err()).is_some());
}
mod english_list {
use super::*;
use pretty_assertions::assert_eq;
macro_rules! test {
($name:ident, $input:expr, $expected:expr) => {
#[test]
fn $name() {
assert_eq!(english_list($input), $expected);
}
};
}
test!(one, &["foo"], "'foo'");
test!(two, &["foo", "bar"], "'foo' and 'bar'");
test!(three, &["foo", "bar", "baz"], "'foo', 'bar' and 'baz'");
test!(
four,
&["foo", "bar", "baz", "boo"],
"'foo', 'bar', 'baz' and 'boo'"
);
}
}