blade-cli 0.1.0

Fast, Node-free linter for Laravel Blade templates
//! `blade.toml`:
//!
//! ```toml
//! [lint.rules]
//! raw-echo = "off"   # "error" | "warning" | "off"
//! ```

use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};

use blade_lint::{Config, Level};
use serde::Deserialize;

#[derive(Deserialize, Default)]
#[serde(deny_unknown_fields)]
struct File {
    #[serde(default)]
    lint: LintSection,
}

#[derive(Deserialize, Default)]
#[serde(deny_unknown_fields)]
struct LintSection {
    #[serde(default)]
    rules: BTreeMap<String, String>,
}

/// Loads `explicit` (which must exist), or `./blade.toml` if there is one, or the
/// defaults.
pub fn load(explicit: Option<&Path>) -> Result<Config, String> {
    let path = match explicit {
        Some(path) => path.to_path_buf(),
        None => {
            let path = PathBuf::from("blade.toml");
            if !path.is_file() {
                return Ok(Config::default());
            }
            path
        }
    };
    let shown = path.display();
    let text = fs::read_to_string(&path).map_err(|e| format!("{shown}: {e}"))?;
    let file: File = toml::from_str(&text).map_err(|e| format!("{shown}: {e}"))?;

    let mut config = Config::default();
    for (rule, level) in &file.lint.rules {
        let level: Level = level
            .parse()
            .map_err(|e| format!("{shown}: [lint.rules] {rule}: {e}"))?;
        config
            .set(rule, level)
            .map_err(|e| format!("{shown}: [lint.rules]: {e}"))?;
    }
    Ok(config)
}