barrierlab-cli 0.1.0

Accessibility audit of a web page from its source, without a browser.
//! Optional scoring and CI gate over a report (`audit-score`).
//!
//! Score and coverage are kept apart everywhere they are shown: a high score
//! with low coverage means "little was checked", not "all is well".

use a11y_report::Report;
use audit_score::{GateDecision, GatePolicy, GateResult, ScoreResult, ScoringProfile};

/// `--score` / `--gate` / `--gate-policy`, shared by the page audit and
/// `barrierlab visual`.
#[derive(Default)]
pub struct Options {
    profile: Option<ScoringProfile>,
    gate: Option<GatePolicy>,
    gate_requested: bool,
}

pub struct Scoring {
    pub result: ScoreResult,
    pub gate: Option<GateResult>,
}

impl Options {
    /// Consumes `arg` (and its value) if it is one of the scoring flags.
    pub fn take(
        &mut self,
        arg: &str,
        args: &mut impl Iterator<Item = String>,
    ) -> Result<bool, String> {
        match arg {
            "--score" => {
                let v = args.next().ok_or("--score needs a value")?;
                self.profile = Some(match v.as_str() {
                    "wcag-strict" => ScoringProfile::wcag_strict(),
                    "balanced" => ScoringProfile::balanced(),
                    "visual-focus" => ScoringProfile::visual_focus(),
                    _ => {
                        return Err(format!(
                            "--score {v}: expected wcag-strict, balanced or visual-focus"
                        ));
                    }
                });
            }
            "--gate" => self.gate_requested = true,
            "--gate-policy" => {
                let path = args.next().ok_or("--gate-policy needs a value")?;
                let text = std::fs::read_to_string(&path)
                    .map_err(|e| format!("--gate-policy {path}: {e}"))?;
                self.gate = Some(
                    serde_json::from_str(&text)
                        .map_err(|e| format!("--gate-policy {path}: {e}"))?,
                );
            }
            _ => return Ok(false),
        }
        Ok(true)
    }

    /// `None` when neither scoring nor a gate was asked for. A gate without a
    /// profile uses `balanced`; without a policy, `GatePolicy::default()`.
    pub fn evaluate(&self, report: &Report) -> Option<Scoring> {
        let gated = self.gate_requested || self.gate.is_some();
        if self.profile.is_none() && !gated {
            return None;
        }
        let profile = self.profile.clone().unwrap_or_default();
        if gated {
            let policy = self.gate.clone().unwrap_or_default();
            let (result, gate) = audit_score::evaluate_gate(report, &profile, &policy);
            Some(Scoring {
                result,
                gate: Some(gate),
            })
        } else {
            Some(Scoring {
                result: audit_score::evaluate(report, &profile),
                gate: None,
            })
        }
    }
}

impl Scoring {
    pub fn gate_failed(&self) -> bool {
        self.gate
            .as_ref()
            .is_some_and(|g| g.decision == GateDecision::Fail)
    }
}