use std::collections::BTreeSet;
use std::fmt;
use std::fs::OpenOptions;
use std::io::Write as _;
use std::path::{Path, PathBuf};
use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};
pub const BASELINE_SCHEMA: u32 = 1;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum GapKind {
EnforcementAnchor,
VerificationAnchor,
EvidenceCitation,
}
impl fmt::Display for GapKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let name = match self {
Self::EnforcementAnchor => "enforcement-anchor",
Self::VerificationAnchor => "verification-anchor",
Self::EvidenceCitation => "evidence-citation",
};
f.write_str(name)
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct GapKey {
pub requirement: String,
pub kind: GapKind,
}
impl GapKey {
pub fn new(requirement: impl Into<String>, kind: GapKind) -> Self {
Self {
requirement: requirement.into(),
kind,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
#[shallguard::enforces("REQ-BASE-001")]
pub struct BaselineEntry {
pub requirement: String,
pub kind: GapKind,
}
impl BaselineEntry {
pub fn key(&self) -> GapKey {
GapKey::new(self.requirement.clone(), self.kind)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Baseline {
pub schema: u32,
#[serde(default, rename = "gap")]
pub gaps: Vec<BaselineEntry>,
}
impl Baseline {
pub fn from_entries(gaps: Vec<BaselineEntry>) -> Self {
let mut baseline = Self {
schema: BASELINE_SCHEMA,
gaps,
};
baseline.sort();
baseline
}
pub fn load(root: &Path, relative_path: &Path) -> Result<Self> {
let path = root.join(relative_path);
let text = std::fs::read_to_string(&path)
.with_context(|| format!("reading traceability baseline {}", path.display()))?;
Self::parse(&text, &path.display().to_string())
}
pub fn parse(text: &str, source: &str) -> Result<Self> {
let mut baseline: Self = toml::from_str(text)
.with_context(|| format!("parsing traceability baseline {source}"))?;
if baseline.schema != BASELINE_SCHEMA {
bail!(
"unsupported traceability baseline schema {} in {} (expected {})",
baseline.schema,
source,
BASELINE_SCHEMA
);
}
baseline.sort();
Ok(baseline)
}
pub fn duplicate_keys(&self) -> BTreeSet<GapKey> {
let mut seen = BTreeSet::new();
let mut duplicates = BTreeSet::new();
for entry in &self.gaps {
let key = entry.key();
if !seen.insert(key.clone()) {
duplicates.insert(key);
}
}
duplicates
}
pub fn render(&self) -> Result<String> {
let mut sorted = self.clone();
sorted.sort();
let body = toml::to_string_pretty(&sorted).context("serializing traceability baseline")?;
Ok(format!(
"# Historical traceability debt. Do not add or refresh entries.\n\
# `cargo shallguard baseline prune` only removes resolved debt.\n\n\
{body}"
))
}
pub fn create_new(&self, root: &Path, relative_path: &Path) -> Result<PathBuf> {
let path = root.join(relative_path);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)
.with_context(|| format!("creating baseline directory {}", parent.display()))?;
}
let mut file = OpenOptions::new()
.write(true)
.create_new(true)
.open(&path)
.with_context(|| {
format!(
"creating initial baseline {} (refusing to overwrite an existing file)",
path.display()
)
})?;
file.write_all(self.render()?.as_bytes())
.with_context(|| format!("writing initial baseline {}", path.display()))?;
Ok(path)
}
pub fn write_pruned(&self, root: &Path, relative_path: &Path) -> Result<PathBuf> {
let path = root.join(relative_path);
std::fs::write(&path, self.render()?)
.with_context(|| format!("writing pruned baseline {}", path.display()))?;
Ok(path)
}
fn sort(&mut self) {
self.gaps.sort_by_key(BaselineEntry::key);
}
}
#[cfg(test)]
mod tests {
use super::*;
fn entry(requirement: &str, kind: GapKind) -> BaselineEntry {
BaselineEntry {
requirement: requirement.to_string(),
kind,
}
}
#[shallguard::verifies("REQ-BASE-001")]
#[test]
fn serialization_is_sorted_and_round_trips() {
let baseline = Baseline::from_entries(vec![
entry("REQ-ZZ-002", GapKind::VerificationAnchor),
entry("REQ-AA-001", GapKind::EnforcementAnchor),
]);
let rendered = baseline.render().expect("baseline renders");
let aa = rendered.find("REQ-AA-001").expect("AA entry exists");
let zz = rendered.find("REQ-ZZ-002").expect("ZZ entry exists");
assert!(aa < zz);
let parsed: Baseline = toml::from_str(&rendered).expect("rendered TOML parses");
assert_eq!(parsed, baseline);
}
#[test]
fn duplicate_keys_are_rejected() {
let first = entry("REQ-AA-001", GapKind::EvidenceCitation);
let second = first.clone();
let baseline = Baseline::from_entries(vec![first, second]);
assert_eq!(
baseline.duplicate_keys(),
BTreeSet::from([GapKey::new("REQ-AA-001", GapKind::EvidenceCitation)])
);
}
}