blade-cli 0.1.0

Fast, Node-free linter for Laravel Blade templates
//! Printing lint results.

use std::io::{self, Write};

use blade_lint::{Diagnostic, LineIndex, Severity};

/// One linted file.
pub struct Report {
    /// As shown in output (see `files::display`).
    pub path: String,
    pub text: String,
    pub diagnostics: Vec<Diagnostic>,
}

/// For people: each finding with the source line and carets under it, then a summary.
///
/// ```text
/// views/a.blade.php:1:1: error[syntax]: unclosed @if: expected @endif
///   |
/// 1 | @if($a)
///   | ^^^
/// ```
pub fn human(reports: &[Report], out: &mut impl Write) -> io::Result<()> {
    for report in reports {
        let text = &report.text;
        let index = LineIndex::new(text);
        for d in &report.diagnostics {
            let (line, col) = index.line_col(text, d.range.start());
            let (end_line, end_col) = index.line_col(text, d.range.end());
            writeln!(
                out,
                "{}:{line}:{col}: {}[{}]: {}",
                report.path, d.severity, d.rule, d.message
            )?;
            let source = index.line_text(text, line);
            let carets = if end_line == line {
                end_col.saturating_sub(col)
            } else {
                (source.chars().count() as u32 + 1).saturating_sub(col)
            }
            .max(1);
            // Copy tabs so the carets line up however wide the terminal draws a tab.
            let indent: String = source
                .chars()
                .take(col as usize - 1)
                .map(|c| if c == '\t' { '\t' } else { ' ' })
                .collect();
            let width = line.to_string().len();
            writeln!(out, "{:width$} |", "")?;
            writeln!(out, "{line} | {source}")?;
            writeln!(
                out,
                "{:width$} | {indent}{}",
                "",
                "^".repeat(carets as usize)
            )?;
            writeln!(out)?;
        }
    }
    writeln!(out, "{}", summary(reports))
}

/// For tools: one JSON object on one line.
///
/// `{"diagnostics":[{"path","rule","severity","message","line","column","end_line",
/// "end_column"}],"summary":{"files","errors","warnings"}}`
pub fn json(reports: &[Report], out: &mut impl Write) -> io::Result<()> {
    let mut diagnostics = Vec::new();
    for report in reports {
        let index = LineIndex::new(&report.text);
        for d in &report.diagnostics {
            let (line, column) = index.line_col(&report.text, d.range.start());
            let (end_line, end_column) = index.line_col(&report.text, d.range.end());
            diagnostics.push(serde_json::json!({
                "path": report.path,
                "rule": d.rule,
                "severity": d.severity.to_string(),
                "message": d.message,
                "line": line,
                "column": column,
                "end_line": end_line,
                "end_column": end_column,
            }));
        }
    }
    let value = serde_json::json!({
        "diagnostics": diagnostics,
        "summary": {
            "files": reports.len(),
            "errors": count(reports, Severity::Error),
            "warnings": count(reports, Severity::Warning),
        },
    });
    writeln!(out, "{value}")
}

/// For GitHub Actions: workflow commands that show up as annotations on the PR diff.
/// <https://docs.github.com/actions/reference/workflow-commands-for-github-actions>
pub fn github(reports: &[Report], out: &mut impl Write) -> io::Result<()> {
    for report in reports {
        let index = LineIndex::new(&report.text);
        for d in &report.diagnostics {
            let (line, col) = index.line_col(&report.text, d.range.start());
            let (end_line, end_col) = index.line_col(&report.text, d.range.end());
            let command = match d.severity {
                Severity::Error => "error",
                Severity::Warning => "warning",
            };
            writeln!(
                out,
                "::{command} file={},line={line},col={col},endLine={end_line},endColumn={end_col},title={}::{}",
                escape_property(&report.path),
                escape_property(&format!("blade lint ({})", d.rule)),
                escape_data(&d.message),
            )?;
        }
    }
    Ok(())
}

/// Escapes a workflow command's message.
fn escape_data(s: &str) -> String {
    s.replace('%', "%25")
        .replace('\r', "%0D")
        .replace('\n', "%0A")
}

/// Escapes a workflow command's property value, where `:` and `,` are separators.
fn escape_property(s: &str) -> String {
    escape_data(s).replace(':', "%3A").replace(',', "%2C")
}

fn count(reports: &[Report], severity: Severity) -> usize {
    reports
        .iter()
        .flat_map(|r| &r.diagnostics)
        .filter(|d| d.severity == severity)
        .count()
}

/// `2 errors and 1 warning in 3 files`, or `no problems in 3 files`.
fn summary(reports: &[Report]) -> String {
    let (errors, warnings) = (
        count(reports, Severity::Error),
        count(reports, Severity::Warning),
    );
    let files = plural(reports.len(), "file");
    let mut found = Vec::new();
    if errors > 0 {
        found.push(plural(errors, "error"));
    }
    if warnings > 0 {
        found.push(plural(warnings, "warning"));
    }
    if found.is_empty() {
        format!("no problems in {files}")
    } else {
        format!("{} in {files}", found.join(" and "))
    }
}

fn plural(n: usize, word: &str) -> String {
    if n == 1 {
        format!("1 {word}")
    } else {
        format!("{n} {word}s")
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn github_escapes() {
        assert_eq!(escape_property("a:b,c%"), "a%3Ab%2Cc%25");
        assert_eq!(escape_data("x\ny%\r"), "x%0Ay%25%0D");
    }
}