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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
//! This crate provides functionalities to
//! define [trackable](trait.Trackable.html) objects and track those.
//!
//! Below is an example that tracks failure of an I/O operation:
//!
//! ```no_run
//! #[macro_use]
//! extern crate trackable;
//!
//! use trackable::error::Failure;
//!
//! fn foo() -> Result<(), Failure> {
//!     track!(std::fs::File::open("/path/to/non_existent_file").map_err(Failure::from_error))?;
//!     Ok(())
//! }
//! fn bar() -> Result<(), Failure> {
//!     track!(foo())?;
//!     Ok(())
//! }
//! fn baz() -> Result<(), Failure> {
//!     track!(bar())?;
//!     Ok(())
//! }
//!
//! fn main() {
//!     let result = baz();
//!     assert!(result.is_err());
//!
//!     let error = result.err().unwrap();
//!     assert_eq!(format!("\r{}", error).replace('\\', "/"), r#"
//! Failed (cause; No such file or directory)
//! HISTORY:
//!   [0] at src/lib.rs:7
//!   [1] at src/lib.rs:12
//!   [2] at src/lib.rs:16
//! "#);
//! }
//! ```
//!
//! This example used the built-in `Failure` type,
//! but you can easily define your own trackable error types.
//! See the documentaion of [error](error/index.html) module for more details.
#![warn(missing_docs)]

#[cfg(feature = "serialize")]
extern crate serde;
#[cfg(feature = "serialize")]
#[macro_use]
extern crate serde_derive;

use std::borrow::Cow;
use std::fmt;

#[macro_use]
mod macros;

pub mod error;

/// This trait allows to track an instance of an implementation type.
///
/// A trackable instance can have a tracking history that manages own backtrace-like (but more general)
/// [history](struct.History.html) for tracking.
///
/// You can add entries to the history by calling tracking macros(e.g., [track!](macro.track.html)).
///
/// See [`TrackableError`](error/struct.TrackableError.html) as a typical implementaion of this trait.
///
/// # Examples
///
/// Defines a trackable type.
///
/// ```
/// #[macro_use]
/// extern crate trackable;
///
/// use trackable::{Trackable, History, Location};
///
/// #[derive(Default)]
/// struct TrackableObject {
///     history: History<Location>,
/// }
/// impl Trackable for TrackableObject {
///     type Event = Location;
///     fn history(&self) -> Option<&History<Self::Event>> {
///         Some(&self.history)
///     }
///     fn history_mut(&mut self) -> Option<&mut History<Self::Event>> {
///         Some(&mut self.history)
///     }
/// }
///
/// fn main() {
///     let o = TrackableObject::default();
///     let o = track!(o);
///     let o = track!(o, "Hello");
///     let o = track!(o, "Hello {}", "World!");
///
///     assert_eq!(format!("\n{}", o.history).replace('\\', "/"), r#"
/// HISTORY:
///   [0] at src/lib.rs:23
///   [1] at src/lib.rs:24 -- Hello
///   [2] at src/lib.rs:25 -- Hello World!
/// "#);
/// }
/// ```
pub trait Trackable {
    /// Event type which a history of an instance of this type can have.
    type Event: From<Location>;

    /// Add an event into the tail of the history of this instance.
    ///
    /// Typically, this is called via [track!](macro.track.html) macro.
    #[inline]
    fn track<F>(&mut self, f: F)
    where
        F: FnOnce() -> Self::Event,
    {
        self.history_mut().map(|h| h.add(f()));
    }

    /// Returns `true` if it is being tracked, otherwise `false`.
    #[inline]
    fn in_tracking(&self) -> bool {
        self.history().is_some()
    }

    /// Returns the reference of the tracking history of this instance.
    ///
    /// If it is not being tracked, this will return `None.
    fn history(&self) -> Option<&History<Self::Event>>;

    /// Returns the mutable reference of the tracking history of this instance.
    ///
    /// If it is not being tracked, this will return `None.
    fn history_mut(&mut self) -> Option<&mut History<Self::Event>>;
}
impl<T: Trackable> Trackable for Option<T> {
    type Event = T::Event;

    #[inline]
    fn history(&self) -> Option<&History<Self::Event>> {
        self.as_ref().and_then(|t| t.history())
    }

    #[inline]
    fn history_mut(&mut self) -> Option<&mut History<Self::Event>> {
        self.as_mut().and_then(|t| t.history_mut())
    }
}
impl<T, E: Trackable> Trackable for Result<T, E> {
    type Event = E::Event;

