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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
//! Error handling
//!
//! A module allowing us to create more detailed, context aware, errors.
//!
//! # Examples
//!
//! Result chaining example.
//!
//! ```rust
//! use balena_temen::error::*;
//!
//! fn eval_as_number() -> Result<()> {
//!     Err(Error::with_message("unable to evaluate as a number")
//!         .context("value", "some value")
//!         .context("expected", "number"))
//! }
//!
//! fn eval_math() -> Result<()> {
//!     Ok(eval_as_number()
//!         .frame_with(|| "eval_math".into())
//!         .context_with(|| ("rhs".to_string(), "`23`".to_string()))?)
//! }
//!
//! fn eval() -> Result<()> {
//!     Ok(eval_math().frame_with_name("eval").context("expression", "1 = `23`")?)
//! }
//!
//! eprintln!("{}", eval().err().unwrap());
//! ```
//!
//! Printed error:
//!
//! ```text
//! temen: unable to evaluate as a number
//!  ├ frame[0]
//!  |  └ context:
//!  |     ├ value: some value
//!  |     └ expected: number
//!  ├ frame[1]: eval_math
//!  |  └ context:
//!  |     └ rhs: `23`
//!  └ frame[2]: eval
//!     └ context:
//!        └ expression: 1 = `23`
//! ```
use std::borrow::Cow;
use std::error;
use std::fmt;
use std::result;

/// Standard library result wrapper
pub type Result<T> = result::Result<T, Error>;

type Display = Cow<'static, str>;

/// Result extension
pub trait ResultExt<T> {
    /// Appends key, value pair to context of the last frame
    ///
    /// # Arguments
    ///
    /// * `k` - A key
    /// * `v` - A value
    fn context<K, V>(self, k: K, v: V) -> Result<T>
    where
        K: Into<Display>,
        V: Into<Display>;

    /// Appends key, value pair to context of the last frame
    ///
    /// # Arguments
    ///
    /// * `f` - A function which must return tuple (key, value)
    fn context_with<F>(self, f: F) -> Result<T>
    where
        F: FnOnce() -> (String, String);

    /// Appends new, anonymous, frame
    ///
    /// Anonymous means that the frame does not have a name.
    fn frame(self) -> Result<T>;

    /// Appends new frame
    ///
    /// # Arguments
    ///
    /// * `f` - A function which must return frame name
    fn frame_with<F>(self, f: F) -> Result<T>
    where
        F: FnOnce() -> String;

    /// Appends new frame
    ///
    /// # Arguments
    ///
    /// * `name` - A frame name
    fn frame_with_name<N>(self, name: N) -> Result<T>
    where
        N: Into<Display>;
}

impl<T> ResultExt<T> for Result<T> {
    fn context<K, V>(self, k: K, v: V) -> Result<T>
    where
        K: Into<Display>,
        V: Into<Display>,
    {
        self.map_err(|e| e.context(k, v))
    }

    fn context_with<F>(self, f: F) -> Result<T>
    where
        F: FnOnce() -> (String, String),
    {
        self.map_err(|e| {
            let (k, v) = f();
            e.context(k, v)
        })
    }

    fn frame(self) -> Result<T> {
        self.map_err(|e| e.frame())
    }

    fn frame_with<F>(self, f: F) -> Result<T>
    where
        F: FnOnce() -> String,
    {
        self.map_err(|e| e.frame_with_name(f()))
    }

    fn frame_with_name<N>(self, name: N) -> Result<T>
    where
        N: Into<Display>,
    {
        self.map_err(|e| e.frame_with_name(name))
    }
}

/// Error type
pub struct Error {
    // Box is not really required here, but we'd like to keep
    // Result as small as possible. Inner can be very huge
    // sometimes.
    inner: Box<Inner>,
}

impl Error {
    /// Creates new error with message
    ///
    /// # Arguments
    ///
    /// * `message` - An error message
    pub fn with_message<M>(message: M) -> Error
    where
        M: Into<Display>,
    {
        let inner = Inner::new(message);
        Error { inner: Box::new(inner) }
    }

    /// Appends key, value pair to context of the last frame
    ///
    /// # Arguments
    ///
    /// * `k` - A key
    /// * `v` - A value
    pub fn context<K, V>(mut self, k: K, v: V) -> Error
    where
        K: Into<Display>,
        V: Into<Display>,
    {
        self.inner
            .frames
            .last_mut()
            .expect("Inner must contain at least one frame")
            .push(k, v);
        self
    }

    /// Appends new, anonymous, frame
    ///
    /// Anonymous means that the frame does not have a name.
    pub fn frame(mut self) -> Error {
        let frame = Frame::new();
        self.inner.frames.push(frame);
        self
    }

    /// Appends new frame
    ///
    /// # Arguments
    ///
    /// * `name` - A frame name
    pub fn frame_with_name<N>(mut self, name: N) -> Error
    where
        N: Into<Display>,
    {
        let frame = Frame::with_name(name);
        self.inner.frames.push(frame);
        self
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        writeln!(f, "temen: {}", self.inner.message)?;

        if self.inner.frames.is_empty() {
            return Ok(());
        }

        let last_frame_idx = self.inner.frames.len() - 1;
        for (frame_idx, frame) in self.inner.frames.iter().enumerate() {
            let context_indent: &str;
            let frame_indent: &str;

            if last_frame_idx == frame_idx {
                frame_indent = " └";
                context_indent = "   ";
            } else {
                frame_indent = " ├";
                context_indent = " | ";
            }

            write!(f, "{} frame[{}]", frame_indent, frame_idx)?;
            if frame.name.is_some() {
                writeln!(f, ": {}", frame.name.as_ref().unwrap())?;
            } else {
                writeln!(f)?;
            }

            if !frame.context.is_empty() {
                writeln!(f, "{} └ context:", context_indent)?;
                let last_index = frame.context().len() - 1;
                for (idx, (k, v)) in frame.context().iter().enumerate() {
                    if idx == last_index {
                        writeln!(f, "{}    └ {}: {}", context_indent, k, v)?;
                    } else {
                        writeln!(f, "{}    ├ {}: {}", context_indent, k, v)?;
                    }
                }
            }
        }
        Ok(())
    }
}

impl fmt::Debug for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(self, f)
    }
}

impl error::Error for Error {
    fn source(&self) -> Option<&(error::Error + 'static)> {
        None
    }
}

struct Inner {
    message: Display,
    frames: Vec<Frame>,
}

impl Inner {
    fn new<M>(message: M) -> Inner
    where
        M: Into<Display>,
    {
        Inner {
            message: message.into(),
            frames: vec![Frame::new()],
        }
    }
}

struct Frame {
    name: Option<Display>,
    context: Vec<(Display, Display)>,
}

impl Frame {
    fn new() -> Frame {
        Frame {
            name: None,
            context: vec![],
        }
    }

    fn with_name<N>(name: N) -> Frame
    where
        N: Into<Display>,
    {
        Frame {
            name: Some(name.into()),
            context: vec![],
        }
    }

    fn push<K, V>(&mut self, k: K, v: V)
    where
        K: Into<Display>,
        V: Into<Display>,
    {
        self.context.push((k.into(), v.into()))
    }

    fn context(&self) -> &[(Display, Display)] {
        self.context.as_ref()
    }
}