pub fn source_snippet(
path: &std::path::Path,
line: u32,
context: u32,
token: Option<&str>,
) -> Option<String> {
let text = std::fs::read_to_string(path).ok()?;
let line = line as usize;
let first = line.saturating_sub(context as usize).max(1);
let last = line + context as usize;
let width = last.to_string().len();
let mut out = format!(" --> {}:{line}\n {:width$} |\n", path.display(), "");
let mut found = false;
for (n, content) in text.lines().enumerate().map(|(i, l)| (i + 1, l)) {
if n < first || n > last {
continue;
}
out.push_str(&format!(" {n:width$} | {content}\n"));
if n == line {
found = true;
let (prefix, caret_width) = match token
.filter(|t| !t.is_empty())
.and_then(|t| content.find(t).map(|at| (at, t)))
{
Some((at, t)) => (&content[..at], t.chars().count()),
None => {
let indent = content.len() - content.trim_start().len();
(&content[..indent], 1)
}
};
let pad: String = prefix
.chars()
.map(|c| if c == '\t' { '\t' } else { ' ' })
.collect();
let carets = "^".repeat(caret_width);
out.push_str(&format!(" {:width$} | {pad}{carets}\n", ""));
}
}
found.then_some(out)
}
pub fn message_token(message: &str) -> Option<&str> {
if let Some((_, tail)) = message.rsplit_once("near '") {
return tail.split_once('\'').map(|(token, _)| token);
}
let end = message.rfind('\'')?;
let start = message[..end].rfind('\'')?;
let token = &message[start + 1..end];
(!token.is_empty()).then_some(token)
}