Skip to main content

oxinav_core/
bookmarks.rs

1//! Named directory bookmarks and their on-disk format.
2//!
3//! The store owns the format — parsing and rendering the text — while the
4//! app owns where that text lives and when it is read or written. That split
5//! keeps every rule here testable without a config file to point at.
6
7use std::path::{Path, PathBuf};
8
9/// A directory saved under a user-chosen name.
10#[derive(Debug, Clone, PartialEq, Eq)]
11pub struct Bookmark {
12    pub name: String,
13    pub path: PathBuf,
14}
15
16/// The saved bookmarks, kept sorted by name so the list a user sees is
17/// stable rather than ordered by when things happened to be added.
18#[derive(Debug, Clone, Default, PartialEq, Eq)]
19pub struct Bookmarks {
20    entries: Vec<Bookmark>,
21}
22
23impl Bookmarks {
24    pub fn new() -> Self {
25        Self::default()
26    }
27
28    pub fn list(&self) -> &[Bookmark] {
29        &self.entries
30    }
31
32    pub fn is_empty(&self) -> bool {
33        self.entries.is_empty()
34    }
35
36    /// Save `path` under `name`, replacing any bookmark of that name.
37    ///
38    /// Replacing rather than duplicating means re-saving a name is how you
39    /// move a bookmark, and the list can never hold two entries a user
40    /// cannot tell apart. A blank name is refused.
41    pub fn add(&mut self, name: &str, path: &Path) -> bool {
42        let name = name.trim();
43        if name.is_empty() || name.contains('\t') || name.contains('\n') {
44            return false;
45        }
46
47        self.entries.retain(|b| b.name != name);
48        self.entries.push(Bookmark {
49            name: name.to_string(),
50            path: path.to_path_buf(),
51        });
52        self.entries.sort_by(|a, b| a.name.cmp(&b.name));
53        true
54    }
55
56    pub fn remove(&mut self, name: &str) -> bool {
57        let before = self.entries.len();
58        self.entries.retain(|b| b.name != name);
59        self.entries.len() != before
60    }
61
62    pub fn resolve(&self, name: &str) -> Option<&Path> {
63        self.entries
64            .iter()
65            .find(|b| b.name == name)
66            .map(|b| b.path.as_path())
67    }
68
69    /// Render for storage: one `name<TAB>path` per line.
70    ///
71    /// Tab-separated rather than anything richer because a path may contain
72    /// almost any character but not a tab or newline, so no escaping — and
73    /// therefore no escaping bugs — is needed.
74    pub fn to_text(&self) -> String {
75        let mut out = String::new();
76        for entry in &self.entries {
77            out.push_str(&entry.name);
78            out.push('\t');
79            out.push_str(&entry.path.to_string_lossy());
80            out.push('\n');
81        }
82        out
83    }
84
85    /// Parse stored text. Malformed lines are skipped rather than failing the
86    /// whole file: a corrupt line should cost one bookmark, not all of them.
87    pub fn from_text(text: &str) -> Self {
88        let mut store = Self::new();
89        for line in text.lines() {
90            let line = line.trim_end_matches('\r');
91            if line.trim().is_empty() {
92                continue;
93            }
94            if let Some((name, path)) = line.split_once('\t') {
95                if !name.trim().is_empty() && !path.is_empty() {
96                    store.add(name, Path::new(path));
97                }
98            }
99        }
100        store
101    }
102}
103
104#[cfg(test)]
105mod tests {
106    use super::*;
107
108    fn names(store: &Bookmarks) -> Vec<&str> {
109        store.list().iter().map(|b| b.name.as_str()).collect()
110    }
111
112    #[test]
113    fn add_then_resolve_returns_the_path() {
114        let mut store = Bookmarks::new();
115        assert!(store.add("code", Path::new("/home/me/code")));
116
117        assert_eq!(store.resolve("code"), Some(Path::new("/home/me/code")));
118    }
119
120    #[test]
121    fn resolve_is_none_for_an_unknown_name() {
122        let store = Bookmarks::new();
123        assert_eq!(store.resolve("nope"), None);
124    }
125
126    #[test]
127    fn adding_the_same_name_moves_it_rather_than_duplicating() {
128        let mut store = Bookmarks::new();
129        store.add("work", Path::new("/old"));
130        store.add("work", Path::new("/new"));
131
132        assert_eq!(store.list().len(), 1);
133        assert_eq!(store.resolve("work"), Some(Path::new("/new")));
134    }
135
136    #[test]
137    fn entries_are_listed_sorted_by_name() {
138        let mut store = Bookmarks::new();
139        store.add("zed", Path::new("/z"));
140        store.add("alpha", Path::new("/a"));
141        store.add("mid", Path::new("/m"));
142
143        assert_eq!(names(&store), vec!["alpha", "mid", "zed"]);
144    }
145
146    #[test]
147    fn blank_and_separator_bearing_names_are_refused() {
148        let mut store = Bookmarks::new();
149
150        assert!(!store.add("   ", Path::new("/a")));
151        // A tab or newline would break the stored line format.
152        assert!(!store.add("a\tb", Path::new("/a")));
153        assert!(!store.add("a\nb", Path::new("/a")));
154        assert!(store.is_empty());
155    }
156
157    #[test]
158    fn names_are_trimmed_on_the_way_in() {
159        let mut store = Bookmarks::new();
160        store.add("  code  ", Path::new("/c"));
161
162        assert_eq!(names(&store), vec!["code"]);
163    }
164
165    #[test]
166    fn remove_reports_whether_anything_went() {
167        let mut store = Bookmarks::new();
168        store.add("code", Path::new("/c"));
169
170        assert!(store.remove("code"));
171        assert!(!store.remove("code"));
172        assert!(store.is_empty());
173    }
174
175    #[test]
176    fn text_round_trips() {
177        let mut store = Bookmarks::new();
178        store.add("code", Path::new("/home/me/code"));
179        store.add("docs", Path::new("/home/me/My Documents"));
180
181        let restored = Bookmarks::from_text(&store.to_text());
182
183        assert_eq!(restored, store);
184    }
185
186    #[test]
187    fn paths_with_spaces_survive_the_round_trip() {
188        let mut store = Bookmarks::new();
189        store.add("space", Path::new("/a b/c d"));
190
191        let restored = Bookmarks::from_text(&store.to_text());
192        assert_eq!(restored.resolve("space"), Some(Path::new("/a b/c d")));
193    }
194
195    #[test]
196    fn malformed_lines_cost_only_themselves() {
197        let text = "good\t/a\nno-tab-here\n\ngood2\t/b\n\t/missing-name\n";
198        let store = Bookmarks::from_text(text);
199
200        assert_eq!(names(&store), vec!["good", "good2"]);
201    }
202
203    #[test]
204    fn carriage_returns_are_tolerated() {
205        let store = Bookmarks::from_text("code\t/c\r\ndocs\t/d\r\n");
206        assert_eq!(names(&store), vec!["code", "docs"]);
207    }
208
209    #[test]
210    fn empty_text_parses_to_an_empty_store() {
211        assert!(Bookmarks::from_text("").is_empty());
212    }
213}