use std::{collections::BTreeSet, path::PathBuf, rc::Rc};
use crate::{
Cache, CacheMode, Model, RepoPath, RepoRoot, Result, config,
graph::{self, EdgeKind, Graph, GraphQuery, GraphResult, Hydrator, NodeKey, RawEdge},
model::{KeyIndex, ParseMode, parse_source},
source,
};
#[derive(Debug, Clone)]
pub struct GraphOptions {
pub query: GraphQuery,
pub cwd: PathBuf,
pub cache: CacheMode,
}
pub fn graph(root: &RepoRoot, opts: &GraphOptions) -> Result<(Graph, GraphResult)> {
let config = config::load_config(root)?;
let cache = Cache::open(root, opts.cache);
let keyed = opts.query.start.iter().any(|s| graph::is_key_reference(s));
let every_edge = !cache.is_on() && (!opts.query.start.is_empty() || opts.query.layout_edges);
let (mut model, keys, all_keys): (Model, Option<KeyIndex>, Option<KeyIndex>) = if keyed {
let slugs = super::locate::key_slugs(&opts.query.start);
let (model, keys) = super::load_keys_for(root, &config, &cache, &slugs)?;
(model, Some(keys), None)
} else if every_edge {
let (model, keys) = super::load_with_keys(root, &config, &cache)?;
(model, None, Some(keys))
} else {
(super::load_for_lookup(root, &config, &cache)?, None, None)
};
model.marker_check = config.markers;
let markers = match keys.as_ref().or(all_keys.as_ref()) {
Some(every) if every_edge => super::markers::marker_edges(&model, every, root),
_ => Vec::new(),
};
let mut graph = if cache.is_on() {
graph::build_from(&model, Vec::new(), Some(hydrator(root)))
} else if every_edge {
let mut graph = graph::build(&model);
graph.add_edges(markers.clone());
graph
} else {
graph::build_from(&model, Vec::new(), None)
};
graph.set_archived(model.archived_documents());
if let Some(keys) = &keys {
for arg in &opts.query.start {
if let Some((entry, slug)) = graph::key_entry(&model, keys, arg) {
let citing = citing(&model, keys, &cache, &entry.path, &slug);
graph.add_key(&entry.path, &slug, &entry.key, entry.line, &citing);
graph.add_edges(key_markers(&cache, &markers, &entry.path, &slug));
}
}
}
if cache.is_on() {
let starts = graph::starts(&mut graph, &model, keys.as_ref(), &opts.cwd, &opts.query)?;
let edges = graph::edges_near(&graph, &starts, &opts.query, &cache);
graph.add_edges(edges);
}
let result = graph::run(&mut graph, &model, keys.as_ref(), &opts.cwd, &opts.query)?;
Ok((graph, result))
}
fn hydrator(root: &RepoRoot) -> Hydrator {
let repo = root.clone();
Hydrator(Rc::new(move |path: &RepoPath| {
let src = source::load(&repo, path).ok()?;
let parsed = parse_source(&src, ParseMode::Document);
Some(graph::frontmatter_json(&crate::Document::new(src, parsed)))
}))
}
fn key_markers(cache: &Cache, markers: &[RawEdge], path: &RepoPath, slug: &str) -> Vec<RawEdge> {
let key = NodeKey::Key(format!("{path}#{slug}"));
let edge = |from: RepoPath, rel: String, line: Option<usize>| RawEdge {
from,
kind: EdgeKind::Marker,
written: key.as_str().to_string(),
to: key.clone(),
rel,
region: None,
line,
note: None,
};
if cache.is_on() {
cache
.stored_citations_of(path, &BTreeSet::new())
.into_iter()
.filter(|c| c.slug.as_deref() == Some(slug))
.filter_map(|c| Some(edge(c.source, c.rel?, Some(c.line))))
.collect()
} else {
markers
.iter()
.filter(|m| m.to.path() == Some(path) && m.region.as_deref() == Some(slug))
.map(|m| edge(m.from.clone(), m.rel.clone(), m.line))
.collect()
}
}
fn citing(
model: &Model,
keys: &KeyIndex,
cache: &Cache,
path: &RepoPath,
slug: &str,
) -> Vec<RepoPath> {
let mut out: BTreeSet<RepoPath> = BTreeSet::new();
if cache.is_on() {
for c in cache.stored_citations_of(path, &BTreeSet::new()) {
if c.rel.is_none() && c.slug.as_deref() == Some(slug) {
out.insert(c.source);
}
}
} else {
for (k, doc) in model.documents() {
if doc.type_name().is_none() {
continue;
}
for link in &doc.body.links {
let Some(label) = crate::model::keys::Label::of(&link.target) else {
continue;
};
if let Ok(r) = crate::model::keys::resolve(model, keys, k, label)
&& &r.path == path
&& r.slug.as_deref() == Some(slug)
{
out.insert(doc.path.clone());
}
}
}
}
out.remove(path);
out.into_iter().collect()
}