    #[inline]
    fn history(&self) -> Option<&History<Self::Event>> {
        self.as_ref().err().and_then(|t| t.history())
    }

    #[inline]
    fn history_mut(&mut self) -> Option<&mut History<Self::Event>> {
        self.as_mut().err().and_then(|t| t.history_mut())
    }
}

/// The tracking history of a target.
///
/// A history is a sequence of the tracked events.
///
/// # Examples
///
/// ```
/// use std::fmt::{Display, Formatter, Result};
/// use trackable::History;
///
/// struct Event(&'static str);
/// impl Display for Event {
///     fn fmt(&self, f: &mut Formatter) -> Result {
///         write!(f, "event: {}", self.0)
///     }
/// }
///
/// let mut history = History::new();
/// history.add(Event("foo"));
/// history.add(Event("bar"));
///
/// assert_eq!(format!("\n{}", history), r#"
/// HISTORY:
///   [0] event: foo
///   [1] event: bar
/// "#);
/// ```
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct History<Event>(Vec<Event>);
impl<Event> History<Event> {
    /// Makes an empty history.
    #[inline]
    pub fn new() -> Self {
        History(Vec::new())
    }

    /// Adds an event to the tail of this history.
    #[inline]
    pub fn add(&mut self, event: Event) {
        self.0.push(event);
    }

    /// Returns the tracked events in this history.
    #[inline]
    pub fn events(&self) -> &[Event] {
        &self.0[..]
    }
}
impl<Event: fmt::Display> fmt::Display for History<Event> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        writeln!(f, "HISTORY:")?;
        for (i, e) in self.events().iter().enumerate() {
            writeln!(f, "  [{}] {}", i, e)?;
        }
        Ok(())
    }
}
impl<Event> Default for History<Event> {
    #[inline]
    fn default() -> Self {
        History::new()
    }
}

/// The location of interest in source code files.
///
/// Typically this is created in the macros which defined in this crate.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct Location {
    module_path: Cow<'static, str>,
    file: Cow<'static, str>,
    line: u32,
    message: Cow<'static, str>,
}
impl Location {
    /// Makes a new `Location` instance.
    ///
    /// # Examples
    ///
    /// ```
    /// use trackable::Location;
    ///
    /// let location = Location::new(module_path!(), file!(), line!(), "Hello".to_string());
    /// assert_eq!(location.message(), "Hello");
    /// ```
    #[inline]
    pub fn new<T>(module_path: &'static str, file: &'static str, line: u32, message: T) -> Self
    where
        T: Into<Cow<'static, str>>,
    {
        Location {
            module_path: Cow::Borrowed(module_path),
            file: Cow::Borrowed(file),
            line,
            message: message.into(),
        }
    }

    /// Gets the crate name of this location.
    #[inline]
    pub fn crate_name(&self) -> &str {
        if let Some(module_path_end) = self.module_path.find(':') {
            &self.module_path[..module_path_end]
        } else {
            self.module_path.as_ref()
        }
    }

    /// Gets the module path of this location.
    #[inline]
    pub fn module_path(&self) -> &str {
        self.module_path.as_ref()
    }

    /// Gets the file name of this location.
    #[inline]
    pub fn file(&self) -> &str {
        self.file.as_ref()
    }

    /// Gets the line of this location.
    #[inline]
    pub fn line(&self) -> u32 {
        self.line
    }

    /// Gets the message left at this location.
    #[inline]
    pub fn message(&self) -> &str {
        self.message.as_ref()
    }
}
impl fmt::Display for Location {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "at {}:{}", self.file(), self.line())?;
        if !self.message().is_empty() {
            write!(f, " -- {}", self.message())?;
        }
        Ok(())
    }
}

#[cfg(test)]
mod test {
    use error::Failure;
    use super::*;

    #[test]
    fn it_works() {
        fn foo() -> Result<(), Failure> {
            track!(
                std::fs::File::open("/path/to/non_existent_file")
                    .map_err(|e| Failure::from_error(format!("{:?}", e.kind())),)
            )?;
            Ok(())
        }
        fn bar() -> Result<(), Failure> {
            track!(foo())?;
            Ok(())
        }
        fn baz() -> Result<(), Failure> {
            track!(bar())?;
            Ok(())
        }

        let result = baz();
        assert!(result.is_err());

        let error = result.err().unwrap();
        assert_eq!(
            format!("\n{}", error).replace('\\', "/"),
            r#"
Failed (cause; NotFound)
HISTORY:
  [0] at src/lib.rs:316
  [1] at src/lib.rs:323
  [2] at src/lib.rs:327
"#
        );
    }
}