1use annotate_snippets::{Level, Snippet, AnnotationKind, Renderer};
2
3#[non_exhaustive]
4#[derive(Debug)]
5pub enum GpError {
6 Any(String),
7 Unknown(String),
8}
9
10impl GpError {
11 pub fn from_stderr(stderr: String) -> Self {
12 if let Some(err) = Self::checked_from_stderr(&stderr) {
13 err
14 } else {
15 Self::Unknown(stderr)
16 }
17 }
18
19 fn checked_from_stderr(stderr: &str) -> Option<Self> {
20 let raw = raw_error(stderr)?;
21
22 Some(Self::Any(raw.join("\n")))
23 }
24
25 pub fn pretty(&self, location: &str) -> String {
26 let (message, snippet) = match self {
27 Self::Any(snippet) => ("gp execution failed", snippet),
28 Self::Unknown(snippet) => ("gp execution failed with unknown error", snippet),
29 };
30
31 let snippet = Level::ERROR.primary_title(format!("{message} at {location}")).element({
32 Snippet::source(snippet).annotation(AnnotationKind::Visible.span(0..snippet.len()))
33 });
34
35 Renderer::styled().anonymized_line_numbers(true).render(&[snippet]).to_string()
36 }
37}
38
39fn raw_error(err: &str) -> Option<Vec<&str>> {
40 err.lines().map(|line| preceded(line)).collect()
41}
42
43fn preceded(line: &str) -> Option<&str> {
44 line.trim().strip_prefix("***")
45}