error_report/
clean.rs

1use std::error::Error;
2
3// Based on https://github.com/shepmaster/snafu
4// Copyright (c) 2019- Jake Goulding
5//
6// Permission is hereby granted, free of charge, to any
7// person obtaining a copy of this software and associated
8// documentation files (the "Software"), to deal in the
9// Software without restriction, including without
10// limitation the rights to use, copy, modify, merge,
11// publish, distribute, sublicense, and/or sell copies of
12// the Software, and to permit persons to whom the Software
13// is furnished to do so, subject to the following
14// conditions:
15//
16// The above copyright notice and this permission notice
17// shall be included in all copies or substantial portions
18// of the Software.
19//
20// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
21// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
22// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
23// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
24// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
25// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
27// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
28// DEALINGS IN THE SOFTWARE.
29
30/// Provides the cleaned_errors method on errors, which returns
31/// an iterator that removes duplicated error messages from the error
32/// and its sources.
33pub trait CleanedErrors {
34    fn cleaned_errors<'a, 'b, 'c>(&'a self) -> CleanedErrorText<'b, 'c>
35    where
36        'a: 'b;
37}
38
39impl<T: Error + 'static> CleanedErrors for T {
40    fn cleaned_errors<'a, 'b, 'c>(&'a self) -> CleanedErrorText<'b, 'c>
41    where
42        'a: 'b,
43    {
44        CleanedErrorText::new(self)
45    }
46}
47
48/// An iterator that removes duplicated error messages from errors.
49///
50/// Some errors return both a source and include the source message in
51/// their own error message. This causes duplication with reporters that
52/// print the whole chain.
53///
54/// This iterator checks if the error message contains the source
55/// error's message as a suffix and removes it.
56pub struct CleanedErrorText<'a, 'b>(Option<CleanedErrorTextStep<'a, 'b>>);
57
58struct CleanedErrorTextStep<'a, 'b> {
59    error: &'a (dyn Error + 'b),
60    /// error text extracted by the previous item and saved here to avoid calling to_string twice
61    error_text: String,
62}
63
64impl<'a, 'b> CleanedErrorTextStep<'a, 'b> {
65    fn new(err: &'a (dyn Error + 'b)) -> Self {
66        Self {
67            error: err,
68            error_text: err.to_string(),
69        }
70    }
71}
72
73impl<'a, 'b> CleanedErrorText<'a, 'b> {
74    pub fn new(err: &'a (dyn Error + 'b)) -> Self {
75        Self(Some(CleanedErrorTextStep::new(err)))
76    }
77}
78
79impl<'a, 'b> Iterator for CleanedErrorText<'a, 'b> {
80    /// The original error, the cleaned display string, and whether it has been cleaned
81    type Item = (&'a (dyn Error + 'b), String, bool);
82
83    fn next(&mut self) -> Option<Self::Item> {
84        let step = self.0.take()?;
85        let error_text = step.error_text;
86        let err = step.error;
87
88        match err.source() {
89            Some(source) => {
90                let source_text = source.to_string();
91                let (cleaned_text, cleaned) = error_text
92                    .strip_suffix(&source_text)
93                    .map(|text| {
94                        let text = text.trim_end();
95                        (text.strip_suffix(':').unwrap_or(text).to_owned(), true)
96                    })
97                    .unwrap_or_else(|| (error_text, false));
98
99                self.0 = Some(CleanedErrorTextStep {
100                    error: source,
101                    error_text: source_text,
102                });
103                Some((err, cleaned_text, cleaned))
104            }
105            None => Some((err, error_text, false)),
106        }
107    }
108}