scrusted-yaml 0.2.0

Validates, loads and resolves scripted-yaml files: YAML with FEEL formulas in marked keys, reloaded live.
Documentation
//! Problems: what is wrong with a file, where (SPEC 5.3).

use std::fmt;

/// How bad a problem is.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Severity {
    /// The file does not load.
    Error,
    /// The file loads; with `strict`, it does not.
    Warning,
}

impl fmt::Display for Severity {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Severity::Error => "error",
            Severity::Warning => "warning",
        })
    }
}

/// One thing wrong with a file: where it is, and what.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Problem {
    /// The name of the file.
    pub file: String,
    /// 1-based; 0 when the source was data, not text.
    pub line: u32,
    /// 1-based column.
    pub column: u32,
    /// The path of the key, as written: `stages.explore.when!`.
    pub key: String,
    /// What is wrong.
    pub message: String,
    /// Error or warning.
    pub severity: Severity,
}

impl fmt::Display for Problem {
    /// `file:line  key  message`, as scripted-yaml prints it.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut parts = Vec::with_capacity(3);
        parts.push(if self.line > 0 { format!("{}:{}", self.file, self.line) } else { self.file.clone() });
        if !self.key.is_empty() {
            parts.push(self.key.clone());
        }
        if !self.message.is_empty() {
            parts.push(self.message.clone());
        }
        f.write_str(&parts.join("  "))
    }
}

/// A place a problem can point at.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Place {
    /// The file.
    pub file: String,
    /// 1-based line, 0 for data.
    pub line: u32,
    /// 1-based column.
    pub column: u32,
    /// The path of the key.
    pub key: String,
}

/// The problems of one validation or one resolve.
#[derive(Debug, Clone, Default)]
pub struct Problems {
    /// In the order found; `sort` puts them in reading order.
    pub list: Vec<Problem>,
}

impl Problems {
    /// An error at a place.
    pub fn error(&mut self, at: &Place, message: impl Into<String>) {
        self.add(at, message, Severity::Error);
    }

    /// A warning at a place.
    pub fn warning(&mut self, at: &Place, message: impl Into<String>) {
        self.add(at, message, Severity::Warning);
    }

    /// A problem at a place.
    pub fn add(&mut self, at: &Place, message: impl Into<String>, severity: Severity) {
        self.list.push(Problem {
            file: at.file.clone(),
            line: at.line,
            column: at.column,
            key: at.key.clone(),
            message: message.into(),
            severity,
        });
    }

    /// Reading order: file by file as first met, then by line.
    pub fn sort(&mut self) {
        let mut files: Vec<String> = Vec::new();
        for p in &self.list {
            if !files.contains(&p.file) {
                files.push(p.file.clone());
            }
        }
        self.list.sort_by_key(|p| (files.iter().position(|f| *f == p.file).unwrap_or(0), p.line));
    }

    /// Makes every warning an error.
    pub fn strict(&mut self) {
        for p in &mut self.list {
            p.severity = Severity::Error;
        }
    }

    /// True when there is an error.
    pub fn failed(&self) -> bool {
        self.list.iter().any(|p| p.severity == Severity::Error)
    }
}

/// Joins the errors of a list of problems into one text, one per line.
pub fn error_text(problems: &[Problem]) -> String {
    problems.iter().filter(|p| p.severity == Severity::Error).map(|p| p.to_string()).collect::<Vec<_>>().join("\n")
}