hledger_fmt/parser/
errors.rs1use crate::String;
2
3#[derive(Debug, PartialEq)]
5pub struct SyntaxError {
6 pub lineno: usize,
7 pub colno_start: usize,
8 pub colno_end: usize,
9 pub message: String,
10 pub expected: &'static str,
11}
12
13#[cfg(feature = "cli")]
15pub fn build_error_context(
16 error: &SyntaxError,
17 content: &[u8],
18 file_path_or_stdin: &crate::file_path::FilePathOrStdin,
19) -> String {
20 use std::io::{self, BufRead, Cursor};
21 let cursor = Cursor::new(content);
22 let reader = io::BufReader::new(cursor);
23 let lines = reader
24 .lines()
25 .map(|line| line.unwrap_or_default())
26 .collect::<Vec<String>>();
27 let mut context = format!(
28 "hledger-fmt error: {}:{}:{}:\n",
29 file_path_or_stdin, error.lineno, error.colno_start
30 );
31
32 let lineno_len = format!("{}", error.lineno).len();
33 if error.lineno > 1 {
34 context.push_str(&format!(
35 "{} | {}\n",
36 " ".repeat(lineno_len),
37 lines[error.lineno - 2]
38 ));
39 }
40 context.push_str(&format!("{} | {}\n", error.lineno, lines[error.lineno - 1]));
41 context.push_str(&format!(
42 "{} | {}{}\n",
43 " ".repeat(lineno_len),
44 " ".repeat(error.colno_start - 1),
45 "^".repeat(error.colno_end - error.colno_start)
46 ));
47 context.push_str(&format!("{}\nExpected {}", error.message, error.expected));
48 context
49}