use std::collections::{BTreeSet, HashMap};
use std::path::Path;
use crate::expect::{error_code, is_error_expect};
use crate::spec::{load_spec_dir, Row, SpecFile, SpecOptions};
use crate::{Error, Result};
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct CensusOptions {
pub col: Option<usize>,
pub name: Option<String>,
}
fn is_code_token(code: &str) -> bool {
let mut chars = code.chars();
matches!(chars.next(), Some('a'..='z'))
&& chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
}
pub fn codes_in_spec_dir(dir: impl AsRef<Path>, options: &CensusOptions) -> Result<Vec<String>> {
let mut codes = BTreeSet::new();
for spec in load_spec_dir(dir, &SpecOptions::default())? {
for row in &spec.rows {
let cell = row.col(expectation_col(&spec, row, options)?);
if !is_error_expect(cell) {
continue;
}
let code = error_code(cell)?;
if is_code_token(&code) {
codes.insert(code);
}
}
}
Ok(codes.into_iter().collect())
}
fn expectation_col(spec: &SpecFile, row: &Row, options: &CensusOptions) -> Result<usize> {
if let Some(name) = &options.name {
return row.index_of(name).ok_or_else(|| {
Error(format!(
"{}: no column named {name:?} (header: {:?})",
spec.file, spec.header
))
});
}
if let Some(col) = options.col {
return Ok(col);
}
Ok(row.cols.len().saturating_sub(1))
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct CatalogueDiff {
pub missing: Vec<String>,
pub extra: Vec<String>,
pub template_mismatch: Vec<String>,
}
pub fn compare_catalogues(
a: &HashMap<String, String>,
b: &HashMap<String, String>,
) -> CatalogueDiff {
let mut diff = CatalogueDiff::default();
for (code, template) in a {
match b.get(code) {
None => diff.missing.push(code.clone()),
Some(other) if other != template => diff.template_mismatch.push(code.clone()),
Some(_) => {}
}
}
for code in b.keys() {
if !a.contains_key(code) {
diff.extra.push(code.clone());
}
}
diff.missing.sort();
diff.extra.sort();
diff.template_mismatch.sort();
diff
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct CoverageReport {
pub uncovered: Vec<String>,
pub orphan: Vec<String>,
}
pub fn coverage(declared: &[String], exercised: &[String]) -> CoverageReport {
let declared_set: BTreeSet<&String> = declared.iter().collect();
let exercised_set: BTreeSet<&String> = exercised.iter().collect();
CoverageReport {
uncovered: declared_set
.difference(&exercised_set)
.map(|code| (*code).clone())
.collect(),
orphan: exercised_set
.difference(&declared_set)
.map(|code| (*code).clone())
.collect(),
}
}