1pub mod library;
5pub mod pack;
6pub mod telemetry;
7
8use std::fs;
9use std::path::Path;
10
11pub 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
34pub 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 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
70pub 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
75pub 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
86pub 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
103pub 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}