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
use core::convert::Infallible;
use std::fmt::Display;
use std::panic::Location;

/// re-exports
pub use anyhow::{anyhow, bail, ensure};
pub use anyhow::{Chain, Error, Ok, Result};

pub trait Context<T, E> {
    fn context<C>(self, context: C) -> Result<T>
    where
        C: Display + Send + Sync + 'static;

    fn with_context<C, F>(self, context: F) -> Result<T>
    where
        C: Display + Send + Sync + 'static,
        F: FnOnce() -> C;

    /// like google map red dot, only record the location info without any context message.
    fn dot(self) -> Result<T>;
}

impl<T, E> Context<T, E> for Result<T, E>
where
    E: Display,
    Result<T, E>: anyhow::Context<T, E>,
{
    #[inline]
    #[track_caller]
    fn context<C>(self, context: C) -> Result<T>
    where
        C: Display + Send + Sync + 'static,
    {
        let caller = Location::caller();
        anyhow::Context::context(self, format!("{} at `{}:{}:{}`", context, caller.file(), caller.line(), caller.column()))
    }

    #[inline]
    #[track_caller]
    fn with_context<C, F>(self, context: F) -> Result<T>
    where
        C: Display + Send + Sync + 'static,
        F: FnOnce() -> C,
    {
        let caller = Location::caller();
        anyhow::Context::with_context(self, || {
            format!("{} at `{}:{}:{}`", context(), caller.file(), caller.line(), caller.column(),)
        })
    }

    #[inline]
    #[track_caller]
    fn dot(self) -> Result<T> {
        let caller = Location::caller();
        anyhow::Context::context(self, format!("at `{}:{}:{}`", caller.file(), caller.line(), caller.column()))
    }
}

impl<T> Context<T, Infallible> for Option<T>
where
    Option<T>: anyhow::Context<T, Infallible>,
{
    #[inline]
    #[track_caller]
    fn context<C>(self, context: C) -> Result<T, Error>
    where
        C: Display + Send + Sync + 'static,
    {
        let caller = Location::caller();
        anyhow::Context::context(self, format!("{} at `{}:{}:{}`", context, caller.file(), caller.line(), caller.column()))
    }

    #[inline]
    #[track_caller]
    fn with_context<C, F>(self, context: F) -> Result<T, Error>
    where
        C: Display + Send + Sync + 'static,
        F: FnOnce() -> C,
    {
        let caller = Location::caller();
        anyhow::Context::with_context(self, || {
            format!("{} at `{}:{}:{}`", context(), caller.file(), caller.line(), caller.column(),)
        })
    }

    #[inline]
    #[track_caller]
    fn dot(self) -> Result<T> {
        let caller = Location::caller();
        anyhow::Context::context(self, format!("at `{}:{}:{}`", caller.file(), caller.line(), caller.column()))
    }
}