Skip to main content

trumly_core/
load.rs

1//! Builds a `Graph` from a set of files. Still pure: the caller reads the files and hands us
2//! (path, text) pairs, so this works the same from the CLI, a test, or WASM in a browser.
3
4use crate::model::Graph;
5use crate::parse::parse_node;
6
7/// One file that could not be loaded, and why.
8#[derive(Debug, Clone, PartialEq, Eq)]
9pub struct LoadError {
10    /// Path relative to the model root, with `/` separators.
11    pub file: String, // path relative to the model root, with `/` separators
12    /// The name used in `check --json`, for example `missing_id`.
13    pub kind: &'static str,
14}
15
16/// The filename without the directory and without `.md`: "sub/a.md" -> "a".
17fn stem(path: &str) -> &str {
18    let name = path.rsplit('/').next().unwrap_or(path);
19    name.strip_suffix(".md").unwrap_or(name)
20}
21
22/// Notes that live next to a model: any `README.md`, and anything whose name or folder starts with a dot.
23pub fn ignored(path: &str) -> bool {
24    let mut parts = path.split('/');
25    path.rsplit('/').next() == Some("README.md") || parts.any(|p| p.starts_with('.'))
26}
27
28/// Load every `.md` file. Files that fail are reported and skipped; the rest still load.
29pub fn load(mut files: Vec<(String, String)>) -> (Graph, Vec<LoadError>) {
30    // Sorted by path so "first wins" for duplicate ids is the same on every machine.
31    files.sort_by(|a, b| a.0.cmp(&b.0));
32    files.retain(|(path, _)| path.ends_with(".md") && !ignored(path));
33
34    let mut graph = Graph::new();
35    let mut errors = Vec::new();
36
37    for (path, text) in files {
38        let kind = match parse_node(&text) {
39            Err(e) => Some(e.as_str()),
40            Ok(node) if node.id != stem(&path) => Some("id_filename_mismatch"),
41            // `insert` hands the node back unused when the id is taken, so we ask it first.
42            Ok(node) => graph.insert(node).err().map(|_| "duplicate_id"),
43        };
44        if let Some(kind) = kind {
45            errors.push(LoadError { file: path, kind });
46        }
47    }
48    errors.sort_by(|a, b| (&a.file, a.kind).cmp(&(&b.file, b.kind)));
49    (graph, errors)
50}
51