aboutsummaryrefslogtreecommitdiff
path: root/src/graph.rs
blob: 460bdec7cb6668b6862d9ef5b5feff5bf9baa7a4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
//! The manifest (what was indexed) and the graph built from it.
//!
//! The manifest is a small JSON file.  The graph is rebuilt in memory
//! on every call; with thousands of notes this takes microseconds.

use crate::note::Note;
use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
use std::path::Path;

#[derive(Serialize, Deserialize)]
pub struct FileEntry {
    pub hash: String,
    pub notes: Vec<Note>,
}

#[derive(Default, Serialize, Deserialize)]
pub struct Manifest {
    pub files: BTreeMap<String, FileEntry>,
}

impl Manifest {
    pub fn load(path: &Path) -> Manifest {
        std::fs::read_to_string(path)
            .ok()
            .and_then(|s| serde_json::from_str(&s).ok())
            .unwrap_or_default()
    }

    /// Write through a temporary file so a crash cannot leave half a file.
    pub fn save(&self, path: &Path) -> Result<()> {
        let tmp = path.with_extension("json.tmp");
        std::fs::write(&tmp, serde_json::to_vec(self)?)?;
        std::fs::rename(&tmp, path)?;
        Ok(())
    }
}

/// How a note is reached from the note we started at.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Rel {
    Parent,
    Child,
    Link,
    Backlink,
}

impl Rel {
    pub fn name(self) -> &'static str {
        match self {
            Rel::Parent => "parent",
            Rel::Child => "child",
            Rel::Link => "link",
            Rel::Backlink => "backlink",
        }
    }
}

pub struct Graph {
    pub notes: Vec<Note>,
    by_id: HashMap<String, usize>,
    children: HashMap<String, Vec<usize>>,
    backlinks: HashMap<String, Vec<usize>>,
    pub duplicates: Vec<(String, Vec<usize>)>,
}

impl Graph {
    pub fn build(m: &Manifest) -> Graph {
        let notes: Vec<Note> = m.files.values().flat_map(|f| f.notes.clone()).collect();
        let mut by_id: HashMap<String, usize> = HashMap::new();
        let mut seen: HashMap<String, Vec<usize>> = HashMap::new();
        for (i, n) in notes.iter().enumerate() {
            if let Some(id) = &n.id {
                seen.entry(id.clone()).or_default().push(i);
                by_id.entry(id.clone()).or_insert(i);
            }
        }
        let mut duplicates: Vec<(String, Vec<usize>)> =
            seen.into_iter().filter(|(_, v)| v.len() > 1).collect();
        duplicates.sort();
        let mut children: HashMap<String, Vec<usize>> = HashMap::new();
        let mut backlinks: HashMap<String, Vec<usize>> = HashMap::new();
        for (i, n) in notes.iter().enumerate() {
            if n.id.is_none() {
                continue;
            }
            if let Some(p) = &n.parent {
                children.entry(p.clone()).or_default().push(i);
            }
            for l in &n.links {
                backlinks.entry(l.dst.clone()).or_default().push(i);
            }
        }
        Graph {
            notes,
            by_id,
            children,
            backlinks,
            duplicates,
        }
    }

    pub fn get(&self, id: &str) -> Option<&Note> {
        self.by_id.get(id).map(|&i| &self.notes[i])
    }

    pub fn parent_of(&self, id: &str) -> Option<&Note> {
        self.get(id)
            .and_then(|n| n.parent.as_deref())
            .and_then(|p| self.get(p))
    }

    pub fn children_of(&self, id: &str) -> Vec<&Note> {
        self.idx(self.children.get(id))
    }

    pub fn backlinks_of(&self, id: &str) -> Vec<&Note> {
        self.idx(self.backlinks.get(id))
    }

    pub fn outlinks_of(&self, id: &str) -> Vec<&Note> {
        match self.get(id) {
            Some(n) => n.links.iter().filter_map(|l| self.get(&l.dst)).collect(),
            None => Vec::new(),
        }
    }

    fn idx(&self, v: Option<&Vec<usize>>) -> Vec<&Note> {
        match v {
            Some(v) => v.iter().map(|&i| &self.notes[i]).collect(),
            None => Vec::new(),
        }
    }

    /// Does the note have a link or a backlink or a parent or a child?
    pub fn is_connected(&self, n: &Note) -> bool {
        let id = match &n.id {
            Some(id) => id,
            None => return false,
        };
        n.parent.is_some()
            || !n.links.is_empty()
            || self.children.contains_key(id)
            || self.backlinks.contains_key(id)
    }

    /// Breadth-first search over all relations, ignoring direction.
    /// Returns (note, distance, relation at the first step).
    pub fn reach(&self, id: &str, hops: usize) -> Vec<(&Note, usize, Rel)> {
        let mut out = Vec::new();
        let mut seen: HashSet<&str> = HashSet::new();
        seen.insert(id);
        let mut queue: VecDeque<(&str, usize, Option<Rel>)> = VecDeque::new();
        queue.push_back((id, 0, None));
        while let Some((cur, d, first)) = queue.pop_front() {
            if d == hops {
                continue;
            }
            let mut next: Vec<(&Note, Rel)> = Vec::new();
            if let Some(p) = self.parent_of(cur) {
                next.push((p, Rel::Parent));
            }
            for c in self.children_of(cur) {
                next.push((c, Rel::Child));
            }
            for l in self.outlinks_of(cur) {
                next.push((l, Rel::Link));
            }
            for b in self.backlinks_of(cur) {
                next.push((b, Rel::Backlink));
            }
            for (n, rel) in next {
                let nid = match n.id.as_deref() {
                    Some(x) => x,
                    None => continue,
                };
                if seen.insert(nid) {
                    let r = first.unwrap_or(rel);
                    out.push((n, d + 1, r));
                    queue.push_back((nid, d + 1, Some(r)));
                }
            }
        }
        out
    }
}