Skip to main content

trumly_fs/
lib.rs

1//! The disk adapter: reads a model folder into (path, text) pairs for trumly-core.
2//! Kept apart from the core so the core never touches the filesystem.
3
4pub mod library;
5pub mod pack;
6pub mod telemetry;
7
8use std::fs;
9use std::path::Path;
10
11/// Every `.md` file under `dir` at any depth, as (path relative to `dir` with `/`, text).
12pub fn read_model(dir: &str) -> Result<Vec<(String, String)>, String> {
13    let root = Path::new(dir);
14    let mut out = Vec::new();
15    walk(root, root, &mut out)?;
16    Ok(out)
17}
18
19fn walk(root: &Path, dir: &Path, out: &mut Vec<(String, String)>) -> Result<(), String> {
20    let entries = fs::read_dir(dir).map_err(|e| format!("cannot read {}: {e}", dir.display()))?;
21    for entry in entries {
22        let path = entry.map_err(|e| e.to_string())?.path();
23        if path.is_dir() {
24            walk(root, &path, out)?;
25        } else if path.extension().is_some_and(|e| e == "md") {
26            let rel = path.strip_prefix(root).map_err(|e| e.to_string())?.to_string_lossy().replace('\\', "/");
27            let text = fs::read_to_string(&path).map_err(|e| format!("cannot read {}: {e}", path.display()))?;
28            out.push((rel, text));
29        }
30    }
31    Ok(())
32}
33
34/// Write the result of a core edit (`trumly_core::ops`) into a model folder: changed nodes go where their file already is
35/// (a renamed node stays in the same folder), and the files of deleted ids are removed. Returns (written, removed).
36pub fn apply_edit(dir: &str, edit: &trumly_core::ops::Edit) -> Result<(usize, usize), String> {
37    use std::collections::BTreeMap;
38    let root = Path::new(dir);
39    let mut at: BTreeMap<String, String> = BTreeMap::new();
40    for (rel, text) in read_model(dir)? {
41        if let Ok(n) = trumly_core::parse::parse_node(&text) {
42            at.entry(n.id).or_insert(rel);
43        }
44    }
45    let folder_of = |rel: &str| rel.rsplit_once('/').map(|(d, _)| format!("{d}/")).unwrap_or_default();
46    // a renamed node's new file goes beside the one it replaces
47    for n in &edit.write {
48        let rel = at.get(&n.id).cloned().unwrap_or_else(|| {
49            let beside = edit.renamed.iter().find(|(_, to)| *to == n.id).and_then(|(from, _)| at.get(from)).map(|p| folder_of(p)).unwrap_or_default();
50            format!("{beside}{}.md", n.id)
51        });
52        let path = root.join(&rel);
53        if let Some(parent) = path.parent() {
54            fs::create_dir_all(parent).map_err(|e| format!("cannot create {}: {e}", parent.display()))?;
55        }
56        fs::write(&path, trumly_core::format::node_to_markdown(n)).map_err(|e| format!("cannot write {}: {e}", path.display()))?;
57    }
58    let mut removed = 0;
59    for id in &edit.delete {
60        if let Some(rel) = at.get(id) {
61            if !edit.write.iter().any(|n| at.get(&n.id) == Some(rel)) {
62                fs::remove_file(root.join(rel)).map_err(|e| format!("cannot remove {rel}: {e}"))?;
63                removed += 1;
64            }
65        }
66    }
67    Ok((edit.write.len(), removed))
68}
69
70/// The relative path of the file holding node `id`, if there is one.
71pub fn path_for_id(dir: &str, id: &str) -> Option<String> {
72    read_model(dir).ok()?.into_iter().find(|(_, text)| trumly_core::parse::parse_node(text).is_ok_and(|n| n.id == id)).map(|(rel, _)| rel)
73}
74
75/// A revision for a file's text: it changes whenever the text does. Used so that a writer must have seen
76/// the current version of a node before it may replace it. FNV-1a, so the same text gives the same revision everywhere.
77pub fn rev_of_text(text: &str) -> String {
78    let mut h: u64 = 0xcbf29ce484222325;
79    for b in text.bytes() {
80        h ^= u64::from(b);
81        h = h.wrapping_mul(0x100000001b3);
82    }
83    format!("{h:016x}-{}", text.len())
84}
85
86/// The stricter rule for ids of files we create. A name that works on every system and cannot be
87/// mistaken for another: lower-case letters, digits, `-` and `_`; starts and ends with a letter or digit;
88/// at most 100 characters; not a name Windows reserves (`con`, `nul`, `com1`...); and no `--`, which only a pack's
89/// nodes use as a namespace separator. Files that already exist keep whatever name they have, so older models still open and save.
90pub fn portable_id(id: &str, namespaced: bool) -> bool {
91    const RESERVED: [&str; 4] = ["con", "prn", "aux", "nul"];
92    let edge = |c: char| c.is_ascii_lowercase() || c.is_ascii_digit();
93    let reserved = RESERVED.contains(&id) || ((id.starts_with("com") || id.starts_with("lpt")) && id.len() == 4 && id.as_bytes()[3].is_ascii_digit());
94    !id.is_empty()
95        && id.len() <= 100
96        && id.chars().next().is_some_and(edge)
97        && id.chars().last().is_some_and(edge)
98        && id.chars().all(|c| edge(c) || c == '-' || c == '_')
99        && !reserved
100        && (namespaced || !id.contains("--"))
101}
102
103/// Write a file so that nobody ever reads half of it: write beside it, then rename over it.
104pub fn write_atomically(path: &Path, text: &str) -> std::io::Result<()> {
105    let dir = path.parent().unwrap_or(Path::new("."));
106    let tmp = dir.join(format!(".{}.{}.tmp", path.file_name().unwrap().to_string_lossy(), std::process::id()));
107    fs::write(&tmp, text)?;
108    fs::rename(&tmp, path)
109}