use std::collections::{BTreeMap, BTreeSet, HashSet};
use serde_json::{Map, Value};
use super::{Edge, EdgeKind, Graph, Hydrator, Node, NodeKey, NodeKind, model::ancestors};
use crate::{
Document, FileKind, Model, RepoPath, Segments, Yaml,
markdown::{Body, IncludeTarget},
model::{frontmatter::Resource, keys::Label},
yaml::Spanned,
};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Target {
Document {
path: RepoPath,
id: String,
knowledge: usize,
},
File(RepoPath),
}
pub fn resolve_to(model: &Model, knowledge: usize, to: &str) -> Option<Target> {
if !to.starts_with('/') {
let (store, id) = crate::model::split_store(to);
let (k, path) = path_in(model, knowledge, store, id)?;
return Some(Target::Document {
path,
id: id.to_string(),
knowledge: k,
});
}
let path = RepoPath::parse(to)?;
if let Some((k, id)) = model.id_of(&path) {
return Some(Target::Document {
path,
id,
knowledge: k,
});
}
model.exists(&path).then_some(Target::File(path))
}
fn path_in(
model: &Model,
citing: usize,
store: Option<&str>,
id: &str,
) -> Option<(usize, RepoPath)> {
let k = match store {
None => citing,
Some(s) => model.store(citing, s)?.knowledge,
};
model.path_of_id(k, id).map(|p| (k, p))
}
#[expect(
clippy::match_same_arms,
reason = "the arm for `relates-to` repeats the wildcard's value, so that the list names every inverse that SOKF_FORMAT_116 gives"
)]
pub fn inverse_rel(rel: &str) -> &'static str {
match rel {
"relates-to" => "relates-to",
"part-of" => "has-part",
"has-part" => "part-of",
"depends-on" => "depended-on-by",
"depended-on-by" => "depends-on",
"references" => "referenced-by",
"referenced-by" => "references",
"supersedes" => "superseded-by",
"superseded-by" => "supersedes",
"implements" => "implemented-by",
"implemented-by" => "implements",
"tests" => "tested-by",
"tested-by" => "tests",
"contradicts" => "contradicts",
"describes" => "described-by",
"described-by" => "describes",
"derives-from" => "derived-by",
"derived-by" => "derives-from",
"includes" => "included-by",
"included-by" => "includes",
_ => "relates-to",
}
}
pub fn frontmatter_json(doc: &Document) -> Map<String, Value> {
let mut fields = Map::new();
if let Some(entries) = doc.frontmatter.as_ref().and_then(Spanned::as_map) {
for (key, value) in entries {
if matches!(
key.value.as_str(),
"links" | "kind" | "path" | "broken" | "reason"
) {
continue;
}
fields.insert(key.value.clone(), yaml_json(value));
}
}
if !fields.contains_key("status") {
fields.insert("status".into(), Value::from("stable"));
}
let reason = if doc.frontmatter.is_none() && doc.frontmatter_found {
Some("frontmatter does not parse")
} else if doc.id().is_none() {
Some("no id")
} else {
None
};
if let Some(reason) = reason {
fields.insert("broken".into(), Value::Bool(true));
fields.insert("reason".into(), Value::from(reason));
}
fields
}
pub(crate) fn yaml_json(value: &Spanned) -> Value {
match &value.value {
Yaml::Null => Value::Null,
Yaml::Bool(b) => Value::Bool(*b),
Yaml::Int(i) => Value::from(*i),
Yaml::Float(f) => serde_json::Number::from_f64(*f).map_or(Value::Null, Value::Number),
Yaml::Str(s) => Value::from(s.as_str()),
Yaml::Seq(items) => Value::Array(items.iter().map(yaml_json).collect()),
Yaml::Map(entries) => Value::Object(
entries
.iter()
.map(|(k, v)| (k.value.clone(), yaml_json(v)))
.collect(),
),
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct RawEdge {
pub from: RepoPath,
pub kind: EdgeKind,
pub written: String,
pub to: NodeKey,
pub rel: String,
pub region: Option<String>,
pub line: Option<usize>,
pub note: Option<String>,
}
pub fn edges_of(model: &Model, path: &RepoPath) -> Vec<RawEdge> {
let mut b = Builder::new(model);
if let Some((k, doc)) = model.loaded_document(path) {
b.document_edges(k, doc);
b.include_edges(&doc.path, Some(k), &doc.segments);
return b.raw;
}
if let Some(crate::Located::Additional(file)) = model.by_path(path) {
b.body_links(&file.path, None, &file.body, &BTreeSet::new());
b.include_edges(&file.path, file.schema.map(|s| s.knowledge), &file.segments);
}
b.raw
}
pub fn build(model: &Model) -> Graph {
build_from(model, declared_edges(model), None)
}
pub(super) fn declared_edges(model: &Model) -> Vec<RawEdge> {
model
.documents_and_schemas()
.map(|(_, d)| &d.path)
.chain(model.additional.iter().map(|a| &a.path))
.flat_map(|p| edges_of(model, p))
.collect()
}
pub fn build_from(model: &Model, edges: Vec<RawEdge>, hydrator: Option<Hydrator>) -> Graph {
let mut b = Builder::new(model);
let mut built: HashSet<NodeKey> = HashSet::new();
for knowledge in &model.knowledges {
let mut fields = Map::new();
if let Some(m) = &knowledge.manifest {
for (key, value) in [
("name", &m.name),
("scope", &m.scope),
("description", &m.description),
] {
if let Some(value) = value {
fields.insert(key.into(), Value::from(value.as_str()));
}
}
}
b.insert(knowledge.root.clone(), NodeKind::Root, fields);
}
for file in &model.tree.files {
if !matches!(file.kind, FileKind::Document | FileKind::Schema) {
continue;
}
let Some(k) = file.root else { continue };
let fields = match model.loaded_document(&file.path) {
Some((_, doc)) => {
built.insert(NodeKey::Path(file.path.clone()));
frontmatter_json(doc)
}
None => Map::new(),
};
b.insert(file.path.clone(), NodeKind::Document, fields);
b.directories(&file.path, &model.knowledges[k].root);
}
for (path, schema) in &model.dispatch {
let mut fields = Map::new();
if let Some(r) = schema {
fields.insert("schema".into(), Value::from(model.schema(*r).id()));
}
b.insert(path.clone(), NodeKind::Additional, fields);
if let Some(k) = model.knowledge_of(path) {
b.directories(path, &model.knowledges[k].root);
}
}
for knowledge in &model.knowledges {
for asset in &knowledge.assets {
let mut fields = Map::new();
let sidecar = asset.sidecar_path();
let id = match asset.sidecar {
Some(i) => knowledge.documents[i].id().map(str::to_string),
None if asset.has_sidecar => model
.fallback
.as_ref()
.and_then(|f| f.fields(&sidecar))
.and_then(|f| f.id),
None => None,
};
if let Some(id) = id {
fields.insert("sidecar".into(), Value::from(id));
}
b.insert(asset.path.clone(), NodeKind::Asset, fields);
b.directories(&asset.path, &knowledge.root);
}
}
b.raw.extend(edges);
let graph = b.finish();
match hydrator {
Some(h) => graph.with_hydrator(h, built),
None => graph,
}
}
struct Builder<'a> {
model: &'a Model,
nodes: BTreeMap<NodeKey, Node>,
raw: Vec<RawEdge>,
}
impl<'a> Builder<'a> {
fn new(model: &'a Model) -> Self {
Builder {
model,
nodes: BTreeMap::new(),
raw: Vec::new(),
}
}
fn insert(&mut self, path: RepoPath, kind: NodeKind, fields: Map<String, Value>) {
let key = NodeKey::Path(path);
self.nodes.insert(key.clone(), Node { key, kind, fields });
}
fn directories(&mut self, path: &RepoPath, root: &RepoPath) {
for d in ancestors(path).take_while(|d| d != root && d.starts_with(root)) {
let key = NodeKey::Path(d);
self.nodes.entry(key.clone()).or_insert_with(|| Node {
key,
kind: NodeKind::Directory,
fields: Map::new(),
});
}
}
#[allow(clippy::too_many_arguments)]
fn edge(
&mut self,
from: &RepoPath,
kind: EdgeKind,
written: &str,
to: NodeKey,
rel: &str,
region: Option<String>,
note: Option<String>,
) {
self.raw.push(RawEdge {
from: from.clone(),
kind,
written: written.to_string(),
to,
rel: rel.to_string(),
region,
line: None,
note,
});
}
fn path_target(&self, written: &str) -> NodeKey {
match RepoPath::parse(written) {
Some(p) if self.model.exists(&p) => NodeKey::Path(p),
_ => NodeKey::Missing(written.to_string()),
}
}
fn document_edges(&mut self, k: usize, doc: &Document) {
let mut reached = BTreeSet::new();
for entry in &doc.core.links {
let to = match resolve_to(self.model, k, &entry.to) {
Some(Target::Document { path: p, .. } | Target::File(p)) => NodeKey::Path(p),
None => NodeKey::Missing(entry.to.clone()),
};
reached.insert(to.clone());
self.edge(
&doc.path,
EdgeKind::Links,
&entry.to,
to,
&entry.rel,
None,
entry.note.clone(),
);
}
self.body_links(&doc.path, Some(k), &doc.body, &reached);
let resources = doc.core.resource.iter().flat_map(Resource::entries);
let paths = resources
.map(|r| (EdgeKind::Resource, r.as_str(), "describes"))
.chain(
doc.core
.sources
.iter()
.map(|e| (EdgeKind::Sources, e.resource.as_str(), "derives-from")),
);
for (kind, written, rel) in paths {
if RepoPath::parse(written).is_some() {
let to = self.path_target(written);
self.edge(&doc.path, kind, written, to, rel, None, None);
}
}
}
fn body_links(
&mut self,
from: &RepoPath,
knowledge: Option<usize>,
body: &Body,
reached: &BTreeSet<NodeKey>,
) {
let mut seen = reached.clone();
for link in &body.links {
let Some(Label {
store,
id: Some(id),
..
}) = Label::of(&link.target)
else {
continue;
};
let written = match store {
Some(s) => format!("{s}:{id}"),
None => id.to_string(),
};
let to = match knowledge.and_then(|k| path_in(self.model, k, store, id)) {
Some((_, path)) => NodeKey::Path(path),
None => NodeKey::Missing(written.clone()),
};
if seen.insert(to.clone()) {
self.edge(
from,
EdgeKind::Links,
&written,
to,
"relates-to",
None,
None,
);
}
}
}
fn include_edges(&mut self, from: &RepoPath, knowledge: Option<usize>, segments: &Segments) {
for block in &segments.regions {
let (to, region) = match &IncludeTarget::parse(&block.target) {
IncludeTarget::Document {
store,
id,
fragment,
} => {
let to = match knowledge
.and_then(|k| path_in(self.model, k, store.as_deref(), id))
{
Some((_, path)) => {
match (fragment.as_deref(), self.model.asset_of(&path)) {
(Some(""), _) | (_, None) => NodeKey::Path(path),
(_, Some((_, asset))) => NodeKey::Path(asset.path.clone()),
}
}
None => NodeKey::Missing(block.target.clone()),
};
(to, fragment.clone().filter(|f| !f.is_empty()))
}
IncludeTarget::File { path, region } => (self.path_target(path), region.clone()),
};
self.edge(
from,
EdgeKind::Includes,
&block.target,
to,
"includes",
region,
None,
);
}
}
fn finish(mut self) -> Graph {
let raw = std::mem::take(&mut self.raw);
let edges = link(&mut self.nodes, raw);
Graph::new(self.nodes, edges)
}
}
impl Graph {
pub fn add_edges(&mut self, raw: Vec<RawEdge>) {
let edges = link(&mut self.nodes, raw);
self.extend_edges(edges);
}
}
fn target(nodes: &mut BTreeMap<NodeKey, Node>, key: NodeKey) -> NodeKey {
let kind = match &key {
NodeKey::Path(_) => NodeKind::File,
NodeKey::Key(_) => NodeKind::Key,
NodeKey::Missing(_) => NodeKind::Missing,
};
nodes.entry(key.clone()).or_insert_with(|| Node {
key: key.clone(),
kind,
fields: Map::new(),
});
key
}
fn link(nodes: &mut BTreeMap<NodeKey, Node>, raw: Vec<RawEdge>) -> Vec<Edge> {
type Ends<'e> = (
&'e NodeKey,
EdgeKind,
&'e NodeKey,
&'e str,
Option<&'e str>,
Option<usize>,
);
fn ends(e: &Edge) -> Ends<'_> {
(&e.from, e.kind, &e.to, &e.rel, e.region.as_deref(), e.line)
}
let mut edges: Vec<Edge> = Vec::with_capacity(raw.len());
for e in raw {
let to = target(nodes, e.to);
let from = target(nodes, NodeKey::Path(e.from));
edges.push(Edge {
from,
kind: e.kind,
to,
rel: e.rel,
region: e.region,
line: e.line,
synthesised: false,
note: e.note,
});
}
let declared: BTreeSet<Ends> = edges.iter().map(ends).collect();
let inverses: Vec<Edge> = edges
.iter()
.map(|e| Edge {
from: e.to.clone(),
kind: e.kind,
to: e.from.clone(),
rel: inverse_rel(&e.rel).to_string(),
region: e.region.clone(),
line: e.line,
synthesised: true,
note: None,
})
.filter(|inv| !declared.contains(&ends(inv)))
.collect();
edges.extend(inverses);
edges
}
#[cfg(test)]
mod tests;