use std::{
collections::{BTreeSet, HashSet},
path::{Path, PathBuf},
};
use crate::{
Cache, CacheMode, Config, Error, Expr, Finding, RepoPath, RepoRoot, Report, Result,
cache::CitedFact,
check, config, fix,
grammar::{FormatRegistry, Grammar},
include, index,
model::{KeyIndex, Query},
};
use super::{
admit::{admit_closure, admit_for_check, admit_full, admit_schemas_for, needed_slugs},
load::{CachedLoader, Loaded, ensure_not_missed, load_for_check, load_formats},
markers::is_checked_unit,
};
#[derive(Debug, Clone)]
pub struct ValidateOptions {
pub paths: Vec<PathBuf>,
pub cwd: PathBuf,
pub fix: bool,
pub cache: CacheMode,
pub query: Option<Expr>,
pub changed: Vec<PathBuf>,
}
fn changed_paths(root: &RepoRoot, cwd: &Path, paths: &[PathBuf]) -> Result<Vec<RepoPath>> {
paths
.iter()
.map(|path| {
let shown = path.display().to_string();
path.to_str()
.and_then(|s| crate::PathArg(s).resolve_new(root, cwd))
.ok_or(Error::Path(shown))
})
.collect()
}
pub fn check_repository(
root: &RepoRoot,
config: &Config,
grammar: &Grammar,
repo_formats: Option<&FormatRegistry>,
cache: &Cache,
want_full: bool,
) -> Result<(Loaded, Vec<Finding>)> {
check_and_keep(root, config, grammar, repo_formats, cache, want_full, true)
}
pub(crate) fn check_and_keep(
root: &RepoRoot,
config: &Config,
grammar: &Grammar,
repo_formats: Option<&FormatRegistry>,
cache: &Cache,
want_full: bool,
report: bool,
) -> Result<(Loaded, Vec<Finding>)> {
let run = || {
check_once(
root,
config,
grammar,
repo_formats,
cache,
want_full,
report,
)
};
let result = run();
if hint_missed(root, cache, result.as_ref().err()) {
return run();
}
result
}
fn hint_missed(root: &RepoRoot, cache: &Cache, e: Option<&Error>) -> bool {
if cache.hint().is_none() || cache.is_fresh() {
return false;
}
let read_removed = e.is_some_and(|e| {
super::load::is_not_found(e)
&& matches!(e, Error::Io { path, .. } if RepoPath::from_fs(root, path).is_some())
});
let missed = cache.missed() || read_removed;
if missed {
cache.drop_hint();
}
missed
}
fn check_once(
root: &RepoRoot,
config: &Config,
grammar: &Grammar,
repo_formats: Option<&FormatRegistry>,
cache: &Cache,
want_full: bool,
report: bool,
) -> Result<(Loaded, Vec<Finding>)> {
let mut loaded = load_for_check(root, config, grammar, repo_formats, cache, want_full)?;
let indexes = index::expected_for(&loaded.model, &[], loaded.touched.as_ref());
let stored_citations = |units: &BTreeSet<RepoPath>, checked: &BTreeSet<RepoPath>| {
let mut rows = Vec::new();
for unit in units {
for c in cache.stored_citations_of(unit, checked) {
rows.push((unit.clone(), c));
}
}
rows
};
let (units, citations) = if loaded.full {
(None, Vec::new())
} else {
let mut units = loaded.dirty.clone();
units.extend(indexes.expected.keys().cloned());
(Some(units), stored_citations(&loaded.dirty, &loaded.dirty))
};
let mut out = check::run_units(
&loaded.model,
&loaded.compiled,
&loaded.expected,
&loaded.keys,
&indexes,
units.as_ref(),
citations,
true,
);
if !loaded.full {
let mut moved: BTreeSet<String> = BTreeSet::new();
for (source, cited) in &out.citations {
let old = cache.old_citations(source);
let new: BTreeSet<CitedFact> = cited
.iter()
.map(|(target, c)| CitedFact::of(target, c))
.collect();
for fact in old.symmetric_difference(&new) {
moved.insert(Query::Citations(fact.target.clone()).key());
}
}
let checked: BTreeSet<RepoPath> = out.documents.keys().cloned().collect();
let round2: BTreeSet<RepoPath> = cache
.readers_of(&moved)
.into_iter()
.filter(|p| is_checked_unit(&loaded.model, cache, p) && !checked.contains(p))
.collect();
if !round2.is_empty() {
admit_for_check(
&mut loaded.model,
&mut CachedLoader::new(root, cache),
cache,
&mut loaded.compiled,
&round2,
)?;
let own = check::capture_keys_of(&loaded.model, &loaded.compiled, Some(&round2));
let held: HashSet<(RepoPath, String)> = own
.document
.keys()
.filter(|k| loaded.keys.document.contains_key(*k))
.cloned()
.collect();
loaded.keys.extend(
own.document
.into_iter()
.filter(|(k, _)| !held.contains(k))
.flat_map(|(_, entries)| entries),
);
let slugs = needed_slugs(&loaded.model, &KeyIndex::default());
let stored = cache.stored_keys_for(&slugs, &checked);
for entries in stored.document.into_values() {
for e in entries {
if !loaded
.keys
.document
.contains_key(&(e.path.clone(), crate::markdown::slug(&e.key)))
{
loaded.keys.add(e);
}
}
}
let more = include::expected_for(&loaded.model, &loaded.keys, Some(&round2));
loaded.expected.includes.extend(more.includes);
loaded.expected.definitions.extend(more.definitions);
let excluding: BTreeSet<RepoPath> = checked.union(&round2).cloned().collect();
let mut citations = stored_citations(&round2, &excluding);
for cited in out.citations.values() {
citations.extend(
cited
.iter()
.filter(|(target, _)| round2.contains(target))
.cloned(),
);
}
let second = check::run_units(
&loaded.model,
&loaded.compiled,
&loaded.expected,
&loaded.keys,
&indexes,
Some(&round2),
citations,
false,
);
out.documents.extend(second.documents);
out.citations.extend(second.citations);
loaded.dirty.extend(round2);
}
}
let checked: BTreeSet<RepoPath> = out.documents.keys().cloned().collect();
for (path, findings) in &out.documents {
cache.record_output(path, findings.clone());
if loaded.model.holds(path) || loaded.model.is_additional(path) {
loaded.model.watch(path);
cache.record_edges(path, crate::graph::edges_of(&loaded.model, path));
loaded.model.unwatch();
}
cache.record_deps(path, &loaded.model.reads_of(path));
}
for (source, cited) in &out.citations {
let rows = cited
.iter()
.map(|(target, c)| crate::cache::CitationRow {
target: target.clone(),
slug: c.slug.clone(),
source: c.source.clone(),
source_type: c.source_type.clone(),
rel: c.rel.clone(),
line: c.line,
})
.collect();
cache.record_citations(source, rows);
}
cache.record_keys_of(&loaded.keys, &checked);
cache.record_plans_of(&loaded.model.plans, &checked);
for queries in loaded.model.reads().values() {
for q in queries {
if let Query::Exists(p) = q
&& !cache.is_walked(p)
{
cache.record_probe(p, loaded.model.tree.exists(p));
}
}
}
ensure_not_missed(cache)?;
cache.commit();
if !report {
return Ok((loaded, Vec::new()));
}
let mut findings = out.findings();
if !loaded.full {
findings.extend(cache.stored_outputs(&checked));
}
Ok((loaded, findings))
}
fn prepare_fix(
root: &RepoRoot,
cache: &Cache,
loaded: &mut Loaded,
findings: &[Finding],
) -> Result<Option<BTreeSet<RepoPath>>> {
if loaded.full {
return Ok(None);
}
let mut fix_set: BTreeSet<RepoPath> = findings
.iter()
.filter(|f| loaded.model.is_unit(&f.path))
.map(|f| f.path.clone())
.collect();
let indexes: BTreeSet<RepoPath> = findings
.iter()
.filter(|f| f.path.file_name() == "index.md" && !loaded.model.is_unit(&f.path))
.map(|f| f.path.clone())
.collect();
let mut moved: BTreeSet<String> = BTreeSet::new();
for f in findings {
if !f.message.contains("its lifecycle states place it in") || !loaded.model.is_unit(&f.path)
{
continue;
}
moved.insert(Query::Path(f.path.clone()).key());
moved.insert(Query::Body(f.path.clone()).key());
if let Some(old) = cache.old_row(&f.path)
&& let Some(id) = old.id
{
moved.insert(
Query::Doc {
knowledge: old.knowledge,
id,
}
.key(),
);
}
if let Some((_, asset)) = loaded.model.asset_of(&f.path) {
moved.insert(Query::Path(asset.path.clone()).key());
}
}
fix_set.extend(
cache
.readers_of(&moved)
.into_iter()
.filter(|p| loaded.model.is_unit(p)),
);
let mut loader = CachedLoader::new(root, cache);
admit_full(&mut loaded.model, &mut loader, cache, &fix_set)?;
let held: BTreeSet<RepoPath> = loaded
.model
.documents()
.map(|(_, d)| d.path.clone())
.chain(loaded.model.additional.iter().map(|a| a.path.clone()))
.collect();
admit_closure(&mut loaded.model, &mut loader, cache, &held);
admit_schemas_for(&mut loaded.model, &mut loader, cache, &held)?;
ensure_not_missed(cache)?;
loaded.compiled.compile_more(&loaded.model);
let mut keys = check::capture_keys_of(&loaded.model, &loaded.compiled, Some(&held));
let slugs = needed_slugs(&loaded.model, &keys);
keys.extend(
cache
.stored_keys_for(&slugs, &held)
.document
.into_values()
.flatten(),
);
loaded.expected = include::expected_for(&loaded.model, &keys, Some(&held));
loaded.keys = keys;
let mut over = held;
over.extend(indexes);
Ok(Some(over))
}
fn plan_fix(
root: &RepoRoot,
cache: &Cache,
loaded: &mut Loaded,
findings: &[Finding],
scope: &config::Scope,
) -> Result<fix::FixPlan> {
let over = prepare_fix(root, cache, loaded, findings)?;
fix::plan(
&loaded.model,
&loaded.compiled,
&loaded.expected,
&loaded.keys,
scope,
over.as_ref(),
)
}
fn plan_is_stale(root: &RepoRoot, model: &crate::Model, plan: &fix::FixPlan) -> bool {
let moved_to: BTreeSet<&RepoPath> = plan.moves.iter().map(|m| &m.to).collect();
let listed_dir = |d: &RepoPath| model.tree.dirs.binary_search_by(|x| x.path.cmp(d)).is_ok();
let gone_dir = |d: &RepoPath| listed_dir(d) && !d.to_fs(root).is_dir();
plan.moves
.iter()
.any(|m| !m.from.to_fs(root).exists() || m.to.parent().is_some_and(|d| gone_dir(&d)))
|| plan
.rewrites
.iter()
.any(|r| !moved_to.contains(&r.path) && !r.path.to_fs(root).exists())
|| plan.creates.iter().any(|c| {
model.tree.file(&c.path).is_some() || c.path.parent().is_some_and(|d| gone_dir(&d))
})
}
const FIX_PASSES: usize = 10;
pub fn validate(
root: &RepoRoot,
opts: &ValidateOptions,
) -> Result<(Report, Option<serde_json::Value>)> {
let config = config::load_config(root)?;
let (grammar, repo_formats) = load_formats(root)?;
let mut scope = config::resolve_paths(root, &opts.cwd, &opts.paths)?;
let cache = Cache::open(root, opts.cache);
if !opts.changed.is_empty() {
if opts.cache == CacheMode::Off {
return Err(Error::Internal(
"`--changed` needs the cache, so don't use it with `--no-cache`".into(),
));
}
cache.set_hint(changed_paths(root, &opts.cwd, &opts.changed)?);
}
let check = || {
check_repository(
root,
&config,
&grammar,
repo_formats.as_ref(),
&cache,
false,
)
};
let mut report = Report::default();
let (mut loaded, mut findings) = check()?;
let mut passes = 0;
while opts.fix && passes < FIX_PASSES {
passes += 1;
let mut plan = plan_fix(root, &cache, &mut loaded, &findings, &scope);
let stale = matches!(&plan, Ok(p) if cache.hint().is_some()
&& !cache.is_fresh()
&& plan_is_stale(root, &loaded.model, p));
if stale {
cache.drop_hint();
}
if stale || hint_missed(root, &cache, plan.as_ref().err()) {
(loaded, findings) = check()?;
plan = plan_fix(root, &cache, &mut loaded, &findings, &scope);
}
let plan = plan?;
for m in &plan.moves {
scope.add(m.to.clone());
}
let (ops, refused) = fix::apply(root, plan)?;
if let Some(mut hint) = cache.hint() {
for op in &ops {
match op {
crate::FixOp::Moved { from, to } => {
hint.push(from.clone());
hint.push(to.clone());
}
crate::FixOp::Created { path } | crate::FixOp::Rewrote { path } => {
hint.push(path.clone());
}
}
}
cache.set_hint(hint);
}
let wrote = !ops.is_empty();
report.fixes.extend(ops);
report.extend(refused);
(loaded, findings) = check()?;
if !wrote || !findings.iter().any(|f| f.criterion == "SOKF_FORMAT_85") {
break;
}
}
report.extend(findings);
let report = report.finish().filter(&scope);
let projection = opts.query.as_ref().map(|q| report.project(q)).transpose()?;
Ok((report, projection))
}