use std::{
collections::{BTreeMap, HashMap, HashSet},
rc::Rc,
};
use serde_json::{Map, Value};
use crate::RepoPath;
pub type Fields = Map<String, Value>;
pub type Hydrate = dyn Fn(&RepoPath) -> Option<Fields>;
#[derive(Clone)]
pub struct Hydrator(pub Rc<Hydrate>);
impl std::fmt::Debug for Hydrator {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("Hydrator")
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum NodeKey {
Path(RepoPath),
Key(String),
Missing(String),
}
impl NodeKey {
pub fn as_str(&self) -> &str {
match self {
NodeKey::Path(p) => p.as_str(),
NodeKey::Key(t) | NodeKey::Missing(t) => t,
}
}
pub fn path(&self) -> Option<&RepoPath> {
match self {
NodeKey::Path(p) => Some(p),
NodeKey::Key(_) | NodeKey::Missing(_) => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum NodeKind {
Root,
Directory,
Document,
Additional,
Asset,
File,
Key,
Missing,
}
impl NodeKind {
pub(super) fn shows_via(self) -> bool {
matches!(
self,
NodeKind::File | NodeKind::Additional | NodeKind::Asset | NodeKind::Directory
)
}
pub fn name(self) -> &'static str {
match self {
NodeKind::Root => "root",
NodeKind::Directory => "directory",
NodeKind::Document => "document",
NodeKind::Additional => "additional",
NodeKind::Asset => "asset",
NodeKind::File => "file",
NodeKind::Key => "key",
NodeKind::Missing => "missing",
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Node {
pub key: NodeKey,
pub kind: NodeKind,
pub fields: Map<String, Value>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum EdgeKind {
Includes,
Keys,
Links,
Marker,
Resource,
Sources,
}
impl EdgeKind {
pub fn name(self) -> &'static str {
match self {
EdgeKind::Includes => "includes",
EdgeKind::Keys => "keys",
EdgeKind::Links => "links",
EdgeKind::Marker => "marker",
EdgeKind::Resource => "resource",
EdgeKind::Sources => "sources",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Edge {
pub from: NodeKey,
pub kind: EdgeKind,
pub to: NodeKey,
pub rel: String,
pub region: Option<String>,
pub line: Option<usize>,
pub synthesised: bool,
pub note: Option<String>,
}
fn inverse(kind: EdgeKind, rel: &str) -> &'static str {
match (kind, rel) {
(EdgeKind::Keys, "defined-in") => "defines",
(EdgeKind::Keys, "defines") => "defined-in",
(EdgeKind::Keys, "cites") => "cited-by",
(EdgeKind::Keys, _) => "cites",
_ => super::inverse_rel(rel),
}
}
#[derive(Debug, Clone, Default)]
pub struct Graph {
pub nodes: BTreeMap<NodeKey, Node>,
pub edges: Vec<Edge>,
out: HashMap<NodeKey, Vec<usize>>,
inbound: HashMap<NodeKey, Vec<usize>>,
hydrator: Option<Hydrator>,
hydrated: HashSet<NodeKey>,
archived: HashSet<NodeKey>,
}
impl Graph {
pub fn new(nodes: BTreeMap<NodeKey, Node>, mut edges: Vec<Edge>) -> Graph {
edges.sort();
edges.dedup();
let mut out: HashMap<NodeKey, Vec<usize>> = HashMap::new();
let mut inbound: HashMap<NodeKey, Vec<usize>> = HashMap::new();
for (i, e) in edges.iter().enumerate() {
out.entry(e.from.clone()).or_default().push(i);
inbound.entry(e.to.clone()).or_default().push(i);
}
Graph {
nodes,
edges,
out,
inbound,
hydrator: None,
hydrated: HashSet::new(),
archived: HashSet::new(),
}
}
pub fn set_archived(&mut self, paths: impl IntoIterator<Item = RepoPath>) {
self.archived = paths.into_iter().map(NodeKey::Path).collect();
}
pub fn is_archived(&self, key: &NodeKey) -> bool {
self.archived.contains(key)
}
pub fn add_key(
&mut self,
path: &RepoPath,
slug: &str,
key: &str,
line: usize,
citing: &[RepoPath],
) {
let node = NodeKey::Key(format!("{path}#{slug}"));
let mut fields = Map::new();
fields.insert("key".into(), Value::from(key));
fields.insert("line".into(), Value::from(line));
self.nodes.insert(
node.clone(),
Node {
key: node.clone(),
kind: NodeKind::Key,
fields,
},
);
let doc = NodeKey::Path(path.clone());
let pair = |from: &NodeKey, to: &NodeKey, rel: &str| {
[false, true].map(|synthesised| {
let (from, to, rel) = if synthesised {
(to, from, inverse(EdgeKind::Keys, rel))
} else {
(from, to, rel)
};
Edge {
from: from.clone(),
kind: EdgeKind::Keys,
to: to.clone(),
rel: rel.to_string(),
region: None,
line: None,
synthesised,
note: None,
}
})
};
let mut edges: Vec<Edge> = pair(&node, &doc, "defined-in").into();
for source in citing {
edges.extend(pair(&NodeKey::Path(source.clone()), &node, "cites"));
}
self.extend_edges(edges);
}
pub(super) fn extend_edges(&mut self, edges: Vec<Edge>) {
let mut all = std::mem::take(&mut self.edges);
all.extend(edges);
let rebuilt = Graph::new(BTreeMap::new(), all);
self.edges = rebuilt.edges;
self.out = rebuilt.out;
self.inbound = rebuilt.inbound;
}
pub fn with_hydrator(mut self, hydrator: Hydrator, built: HashSet<NodeKey>) -> Graph {
self.hydrator = Some(hydrator);
self.hydrated = built;
self
}
pub fn hydrate(&mut self, key: &NodeKey) {
let Some(hydrator) = &self.hydrator else {
return;
};
if self.hydrated.contains(key) {
return;
}
let Some(node) = self.nodes.get_mut(key) else {
return;
};
if node.kind != NodeKind::Document {
return;
}
if let Some(path) = key.path()
&& let Some(fields) = (hydrator.0)(path)
{
node.fields = fields;
}
self.hydrated.insert(key.clone());
}
pub fn node(&self, key: &NodeKey) -> Option<&Node> {
self.nodes.get(key)
}
pub fn kind(&self, key: &NodeKey) -> Option<NodeKind> {
self.nodes.get(key).map(|n| n.kind)
}
pub fn edges_from(&self, key: &NodeKey) -> impl Iterator<Item = &Edge> {
self.edge_indices_from(key).iter().map(|&i| &self.edges[i])
}
pub fn edge_indices_from(&self, key: &NodeKey) -> &[usize] {
self.out.get(key).map(Vec::as_slice).unwrap_or(&[])
}
pub fn inverse_indices(&self, edge: &Edge) -> impl Iterator<Item = usize> {
self.inbound
.get(&edge.from)
.into_iter()
.flatten()
.copied()
.filter(move |&i| {
let other = &self.edges[i];
other.from == edge.to
&& other.kind == edge.kind
&& other.region == edge.region
&& other.line == edge.line
&& (other.rel == inverse(edge.kind, &edge.rel)
|| inverse(other.kind, &other.rel) == edge.rel)
})
}
pub fn parent(key: &NodeKey) -> Option<NodeKey> {
key.path()?.parent().map(NodeKey::Path)
}
pub fn ensure(&mut self, path: RepoPath, kind: NodeKind) {
let key = NodeKey::Path(path);
self.nodes
.entry(key.clone())
.and_modify(|n| n.kind = kind)
.or_insert_with(|| Node {
key,
kind,
fields: Map::new(),
});
}
}
pub(super) fn ancestors(path: &RepoPath) -> impl Iterator<Item = RepoPath> {
std::iter::successors(path.parent(), RepoPath::parent)
}
#[cfg(test)]
mod tests {
use super::*;
fn p(s: &str) -> NodeKey {
NodeKey::Path(RepoPath::parse(s).unwrap())
}
fn edge(from: &NodeKey, kind: EdgeKind, to: &NodeKey, rel: &str, synthesised: bool) -> Edge {
Edge {
from: from.clone(),
kind,
to: to.clone(),
rel: rel.into(),
region: None,
line: None,
synthesised,
note: None,
}
}
#[test]
fn keys_order_paths_before_missing_targets() {
let mut keys = vec![
NodeKey::Missing("a".into()),
p("/z.md"),
p("/a.md"),
NodeKey::Missing("b".into()),
];
keys.sort();
assert_eq!(
keys,
vec![
p("/a.md"),
p("/z.md"),
NodeKey::Missing("a".into()),
NodeKey::Missing("b".into())
]
);
assert_eq!(p("/a.md").as_str(), "/a.md");
assert_eq!(NodeKey::Missing("x".into()).as_str(), "x");
assert!(NodeKey::Missing("x".into()).path().is_none());
assert_eq!(Graph::parent(&p("/k/a.md")), Some(p("/k")));
assert_eq!(Graph::parent(&p("/")), None);
assert_eq!(Graph::parent(&NodeKey::Missing("x".into())), None);
}
#[test]
fn edges_sort_by_from_kind_to_rel_region_note_and_dedup() {
let a = p("/a.md");
let b = p("/b.md");
let m = NodeKey::Missing("m".into());
let mut edges = vec![
edge(&b, EdgeKind::Links, &a, "depends-on", false),
edge(&a, EdgeKind::Resource, &b, "describes", false),
edge(&a, EdgeKind::Links, &m, "references", false),
edge(&a, EdgeKind::Links, &b, "references", false),
edge(&a, EdgeKind::Includes, &b, "includes", false),
edge(&a, EdgeKind::Links, &b, "depends-on", false),
edge(&a, EdgeKind::Links, &b, "depends-on", false),
];
let g = Graph::new(BTreeMap::new(), std::mem::take(&mut edges));
let shown: Vec<String> = g
.edges
.iter()
.map(|e| {
format!(
"{} {} {} {}",
e.from.as_str(),
e.kind.name(),
e.to.as_str(),
e.rel
)
})
.collect();
assert_eq!(
shown,
vec![
"/a.md includes /b.md includes",
"/a.md links /b.md depends-on",
"/a.md links /b.md references",
"/a.md links m references",
"/a.md resource /b.md describes",
"/b.md links /a.md depends-on",
]
);
assert_eq!(g.edges_from(&a).count(), 5);
assert_eq!(g.edge_indices_from(&b), &[5]);
assert!(g.edge_indices_from(&m).is_empty());
assert_eq!(EdgeKind::Sources.name(), "sources");
}
#[test]
fn inverses_find_the_declared_or_synthesised_side_and_every_custom_rel() {
let a = p("/a.md");
let b = p("/b.md");
let c = p("/c.md");
let g = Graph::new(
BTreeMap::new(),
vec![
edge(&a, EdgeKind::Links, &b, "depends-on", false),
edge(&b, EdgeKind::Links, &a, "depended-on-by", true),
edge(&a, EdgeKind::Links, &c, "likes", false),
edge(&a, EdgeKind::Links, &c, "hates", false),
edge(&c, EdgeKind::Links, &a, "relates-to", false),
edge(&b, EdgeKind::Resource, &c, "describes", false),
],
);
let rels = |e: &Edge| {
g.inverse_indices(e)
.map(|i| g.edges[i].rel.clone())
.collect::<Vec<_>>()
};
let declared = &g.edges[g.edge_indices_from(&a)[0]];
assert_eq!(declared.rel, "depends-on");
assert_eq!(rels(declared), vec!["depended-on-by"]);
let relates = g.edges.iter().find(|e| e.rel == "relates-to").unwrap();
assert_eq!(rels(relates), vec!["hates", "likes"]);
let custom = g.edges.iter().find(|e| e.rel == "likes").unwrap();
assert_eq!(rels(custom), vec!["relates-to"]);
let lone = g.edges.iter().find(|e| e.rel == "describes").unwrap();
assert_eq!(rels(lone), Vec::<String>::new());
}
#[test]
fn ensure_adds_or_rekinds_a_node() {
let mut g = Graph::default();
let path = RepoPath::parse("/src").unwrap();
g.ensure(path.clone(), NodeKind::File);
assert_eq!(g.kind(&p("/src")), Some(NodeKind::File));
g.ensure(path, NodeKind::Directory);
assert_eq!(g.kind(&p("/src")), Some(NodeKind::Directory));
assert_eq!(g.nodes.len(), 1);
assert!(g.node(&p("/nope")).is_none());
assert_eq!(NodeKind::Additional.name(), "additional");
}
}