use std::collections::{BTreeMap, BTreeSet};
use super::{Citation, Citations, Ctx, DocView};
use crate::{
Document, Finding, MarkerCheck, Model, RepoPath,
graph::{Target, resolve_to},
model::{LinkEntry, Query, Status},
report::and_list,
};
#[derive(Debug, Clone)]
pub struct Citer {
source: RepoPath,
source_type: String,
retired: bool,
superseded: BTreeSet<RepoPath>,
}
impl Citer {
pub fn of(doc: DocView<'_>, ctx: &Ctx<'_>) -> Option<Citer> {
let mut citer = Citer {
source: doc.path.clone(),
source_type: String::new(),
retired: false,
superseded: BTreeSet::new(),
};
let Some(core) = doc.core else {
return Some(citer);
};
citer.source_type = core.type_.clone()?;
let Some(k) = ctx.knowledge else {
return Some(citer);
};
citer.retired = core.status == Some(Status::Deprecated)
|| ctx
.model
.is_archived(k, core.type_.as_deref(), doc.frontmatter);
citer.superseded = linked_documents(ctx.model, k, &core.links, "supersedes");
Some(citer)
}
pub fn cite(
&self,
target: &RepoPath,
slug: Option<String>,
line: usize,
include: bool,
) -> Citation {
Citation {
slug,
source: self.source.clone(),
source_type: self.source_type.clone(),
rel: None,
line,
include,
supersedes: self.superseded.contains(target),
retired: self.retired,
declared: false,
}
}
pub fn declare(&self, line: usize) -> Citation {
Citation {
slug: None,
source: self.source.clone(),
source_type: self.source_type.clone(),
rel: None,
line,
include: false,
supersedes: true,
retired: self.retired,
declared: true,
}
}
}
pub fn check_document(
model: &Model,
citations: &Citations,
k: usize,
doc: &Document,
) -> Vec<Finding> {
if doc.core.status != Some(Status::Deprecated) {
return Vec::new();
}
model.note(Query::Citations(doc.path.clone()));
let markers_off = model.marker_check == MarkerCheck::Off;
let cited: Vec<&Citation> = citations
.all_of(&doc.path)
.filter(|c| !(markers_off && c.rel.is_some()))
.collect();
for c in &cited {
model.note(Query::Body(c.source.clone()));
}
let warnable: Vec<&Citation> = cited
.iter()
.copied()
.filter(|c| !c.retired && !c.supersedes)
.collect();
if warnable.is_empty() {
return Vec::new();
}
let mut named = linked_documents(model, k, &doc.core.links, "superseded-by");
named.remove(&doc.path);
let mut replacements = named.clone();
replacements.extend(
cited
.iter()
.filter(|c| c.supersedes && c.source != doc.path)
.map(|c| c.source.clone()),
);
let mut clauses: BTreeMap<usize, String> = BTreeMap::new();
let name = doc.id().unwrap_or(doc.path.as_str());
warnable
.iter()
.filter(|c| !named.contains(&c.source))
.map(|c| {
let citing = model.knowledge_of(&c.source).unwrap_or(k);
let replaced = clauses
.entry(citing)
.or_insert_with(|| replaced_by(&spellings(model, citing, &replacements)))
.as_str();
let at = match &c.slug {
Some(slug) => format!("`{name}#{slug}`, in `{name}`"),
None => format!("`{name}`"),
};
let (key, message) = match (&c.rel, c.include) {
(Some(rel), _) => (
"SOKF_VALIDATION_58",
format!("`sokf-{rel}:` cites {at}, which is deprecated{replaced}"),
),
(None, true) => (
"SOKF_VALIDATION_59",
format!("`sokf:include` includes {at}, which is deprecated{replaced}"),
),
(None, false) => (
"SOKF_VALIDATION_57",
format!("link to {at}, which is deprecated{replaced}"),
),
};
Finding::warning(c.source.clone(), Some(c.line), key, message)
})
.collect()
}
fn spellings(model: &Model, citing: usize, replacements: &BTreeSet<RepoPath>) -> Vec<String> {
let mut names: Vec<String> = replacements
.iter()
.map(|path| {
model
.id_of(path)
.and_then(|(store, id)| model.canonical_include(citing, store, &id, None))
.unwrap_or_else(|| path.to_string())
})
.collect();
names.sort();
names.dedup();
names
}
fn linked_documents(model: &Model, k: usize, links: &[LinkEntry], rel: &str) -> BTreeSet<RepoPath> {
links
.iter()
.filter(|l| l.rel == rel)
.filter_map(|l| match resolve_to(model, k, &l.to)? {
Target::Document { path, .. } => Some(path),
Target::File(_) => None,
})
.collect()
}
fn replaced_by(superseders: &[String]) -> String {
let names: Vec<String> = superseders.iter().map(|s| format!("`{s}`")).collect();
let verb = match names.as_slice() {
[] => return String::new(),
[_] => "supersedes",
_ => "supersede",
};
format!(": {} {verb} it", and_list(&names))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_clause_names_each_superseder_in_a_list() {
let names =
|list: &[&str]| -> Vec<String> { list.iter().map(ToString::to_string).collect() };
assert_eq!(replaced_by(&[]), "");
assert_eq!(replaced_by(&names(&["a"])), ": `a` supersedes it");
assert_eq!(
replaced_by(&names(&["a", "b"])),
": `a` and `b` supersede it"
);
assert_eq!(
replaced_by(&names(&["a", "b", "c"])),
": `a`, `b`, and `c` supersede it"
);
}
}