barrierlab-cli 0.1.0

Accessibility audit of a web page from its source, without a browser.
//! Text output through runemark: verdict, counts, findings by outcome.

use crate::score::Scoring;
use a11y_report::{NotRun, Outcome, Report};
use audit_score::{GateCheck, GateDecision};
use runemark::{
    ColorMode, Console, DetailLevel, Finding, FindingGroup, Metric, RenderOptions, Report as View,
    ScopeNote, Tone, Verdict,
};

pub fn print(target: &str, report: &Report, scoring: Option<&Scoring>) {
    let s = &report.summary;
    let verdict = if s.fail > 0 {
        Verdict::Failed
    } else if s.review > 0 {
        Verdict::Warning
    } else {
        Verdict::Passed
    };
    let mut view = View::new(format!("barrierlab {target}"), verdict)
        .with_detail_level(DetailLevel::Detailed)
        .add_metric(Metric::new("Fail", s.fail.to_string()))
        .add_metric(Metric::new("Review", s.review.to_string()))
        .add_metric(Metric::new("Untested", s.untested.to_string()));
    if let Some(sc) = scoring {
        // Two separate numbers on purpose: coverage says how much of the rule
        // set could run at all.
        view = view
            .add_metric(Metric::new("Score", format!("{:.1}", sc.result.score)))
            .add_metric(Metric::new(
                "Coverage",
                format!("{:.0}%", sc.result.coverage * 100.0),
            ));
        if let Some(gate) = &sc.gate {
            let mut lines = vec![
                match gate.decision {
                    GateDecision::Pass => "pass",
                    GateDecision::Warn => "warn",
                    GateDecision::Fail => "fail",
                }
                .to_string(),
            ];
            for r in &gate.reasons {
                let check = match r.check {
                    GateCheck::Score => "score",
                    GateCheck::Coverage => "coverage",
                    GateCheck::BlockingFails => "blocking fails",
                };
                lines.push(format!(
                    "{:?} {check}: {} (threshold {})",
                    r.level, r.actual, r.threshold
                ));
            }
            view = view.add_scope_note(ScopeNote::new("Gate", lines));
        }
    }
    // Rules with nothing to check on this page are not "missing data": count
    // them apart from the ones that could not run.
    let count = |reason: NotRun| {
        report
            .rule_runs
            .iter()
            .filter(|r| r.not_run == Some(reason))
            .count()
    };
    let mut lines = Vec::new();
    let missing = count(NotRun::CapabilityMissing);
    if missing > 0 {
        lines.push(format!(
            "{missing} rule(s) need data this run did not provide (rendered styles, geometry, paint order or a baseline)"
        ));
    }
    let errored = count(NotRun::Errored);
    if errored > 0 {
        lines.push(format!("{errored} rule(s) failed to run"));
    }
    let skipped = count(NotRun::NotApplicable);
    if skipped > 0 {
        lines.push(format!(
            "{skipped} rule(s) found nothing to check here (not applicable)"
        ));
    }
    if !lines.is_empty() {
        view = view.add_scope_note(ScopeNote::new("Not run", lines));
    }
    if !report.inputs.is_empty() {
        let lines = report
            .inputs
            .iter()
            .map(|i| {
                let subject = i.subject.as_deref().unwrap_or("-");
                let detail = i.detail.as_deref().unwrap_or("");
                format!("{subject}: {detail}")
            })
            .collect();
        view = view.add_scope_note(ScopeNote::new(
            "Incomplete input (affected checks are untested, not passed)",
            lines,
        ));
    }
    for (outcome, title, tone, advisory) in [
        (Outcome::Fail, "Failed", Tone::Error, false),
        (Outcome::Review, "Needs review", Tone::Warning, false),
        (Outcome::Untested, "Check by hand", Tone::Muted, true),
    ] {
        let mut group = FindingGroup::new(title).with_advisory(advisory);
        for f in report.findings.iter().filter(|f| f.outcome == outcome) {
            group = group.add_finding(Finding::new(tone, &f.message).with_rule_id(&f.rule_id));
        }
        if !group.findings.is_empty() {
            view = view.add_group(group);
        }
    }
    // Width from COLUMNS (shells do not export it to child processes; set it
    // yourself for a fixed width, e.g. for snapshots).
    let width = std::env::var("COLUMNS")
        .ok()
        .and_then(|c| c.parse::<usize>().ok())
        .unwrap_or(0);
    let options = RenderOptions::new().with_width(width);
    print!(
        "{}",
        view.render_with_options(Console::stdout(ColorMode::Auto), options)
    );
}

/// The report as pretty JSON, every finding with its stable `id` first
/// (`Finding::id()`, which the model computes but does not store).
pub fn json(report: &Report, scoring: Option<&Scoring>) -> String {
    let mut value = serde_json::to_value(report).expect("serialize");
    if let Some(findings) = value["findings"].as_array_mut() {
        for (entry, finding) in findings.iter_mut().zip(&report.findings) {
            let serde_json::Value::Object(fields) = entry.take() else {
                unreachable!("a finding serialises as an object")
            };
            let mut with_id = serde_json::Map::new();
            with_id.insert("id".into(), finding.id().as_str().into());
            with_id.extend(fields);
            *entry = serde_json::Value::Object(with_id);
        }
    }
    if let Some(sc) = scoring {
        value["score"] = serde_json::to_value(&sc.result).expect("serialize");
        if let Some(gate) = &sc.gate {
            value["gate"] = serde_json::to_value(gate).expect("serialize");
        }
    }
    serde_json::to_string_pretty(&value).expect("serialize")
}