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
//! A magical type for displaying source file errors
//!
//! # example
//!
//! ```rust
//! use source_error::{from_file, Position};
//! use std::error::Error;
//!
//! fn main() -> Result<(), Box<dyn Error>> {
//!     println!(
//!       "{}",
//!       from_file("whoopsie!", "tests/source.json", Position::new(3, 4))?
//!     );
//!     Ok(())
//! }
//! ```
use colored::Colorize;
use std::{
    error::Error as StdError,
    fmt, io,
    ops::RangeInclusive,
    path::{Path, PathBuf},
};

/// Line and column coordinates
#[derive(Debug)]
pub struct Position {
    line: usize,
    col: usize,
}

impl Position {
    /// Return's a new `Position` given a line and column number
    /// These should be 1-based
    pub fn new(
        line: usize,
        col: usize,
    ) -> Position {
        Position { line, col }
    }
}

/// An `Error` type targetting errors tied to source file contents
///
/// Most of the utility of this type is in its implementation of `Display` which
/// renders the error next along with the relative line of code
pub struct Error<S> {
    message: String,
    path: PathBuf,
    lines: S,
    position: Position,
}

impl<S> fmt::Debug for Error<S> {
    fn fmt(
        &self,
        f: &mut fmt::Formatter<'_>,
    ) -> fmt::Result {
        f.debug_struct("Error")
            .field("message", &self.message)
            .field("path", &self.path.display())
            .field("position", &self.position)
            .finish()
    }
}

/// Creates an `Error` with a message and path to source file a
/// along with the relative position of the error
///
/// Positions should be  1-based to align with what people see in their
/// source file editors
pub fn from_file<M, P>(
    message: M,
    path: P,
    position: Position,
) -> io::Result<Error<String>>
where
    P: AsRef<Path>,
    M: AsRef<str>,
{
    Ok(from_lines(
        message,
        path.as_ref(),
        std::fs::read_to_string(path.as_ref())?,
        position,
    ))
}

/// Creates an `Error` with a message, path to source file a
/// and source lines along with the relative position of the error
///
/// Positions are 1 based to align with what people see in their
/// source file editors
pub fn from_lines<M, P, S>(
    message: M,
    path: P,
    lines: S,
    position: Position,
) -> Error<S>
where
    M: AsRef<str>,
    P: AsRef<Path>,
    S: AsRef<str>,
{
    Error {
        message: message.as_ref().into(),
        path: path.as_ref().into(),
        lines,
        position,
    }
}

fn line_range(line: usize) -> RangeInclusive<usize> {
    line.checked_sub(2).unwrap_or_default()..=line.checked_add(2).unwrap_or(std::usize::MAX)
}

/// Creates a colorized display of error information
///
/// You can disable color by exporting the `NO_COLOR` environment variable
/// to anything but "0"
impl<S> fmt::Display for Error<S>
where
    S: AsRef<str>,
{
    fn fmt(
        &self,
        f: &mut fmt::Formatter<'_>,
    ) -> fmt::Result {
        let Self {
            message,
            path,
            lines,
            position,
        } = self;
        let Position { line, col } = position;
        let line_range = line_range(*line);
        writeln!(f, "⚠️ {}\n", format!("error: {}", message).red())?;
        writeln!(
            f,
            "   {}\n",
            format!("at {}:{}:{}", path.display(), line, col).dimmed()
        )?;
        let lines = lines
            .as_ref()
            .lines()
            .enumerate()
            .filter_map(|(idx, line)| {
                let line_idx = idx + 1;
                if line_range.contains(&line_idx) {
                    Some((line_idx, line))
                } else {
                    None
                }
            })
            .collect::<Vec<_>>();
        let max_line = lines
            .last()
            .map(|(idx, _)| idx.to_string().len())
            .unwrap_or_default();
        for (idx, matched) in lines {
            if idx == *line {
                write!(f, "{} ", ">".red())?;
            } else {
                f.write_str("  ")?;
            }
            writeln!(
                f,
                " {}{}",
                format!("{}{} |", " ".repeat(max_line - idx.to_string().len()), idx).dimmed(),
                matched
            )?;
        }
        Ok(())
    }
}

impl<S> StdError for Error<S> where S: AsRef<str> {}

#[cfg(test)]
mod tests {
    use super::*;
    use pretty_assertions::assert_eq;
    use std::env;

    #[test]
    fn it_impl_error() {
        fn is<E>(_: E)
        where
            E: StdError,
        {
        }
        is(from_lines("..", "...", "", Position::new(1, 1)))
    }

    #[test]
    fn it_works() {
        env::set_var("NO_COLOR", "");
        let expected = include_str!("../tests/expect.txt");
        let err = from_lines(
            "something is definitely wrong here",
            "../tests/source.json",
            include_str!("../tests/source.json"),
            Position::new(3, 4),
        );
        assert_eq!(format!("{}", err), expected)
    }

    #[test]
    fn line_range_is_expected() {
        for (given, expect) in &[
            (1, (0, 3)),
            (2, (0, 4)),
            (3, (1, 5)),
            (std::usize::MAX, (std::usize::MAX - 2, std::usize::MAX)),
        ] {
            let (start, end) = expect;
            let range = line_range(*given);
            assert_eq!(start, range.start());
            assert_eq!(end, range.end());
        }
    }
}