1use std::{collections::BTreeSet, path::PathBuf, rc::Rc};
4
5use crate::{
6 Cache, CacheMode, Model, RepoPath, RepoRoot, Result, config,
7 graph::{self, EdgeKind, Graph, GraphQuery, GraphResult, Hydrator, NodeKey, RawEdge},
8 model::{KeyIndex, ParseMode, parse_source},
9 source,
10};
11
12#[derive(Debug, Clone)]
14pub struct GraphOptions {
15 pub query: GraphQuery,
17 pub cwd: PathBuf,
19 pub cache: CacheMode,
21}
22
23pub fn graph(root: &RepoRoot, opts: &GraphOptions) -> Result<(Graph, GraphResult)> {
41 let config = config::load_config(root)?;
42 let cache = Cache::open(root, opts.cache);
43 let keyed = opts.query.start.iter().any(|s| has_fragment(s));
47 let every_edge = !cache.is_on() && (!opts.query.start.is_empty() || opts.query.layout_edges);
51 let (mut model, keys, all_keys): (Model, Option<KeyIndex>, Option<KeyIndex>) = if keyed {
52 let slugs = super::locate::key_slugs(&opts.query.start, has_fragment);
53 let (model, keys) = super::load_keys_for(root, &config, &cache, &slugs)?;
54 (model, Some(keys), None)
55 } else if every_edge {
56 let (model, keys) = super::load_with_keys(root, &config, &cache)?;
57 (model, None, Some(keys))
58 } else {
59 (super::load_for_lookup(root, &config, &cache)?, None, None)
60 };
61 model.marker_check = config.markers;
62 let markers = match keys.as_ref().or(all_keys.as_ref()) {
63 Some(every) if every_edge => super::markers::marker_edges(&model, every, root),
64 _ => Vec::new(),
65 };
66 let mut graph = if cache.is_on() {
67 graph::build_from(&model, Vec::new(), Some(hydrator(root)))
68 } else if every_edge {
69 let mut graph = graph::build(&model);
70 graph.add_edges(markers.clone());
71 graph
72 } else {
73 graph::build_from(&model, Vec::new(), None)
74 };
75 graph.set_archived(model.archived_documents());
76 if let Some(keys) = &keys {
77 for arg in &opts.query.start {
78 if let Some((entry, slug)) = graph::key_entry(&model, keys, arg) {
79 let citing = citing(&model, keys, &cache, &entry.path, &slug);
80 graph.add_key(&entry.path, &slug, &entry.key, entry.line, &citing);
81 graph.add_edges(key_markers(&cache, &markers, &entry.path, &slug));
82 }
83 }
84 }
85 if cache.is_on() {
86 let starts = graph::starts(&mut graph, &model, keys.as_ref(), &opts.cwd, &opts.query)?;
87 let edges = graph::edges_near(&graph, &starts, &opts.query, &cache);
88 graph.add_edges(edges);
89 }
90 let result = graph::run(&mut graph, &model, keys.as_ref(), &opts.cwd, &opts.query)?;
91 Ok((graph, result))
92}
93
94fn has_fragment(arg: &str) -> bool {
97 arg.split_once('#').is_some_and(|(_, f)| !f.is_empty())
98}
99
100fn hydrator(root: &RepoRoot) -> Hydrator {
103 let repo = root.clone();
104 Hydrator(Rc::new(move |path: &RepoPath| {
105 let src = source::load(&repo, path).ok()?;
106 let parsed = parse_source(&src, ParseMode::Document);
107 Some(graph::frontmatter_json(&crate::Document::new(src, parsed)))
108 }))
109}
110
111fn key_markers(cache: &Cache, markers: &[RawEdge], path: &RepoPath, slug: &str) -> Vec<RawEdge> {
118 let key = NodeKey::Key(format!("{path}#{slug}"));
119 let edge = |from: RepoPath, rel: String, line: Option<usize>| RawEdge {
120 from,
121 kind: EdgeKind::Marker,
122 written: key.as_str().to_string(),
123 to: key.clone(),
124 rel,
125 region: None,
126 line,
127 note: None,
128 };
129 if cache.is_on() {
130 cache
131 .stored_citations_of(path, &BTreeSet::new())
132 .into_iter()
133 .filter(|c| c.slug.as_deref() == Some(slug))
134 .filter_map(|c| Some(edge(c.source, c.rel?, Some(c.line))))
135 .collect()
136 } else {
137 markers
138 .iter()
139 .filter(|m| m.to.path() == Some(path) && m.region.as_deref() == Some(slug))
140 .map(|m| edge(m.from.clone(), m.rel.clone(), m.line))
141 .collect()
142 }
143}
144
145fn citing(
152 model: &Model,
153 keys: &KeyIndex,
154 cache: &Cache,
155 path: &RepoPath,
156 slug: &str,
157) -> Vec<RepoPath> {
158 let mut out: BTreeSet<RepoPath> = BTreeSet::new();
159 if cache.is_on() {
160 for c in cache.stored_citations_of(path, &BTreeSet::new()) {
161 if c.rel.is_none() && c.slug.as_deref() == Some(slug) {
162 out.insert(c.source);
163 }
164 }
165 } else {
166 for (k, doc) in model.documents() {
167 if doc.type_name().is_none() {
168 continue;
169 }
170 for link in &doc.body.links {
171 let Some(label) = crate::model::keys::Label::of(&link.target) else {
172 continue;
173 };
174 if let Ok(r) = crate::model::keys::resolve(model, keys, k, label)
175 && &r.path == path
176 && r.slug.as_deref() == Some(slug)
177 {
178 out.insert(doc.path.clone());
179 }
180 }
181 }
182 }
183 out.remove(path);
184 out.into_iter().collect()
185}