use std::collections::HashMap;
use std::path::{Path, PathBuf};
use super::Verdict;
pub struct Dormant {
pub workspace: PathBuf,
pub members: usize,
pub grants: Vec<String>,
}
#[derive(Default)]
pub struct Roll {
seen: HashMap<PathBuf, (usize, HashMap<String, usize>)>,
short: bool,
}
impl Roll {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn attend(&mut self, workspace: &Path, verdict: &Verdict) {
let (members, idle) = self.seen.entry(workspace.to_path_buf()).or_default();
*members += 1;
for grant in &verdict.dormant {
*idle.entry(grant.clone()).or_default() += 1;
}
}
pub fn short(&mut self) {
self.short = true;
}
#[must_use]
pub fn dormant(&self) -> Vec<Dormant> {
if self.short {
return Vec::new();
}
let mut found: Vec<Dormant> = self
.seen
.iter()
.filter_map(|(workspace, (members, idle))| {
let mut grants: Vec<String> = idle
.iter()
.filter(|&(_, count)| count == members)
.map(|(grant, _)| grant.clone())
.collect();
grants.sort();
(!grants.is_empty()).then(|| Dormant {
workspace: workspace.clone(),
members: *members,
grants,
})
})
.collect();
found.sort_by(|a, b| a.workspace.cmp(&b.workspace));
found
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::judge::Census;
fn member(dormant: &[&str]) -> Verdict {
Verdict {
package: "member".to_owned(),
findings: Vec::new(),
ratified: Vec::new(),
stale: Vec::new(),
dormant: dormant.iter().map(|&g| g.to_owned()).collect(),
census: Census::default(),
}
}
#[test]
fn a_grant_one_member_exercises_is_not_dormant_for_the_workspace() {
let shared = Path::new("libs/kernels/kernels.zone");
let mut roll = Roll::new();
roll.attend(shared, &member(&["use ledger", "use bugle"]));
roll.attend(shared, &member(&["use bugle"]));
let found = roll.dormant();
assert_eq!(found.len(), 1, "one workspace answered");
assert_eq!(found[0].grants, ["use bugle"], "ledger was exercised by the second member");
assert_eq!(found[0].members, 2);
}
#[test]
fn every_member_leaving_it_idle_is_what_makes_it_dead() {
let shared = Path::new("kernels.zone");
let mut roll = Roll::new();
roll.attend(shared, &member(&["use bugle"]));
roll.attend(shared, &member(&["use bugle"]));
assert_eq!(roll.dormant()[0].grants, ["use bugle"]);
}
#[test]
fn a_short_roll_makes_no_claim_at_all() {
let shared = Path::new("kernels.zone");
let mut roll = Roll::new();
roll.attend(shared, &member(&["use bugle"]));
roll.short();
assert!(roll.dormant().is_empty(), "four of five members cannot convict a grant");
}
#[test]
fn two_workspaces_are_tallied_apart() {
let mut roll = Roll::new();
roll.attend(Path::new("a/a.zone"), &member(&["use one"]));
roll.attend(Path::new("b/b.zone"), &member(&["use two"]));
let found = roll.dormant();
assert_eq!(found.len(), 2);
assert_eq!(found[0].workspace, Path::new("a/a.zone"), "sorted by file");
assert_eq!(found[1].grants, ["use two"]);
}
}