use a11y_report::Report;
use audit_score::{GateDecision, GatePolicy, GateResult, ScoreResult, ScoringProfile};
#[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 {
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)
}
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)
}
}