1use std::collections::{BTreeMap, BTreeSet, HashSet};
6
7use serde_json::{Map, Value};
8
9use super::{Edge, EdgeKind, Graph, Hydrator, Node, NodeKey, NodeKind, model::ancestors};
10use crate::{
11 Document, FileKind, Model, RepoPath, Segments, Yaml,
12 markdown::{Body, IncludeTarget},
13 model::{frontmatter::Resource, keys::Label},
14 yaml::Spanned,
15};
16
17#[derive(Debug, Clone, PartialEq, Eq)]
19pub enum Target {
20 Document {
22 path: RepoPath,
24 id: String,
26 knowledge: usize,
28 },
29 File(RepoPath),
31}
32
33pub fn resolve_to(model: &Model, knowledge: usize, to: &str) -> Option<Target> {
43 if !to.starts_with('/') {
44 let (store, id) = crate::model::split_store(to);
45 let (k, path) = path_in(model, knowledge, store, id)?;
46 return Some(Target::Document {
47 path,
48 id: id.to_string(),
49 knowledge: k,
50 });
51 }
52 let path = RepoPath::parse(to)?;
53 if let Some((k, id)) = model.id_of(&path) {
54 return Some(Target::Document {
55 path,
56 id,
57 knowledge: k,
58 });
59 }
60 model.exists(&path).then_some(Target::File(path))
61}
62
63fn path_in(
67 model: &Model,
68 citing: usize,
69 store: Option<&str>,
70 id: &str,
71) -> Option<(usize, RepoPath)> {
72 let k = match store {
73 None => citing,
74 Some(s) => model.store(citing, s)?.knowledge,
75 };
76 model.path_of_id(k, id).map(|p| (k, p))
77}
78
79#[expect(
88 clippy::match_same_arms,
89 reason = "the arm for `relates-to` repeats the wildcard's value, so that the list names every inverse that SOKF_FORMAT_116 gives"
90)]
91pub fn inverse_rel(rel: &str) -> &'static str {
92 match rel {
93 "relates-to" => "relates-to",
94 "part-of" => "has-part",
95 "has-part" => "part-of",
96 "depends-on" => "depended-on-by",
97 "depended-on-by" => "depends-on",
98 "references" => "referenced-by",
99 "referenced-by" => "references",
100 "supersedes" => "superseded-by",
101 "superseded-by" => "supersedes",
102 "implements" => "implemented-by",
103 "implemented-by" => "implements",
104 "tests" => "tested-by",
105 "tested-by" => "tests",
106 "contradicts" => "contradicts",
107 "describes" => "described-by",
108 "described-by" => "describes",
109 "derives-from" => "derived-by",
110 "derived-by" => "derives-from",
111 "includes" => "included-by",
112 "included-by" => "includes",
113 _ => "relates-to",
114 }
115}
116
117pub fn frontmatter_json(doc: &Document) -> Map<String, Value> {
124 let mut fields = Map::new();
125 if let Some(entries) = doc.frontmatter.as_ref().and_then(Spanned::as_map) {
126 for (key, value) in entries {
127 if matches!(
128 key.value.as_str(),
129 "links" | "kind" | "path" | "broken" | "reason"
130 ) {
131 continue;
132 }
133 fields.insert(key.value.clone(), yaml_json(value));
134 }
135 }
136 if !fields.contains_key("status") {
138 fields.insert("status".into(), Value::from("stable"));
139 }
140 let reason = if doc.frontmatter.is_none() && doc.frontmatter_found {
142 Some("frontmatter does not parse")
143 } else if doc.id().is_none() {
144 Some("no id")
145 } else {
146 None
147 };
148 if let Some(reason) = reason {
149 fields.insert("broken".into(), Value::Bool(true));
150 fields.insert("reason".into(), Value::from(reason));
151 }
152 fields
153}
154
155pub(crate) fn yaml_json(value: &Spanned) -> Value {
158 match &value.value {
159 Yaml::Null => Value::Null,
160 Yaml::Bool(b) => Value::Bool(*b),
161 Yaml::Int(i) => Value::from(*i),
162 Yaml::Float(f) => serde_json::Number::from_f64(*f).map_or(Value::Null, Value::Number),
163 Yaml::Str(s) => Value::from(s.as_str()),
164 Yaml::Seq(items) => Value::Array(items.iter().map(yaml_json).collect()),
165 Yaml::Map(entries) => Value::Object(
166 entries
167 .iter()
168 .map(|(k, v)| (k.value.clone(), yaml_json(v)))
169 .collect(),
170 ),
171 }
172}
173
174#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
180pub struct RawEdge {
181 pub from: RepoPath,
183 pub kind: EdgeKind,
185 pub written: String,
188 pub to: NodeKey,
190 pub rel: String,
192 pub region: Option<String>,
195 pub line: Option<usize>,
197 pub note: Option<String>,
199}
200
201pub fn edges_of(model: &Model, path: &RepoPath) -> Vec<RawEdge> {
212 let mut b = Builder::new(model);
213 if let Some((k, doc)) = model.loaded_document(path) {
214 b.document_edges(k, doc);
215 b.include_edges(&doc.path, Some(k), &doc.segments);
216 return b.raw;
217 }
218 if let Some(crate::Located::Additional(file)) = model.by_path(path) {
219 b.body_links(&file.path, None, &file.body, &BTreeSet::new());
220 b.include_edges(&file.path, file.schema.map(|s| s.knowledge), &file.segments);
221 }
222 b.raw
223}
224
225pub fn build(model: &Model) -> Graph {
228 build_from(model, declared_edges(model), None)
229}
230
231pub(super) fn declared_edges(model: &Model) -> Vec<RawEdge> {
234 model
235 .documents_and_schemas()
236 .map(|(_, d)| &d.path)
237 .chain(model.additional.iter().map(|a| &a.path))
238 .flat_map(|p| edges_of(model, p))
239 .collect()
240}
241
242pub fn build_from(model: &Model, edges: Vec<RawEdge>, hydrator: Option<Hydrator>) -> Graph {
253 let mut b = Builder::new(model);
254 let mut built: HashSet<NodeKey> = HashSet::new();
255 for knowledge in &model.knowledges {
258 let mut fields = Map::new();
259 if let Some(m) = &knowledge.manifest {
260 for (key, value) in [
261 ("name", &m.name),
262 ("scope", &m.scope),
263 ("description", &m.description),
264 ] {
265 if let Some(value) = value {
266 fields.insert(key.into(), Value::from(value.as_str()));
267 }
268 }
269 }
270 b.insert(knowledge.root.clone(), NodeKind::Root, fields);
271 }
272 for file in &model.tree.files {
277 if !matches!(file.kind, FileKind::Document | FileKind::Schema) {
278 continue;
279 }
280 let Some(k) = file.root else { continue };
281 let fields = match model.loaded_document(&file.path) {
282 Some((_, doc)) => {
283 built.insert(NodeKey::Path(file.path.clone()));
284 frontmatter_json(doc)
285 }
286 None => Map::new(),
287 };
288 b.insert(file.path.clone(), NodeKind::Document, fields);
289 b.directories(&file.path, &model.knowledges[k].root);
290 }
291 for (path, schema) in &model.dispatch {
293 let mut fields = Map::new();
294 if let Some(r) = schema {
295 fields.insert("schema".into(), Value::from(model.schema(*r).id()));
296 }
297 b.insert(path.clone(), NodeKind::Additional, fields);
298 if let Some(k) = model.knowledge_of(path) {
299 b.directories(path, &model.knowledges[k].root);
300 }
301 }
302 for knowledge in &model.knowledges {
306 for asset in &knowledge.assets {
307 let mut fields = Map::new();
308 let sidecar = asset.sidecar_path();
309 let id = match asset.sidecar {
310 Some(i) => knowledge.documents[i].id().map(str::to_string),
311 None if asset.has_sidecar => model
312 .fallback
313 .as_ref()
314 .and_then(|f| f.fields(&sidecar))
315 .and_then(|f| f.id),
316 None => None,
317 };
318 if let Some(id) = id {
319 fields.insert("sidecar".into(), Value::from(id));
320 }
321 b.insert(asset.path.clone(), NodeKind::Asset, fields);
322 b.directories(&asset.path, &knowledge.root);
323 }
324 }
325 b.raw.extend(edges);
327 let graph = b.finish();
328 match hydrator {
329 Some(h) => graph.with_hydrator(h, built),
330 None => graph,
331 }
332}
333
334struct Builder<'a> {
335 model: &'a Model,
336 nodes: BTreeMap<NodeKey, Node>,
337 raw: Vec<RawEdge>,
339}
340
341impl<'a> Builder<'a> {
342 fn new(model: &'a Model) -> Self {
343 Builder {
344 model,
345 nodes: BTreeMap::new(),
346 raw: Vec::new(),
347 }
348 }
349
350 fn insert(&mut self, path: RepoPath, kind: NodeKind, fields: Map<String, Value>) {
351 let key = NodeKey::Path(path);
352 self.nodes.insert(key.clone(), Node { key, kind, fields });
353 }
354
355 fn directories(&mut self, path: &RepoPath, root: &RepoPath) {
358 for d in ancestors(path).take_while(|d| d != root && d.starts_with(root)) {
359 let key = NodeKey::Path(d);
360 self.nodes.entry(key.clone()).or_insert_with(|| Node {
361 key,
362 kind: NodeKind::Directory,
363 fields: Map::new(),
364 });
365 }
366 }
367
368 #[allow(clippy::too_many_arguments)]
369 fn edge(
370 &mut self,
371 from: &RepoPath,
372 kind: EdgeKind,
373 written: &str,
374 to: NodeKey,
375 rel: &str,
376 region: Option<String>,
377 note: Option<String>,
378 ) {
379 self.raw.push(RawEdge {
380 from: from.clone(),
381 kind,
382 written: written.to_string(),
383 to,
384 rel: rel.to_string(),
385 region,
386 line: None,
387 note,
388 });
389 }
390
391 fn path_target(&self, written: &str) -> NodeKey {
394 match RepoPath::parse(written) {
395 Some(p) if self.model.exists(&p) => NodeKey::Path(p),
396 _ => NodeKey::Missing(written.to_string()),
397 }
398 }
399
400 fn document_edges(&mut self, k: usize, doc: &Document) {
401 let mut reached = BTreeSet::new();
402 for entry in &doc.core.links {
403 let to = match resolve_to(self.model, k, &entry.to) {
404 Some(Target::Document { path: p, .. } | Target::File(p)) => NodeKey::Path(p),
405 None => NodeKey::Missing(entry.to.clone()),
406 };
407 reached.insert(to.clone());
408 self.edge(
409 &doc.path,
410 EdgeKind::Links,
411 &entry.to,
412 to,
413 &entry.rel,
414 None,
415 entry.note.clone(),
416 );
417 }
418 self.body_links(&doc.path, Some(k), &doc.body, &reached);
419 let resources = doc.core.resource.iter().flat_map(Resource::entries);
420 let paths = resources
421 .map(|r| (EdgeKind::Resource, r.as_str(), "describes"))
422 .chain(
423 doc.core
424 .sources
425 .iter()
426 .map(|e| (EdgeKind::Sources, e.resource.as_str(), "derives-from")),
427 );
428 for (kind, written, rel) in paths {
429 if RepoPath::parse(written).is_some() {
430 let to = self.path_target(written);
431 self.edge(&doc.path, kind, written, to, rel, None, None);
432 }
433 }
434 }
435
436 fn body_links(
440 &mut self,
441 from: &RepoPath,
442 knowledge: Option<usize>,
443 body: &Body,
444 reached: &BTreeSet<NodeKey>,
445 ) {
446 let mut seen = reached.clone();
447 for link in &body.links {
448 let Some(Label {
449 store,
450 id: Some(id),
451 ..
452 }) = Label::of(&link.target)
453 else {
454 continue;
455 };
456 let written = match store {
457 Some(s) => format!("{s}:{id}"),
458 None => id.to_string(),
459 };
460 let to = match knowledge.and_then(|k| path_in(self.model, k, store, id)) {
461 Some((_, path)) => NodeKey::Path(path),
462 None => NodeKey::Missing(written.clone()),
463 };
464 if seen.insert(to.clone()) {
465 self.edge(
466 from,
467 EdgeKind::Links,
468 &written,
469 to,
470 "relates-to",
471 None,
472 None,
473 );
474 }
475 }
476 }
477
478 fn include_edges(&mut self, from: &RepoPath, knowledge: Option<usize>, segments: &Segments) {
479 for block in &segments.regions {
480 let (to, region) = match &IncludeTarget::parse(&block.target) {
481 IncludeTarget::Document {
486 store,
487 id,
488 fragment,
489 } => {
490 let to = match knowledge
491 .and_then(|k| path_in(self.model, k, store.as_deref(), id))
492 {
493 Some((_, path)) => {
494 match (fragment.as_deref(), self.model.asset_of(&path)) {
495 (Some(""), _) | (_, None) => NodeKey::Path(path),
496 (_, Some((_, asset))) => NodeKey::Path(asset.path.clone()),
497 }
498 }
499 None => NodeKey::Missing(block.target.clone()),
500 };
501 (to, fragment.clone().filter(|f| !f.is_empty()))
502 }
503 IncludeTarget::File { path, region } => (self.path_target(path), region.clone()),
504 };
505 self.edge(
506 from,
507 EdgeKind::Includes,
508 &block.target,
509 to,
510 "includes",
511 region,
512 None,
513 );
514 }
515 }
516
517 fn finish(mut self) -> Graph {
520 let raw = std::mem::take(&mut self.raw);
521 let edges = link(&mut self.nodes, raw);
522 Graph::new(self.nodes, edges)
523 }
524}
525
526impl Graph {
527 pub fn add_edges(&mut self, raw: Vec<RawEdge>) {
532 let edges = link(&mut self.nodes, raw);
533 self.extend_edges(edges);
534 }
535}
536
537fn target(nodes: &mut BTreeMap<NodeKey, Node>, key: NodeKey) -> NodeKey {
542 let kind = match &key {
543 NodeKey::Path(_) => NodeKind::File,
544 NodeKey::Key(_) => NodeKind::Key,
545 NodeKey::Missing(_) => NodeKind::Missing,
546 };
547 nodes.entry(key.clone()).or_insert_with(|| Node {
548 key: key.clone(),
549 kind,
550 fields: Map::new(),
551 });
552 key
553}
554
555fn link(nodes: &mut BTreeMap<NodeKey, Node>, raw: Vec<RawEdge>) -> Vec<Edge> {
559 type Ends<'e> = (
560 &'e NodeKey,
561 EdgeKind,
562 &'e NodeKey,
563 &'e str,
564 Option<&'e str>,
565 Option<usize>,
566 );
567 fn ends(e: &Edge) -> Ends<'_> {
568 (&e.from, e.kind, &e.to, &e.rel, e.region.as_deref(), e.line)
569 }
570 let mut edges: Vec<Edge> = Vec::with_capacity(raw.len());
571 for e in raw {
572 let to = target(nodes, e.to);
573 let from = target(nodes, NodeKey::Path(e.from));
576 edges.push(Edge {
577 from,
578 kind: e.kind,
579 to,
580 rel: e.rel,
581 region: e.region,
582 line: e.line,
583 synthesised: false,
584 note: e.note,
585 });
586 }
587 let declared: BTreeSet<Ends> = edges.iter().map(ends).collect();
588 let inverses: Vec<Edge> = edges
589 .iter()
590 .map(|e| Edge {
591 from: e.to.clone(),
592 kind: e.kind,
593 to: e.from.clone(),
594 rel: inverse_rel(&e.rel).to_string(),
595 region: e.region.clone(),
596 line: e.line,
597 synthesised: true,
598 note: None,
599 })
600 .filter(|inv| !declared.contains(&ends(inv)))
601 .collect();
602 edges.extend(inverses);
603 edges
604}
605
606#[cfg(test)]
607mod tests;