| 1 | use std::fs::File; |
| 2 | use std::io::{BufRead, BufReader}; |
| 3 | use std::path::Path; |
| 4 | |
| 5 | use crate::sudoers::Span; |
| 6 | |
| 7 | pub(crate) fn cited_error(message: &str, span: Span, path: impl AsRef<Path>) { |
| 8 | let path_str = path.as_ref().display(); |
| 9 | let Span { |
| 10 | start: (line, col), |
| 11 | end: (end_line, mut end_col), |
| 12 | } = span; |
| 13 | eprintln_ignore_io_error!("{path_str}:{line}:{col}: {message}"); |
| 14 | |
| 15 | // we won't try to "span" errors across multiple lines |
| 16 | if line != end_line { |
| 17 | end_col = col; |
| 18 | } |
| 19 | |
| 20 | let citation = || { |
| 21 | let inp = BufReader::new(File::open(path).ok()?); |
| 22 | let line = inp.lines().nth(line - 1)?.ok()?; |
| 23 | let padding = line |
| 24 | .chars() |
| 25 | .take(col - 1) |
| 26 | .map(|c| if c.is_whitespace() { c } else { ' ' }) |
| 27 | .collect::<String>(); |
| 28 | let lineunder = std::iter::repeat_n('~', end_col - col) |
| 29 | .skip(1) |
| 30 | .collect::<String>(); |
| 31 | eprintln_ignore_io_error!("{line}"); |
| 32 | eprintln_ignore_io_error!("{padding}^{lineunder}"); |
| 33 | Some(()) |
| 34 | }; |
| 35 | |
| 36 | // we ignore any errors in displaying an error |
| 37 | let _ = citation(); |
| 38 | } |
| 39 | |
| 40 | macro_rules! diagnostic { |
| 41 | ($str:expr, $path:tt @ $pos:ident) => { |
| 42 | if let Some(range) = $pos { |
| 43 | $crate::sudo::diagnostic::cited_error(&format!($str), range, $path); |
| 44 | } else { |
| 45 | for line in format!($str).split('\n') { |
| 46 | eprintln_ignore_io_error!("sudo: {}", line); |
| 47 | } |
| 48 | } |
| 49 | }; |
| 50 | ($str:expr) => {{ |
| 51 | for line in format!($str).split('\n') { |
| 52 | eprintln_ignore_io_error!("sudo: {}", line); |
| 53 | } |
| 54 | }}; |
| 55 | } |
| 56 | |
| 57 | pub(crate) use diagnostic; |