Skip to main content

cargo/util/
errors.rs

1#![allow(unknown_lints)]
2
3use std::fmt;
4use std::path::PathBuf;
5use std::process::{ExitStatus, Output};
6use std::str;
7
8use clap;
9use failure::{Context, Error, Fail};
10use log::trace;
11
12use crate::core::{TargetKind, Workspace};
13
14pub type CargoResult<T> = failure::Fallible<T>; // Alex's body isn't quite ready to give up "Result"
15
16pub trait CargoResultExt<T, E> {
17    fn chain_err<F, D>(self, f: F) -> Result<T, Context<D>>
18    where
19        F: FnOnce() -> D,
20        D: fmt::Display + Send + Sync + 'static;
21}
22
23impl<T, E> CargoResultExt<T, E> for Result<T, E>
24where
25    E: Into<Error>,
26{
27    fn chain_err<F, D>(self, f: F) -> Result<T, Context<D>>
28    where
29        F: FnOnce() -> D,
30        D: fmt::Display + Send + Sync + 'static,
31    {
32        self.map_err(|failure| {
33            let err = failure.into();
34            let context = f();
35            trace!("error: {}", err);
36            trace!("\tcontext: {}", context);
37            err.context(context)
38        })
39    }
40}
41
42#[derive(Debug, Fail)]
43#[fail(display = "failed to get 200 response from `{}`, got {}", url, code)]
44pub struct HttpNot200 {
45    pub code: u32,
46    pub url: String,
47}
48
49pub struct Internal {
50    inner: Error,
51}
52
53impl Internal {
54    pub fn new(inner: Error) -> Internal {
55        Internal { inner }
56    }
57}
58
59impl Fail for Internal {
60    fn cause(&self) -> Option<&dyn Fail> {
61        self.inner.as_fail().cause()
62    }
63}
64
65impl fmt::Debug for Internal {
66    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67        self.inner.fmt(f)
68    }
69}
70
71impl fmt::Display for Internal {
72    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73        self.inner.fmt(f)
74    }
75}
76
77/// Error wrapper related to a particular manifest and providing it's path.
78///
79/// This error adds no displayable info of it's own.
80pub struct ManifestError {
81    cause: Error,
82    manifest: PathBuf,
83}
84
85impl ManifestError {
86    pub fn new<E: Into<Error>>(cause: E, manifest: PathBuf) -> Self {
87        Self {
88            cause: cause.into(),
89            manifest,
90        }
91    }
92
93    pub fn manifest_path(&self) -> &PathBuf {
94        &self.manifest
95    }
96
97    /// Returns an iterator over the `ManifestError` chain of causes.
98    ///
99    /// So if this error was not caused by another `ManifestError` this will be empty.
100    pub fn manifest_causes(&self) -> ManifestCauses<'_> {
101        ManifestCauses { current: self }
102    }
103}
104
105impl Fail for ManifestError {
106    fn cause(&self) -> Option<&dyn Fail> {
107        self.cause.as_fail().cause()
108    }
109}
110
111impl fmt::Debug for ManifestError {
112    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
113        self.cause.fmt(f)
114    }
115}
116
117impl fmt::Display for ManifestError {
118    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
119        self.cause.fmt(f)
120    }
121}
122
123/// An iterator over the `ManifestError` chain of causes.
124pub struct ManifestCauses<'a> {
125    current: &'a ManifestError,
126}
127
128impl<'a> Iterator for ManifestCauses<'a> {
129    type Item = &'a ManifestError;
130
131    fn next(&mut self) -> Option<Self::Item> {
132        self.current = self.current.cause.downcast_ref()?;
133        Some(self.current)
134    }
135}
136
137impl<'a> ::std::iter::FusedIterator for ManifestCauses<'a> {}
138
139// =============================================================================
140// Process errors
141#[derive(Debug, Fail)]
142#[fail(display = "{}", desc)]
143pub struct ProcessError {
144    pub desc: String,
145    pub exit: Option<ExitStatus>,
146    pub output: Option<Output>,
147}
148
149// =============================================================================
150// Cargo test errors.
151
152/// Error when testcases fail
153#[derive(Debug, Fail)]
154#[fail(display = "{}", desc)]
155pub struct CargoTestError {
156    pub test: Test,
157    pub desc: String,
158    pub exit: Option<ExitStatus>,
159    pub causes: Vec<ProcessError>,
160}
161
162#[derive(Debug)]
163pub enum Test {
164    Multiple,
165    Doc,
166    UnitTest {
167        kind: TargetKind,
168        name: String,
169        pkg_name: String,
170    },
171}
172
173impl CargoTestError {
174    pub fn new(test: Test, errors: Vec<ProcessError>) -> Self {
175        if errors.is_empty() {
176            panic!("Cannot create CargoTestError from empty Vec")
177        }
178        let desc = errors
179            .iter()
180            .map(|error| error.desc.clone())
181            .collect::<Vec<String>>()
182            .join("\n");
183        CargoTestError {
184            test,
185            desc,
186            exit: errors[0].exit,
187            causes: errors,
188        }
189    }
190
191    pub fn hint(&self, ws: &Workspace<'_>) -> String {
192        match self.test {
193            Test::UnitTest {
194                ref kind,
195                ref name,
196                ref pkg_name,
197            } => {
198                let pkg_info = if ws.members().count() > 1 && ws.is_virtual() {
199                    format!("-p {} ", pkg_name)
200                } else {
201                    String::new()
202                };
203
204                match *kind {
205                    TargetKind::Bench => {
206                        format!("test failed, to rerun pass '{}--bench {}'", pkg_info, name)
207                    }
208                    TargetKind::Bin => {
209                        format!("test failed, to rerun pass '{}--bin {}'", pkg_info, name)
210                    }
211                    TargetKind::Lib(_) => format!("test failed, to rerun pass '{}--lib'", pkg_info),
212                    TargetKind::Test => {
213                        format!("test failed, to rerun pass '{}--test {}'", pkg_info, name)
214                    }
215                    TargetKind::ExampleBin | TargetKind::ExampleLib(_) => {
216                        format!("test failed, to rerun pass '{}--example {}", pkg_info, name)
217                    }
218                    _ => "test failed.".into(),
219                }
220            }
221            Test::Doc => "test failed, to rerun pass '--doc'".into(),
222            _ => "test failed.".into(),
223        }
224    }
225}
226
227// =============================================================================
228// CLI errors
229
230pub type CliResult = Result<(), CliError>;
231
232#[derive(Debug)]
233pub struct CliError {
234    pub error: Option<failure::Error>,
235    pub unknown: bool,
236    pub exit_code: i32,
237}
238
239impl CliError {
240    pub fn new(error: failure::Error, code: i32) -> CliError {
241        let unknown = error.downcast_ref::<Internal>().is_some();
242        CliError {
243            error: Some(error),
244            exit_code: code,
245            unknown,
246        }
247    }
248
249    pub fn code(code: i32) -> CliError {
250        CliError {
251            error: None,
252            exit_code: code,
253            unknown: false,
254        }
255    }
256}
257
258impl From<failure::Error> for CliError {
259    fn from(err: failure::Error) -> CliError {
260        CliError::new(err, 101)
261    }
262}
263
264impl From<clap::Error> for CliError {
265    fn from(err: clap::Error) -> CliError {
266        let code = if err.use_stderr() { 1 } else { 0 };
267        CliError::new(err.into(), code)
268    }
269}
270
271// =============================================================================
272// Construction helpers
273
274pub fn process_error(
275    msg: &str,
276    status: Option<ExitStatus>,
277    output: Option<&Output>,
278) -> ProcessError {
279    let exit = match status {
280        Some(s) => status_to_string(s),
281        None => "never executed".to_string(),
282    };
283    let mut desc = format!("{} ({})", &msg, exit);
284
285    if let Some(out) = output {
286        match str::from_utf8(&out.stdout) {
287            Ok(s) if !s.trim().is_empty() => {
288                desc.push_str("\n--- stdout\n");
289                desc.push_str(s);
290            }
291            Ok(..) | Err(..) => {}
292        }
293        match str::from_utf8(&out.stderr) {
294            Ok(s) if !s.trim().is_empty() => {
295                desc.push_str("\n--- stderr\n");
296                desc.push_str(s);
297            }
298            Ok(..) | Err(..) => {}
299        }
300    }
301
302    return ProcessError {
303        desc,
304        exit: status,
305        output: output.cloned(),
306    };
307
308    #[cfg(unix)]
309    fn status_to_string(status: ExitStatus) -> String {
310        use libc;
311        use std::os::unix::process::*;
312
313        if let Some(signal) = status.signal() {
314            let name = match signal as libc::c_int {
315                libc::SIGABRT => ", SIGABRT: process abort signal",
316                libc::SIGALRM => ", SIGALRM: alarm clock",
317                libc::SIGFPE => ", SIGFPE: erroneous arithmetic operation",
318                libc::SIGHUP => ", SIGHUP: hangup",
319                libc::SIGILL => ", SIGILL: illegal instruction",
320                libc::SIGINT => ", SIGINT: terminal interrupt signal",
321                libc::SIGKILL => ", SIGKILL: kill",
322                libc::SIGPIPE => ", SIGPIPE: write on a pipe with no one to read",
323                libc::SIGQUIT => ", SIGQUIT: terminal quite signal",
324                libc::SIGSEGV => ", SIGSEGV: invalid memory reference",
325                libc::SIGTERM => ", SIGTERM: termination signal",
326                libc::SIGBUS => ", SIGBUS: access to undefined memory",
327                #[cfg(not(target_os = "haiku"))]
328                libc::SIGSYS => ", SIGSYS: bad system call",
329                libc::SIGTRAP => ", SIGTRAP: trace/breakpoint trap",
330                _ => "",
331            };
332            format!("signal: {}{}", signal, name)
333        } else {
334            status.to_string()
335        }
336    }
337
338    #[cfg(windows)]
339    fn status_to_string(status: ExitStatus) -> String {
340        status.to_string()
341    }
342}
343
344pub fn internal<S: fmt::Display>(error: S) -> failure::Error {
345    _internal(&error)
346}
347
348fn _internal(error: &dyn fmt::Display) -> failure::Error {
349    Internal::new(failure::format_err!("{}", error)).into()
350}