oxinav-core 0.2.0

Core logic for OxiNav: file operations, pane state, archives and viewing, with no UI dependency
Documentation
//! Named directory bookmarks and their on-disk format.
//!
//! The store owns the format — parsing and rendering the text — while the
//! app owns where that text lives and when it is read or written. That split
//! keeps every rule here testable without a config file to point at.

use std::path::{Path, PathBuf};

/// A directory saved under a user-chosen name.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Bookmark {
    pub name: String,
    pub path: PathBuf,
}

/// The saved bookmarks, kept sorted by name so the list a user sees is
/// stable rather than ordered by when things happened to be added.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Bookmarks {
    entries: Vec<Bookmark>,
}

impl Bookmarks {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn list(&self) -> &[Bookmark] {
        &self.entries
    }

    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Save `path` under `name`, replacing any bookmark of that name.
    ///
    /// Replacing rather than duplicating means re-saving a name is how you
    /// move a bookmark, and the list can never hold two entries a user
    /// cannot tell apart. A blank name is refused.
    pub fn add(&mut self, name: &str, path: &Path) -> bool {
        let name = name.trim();
        if name.is_empty() || name.contains('\t') || name.contains('\n') {
            return false;
        }

        self.entries.retain(|b| b.name != name);
        self.entries.push(Bookmark {
            name: name.to_string(),
            path: path.to_path_buf(),
        });
        self.entries.sort_by(|a, b| a.name.cmp(&b.name));
        true
    }

    pub fn remove(&mut self, name: &str) -> bool {
        let before = self.entries.len();
        self.entries.retain(|b| b.name != name);
        self.entries.len() != before
    }

    pub fn resolve(&self, name: &str) -> Option<&Path> {
        self.entries
            .iter()
            .find(|b| b.name == name)
            .map(|b| b.path.as_path())
    }

    /// Render for storage: one `name<TAB>path` per line.
    ///
    /// Tab-separated rather than anything richer because a path may contain
    /// almost any character but not a tab or newline, so no escaping — and
    /// therefore no escaping bugs — is needed.
    pub fn to_text(&self) -> String {
        let mut out = String::new();
        for entry in &self.entries {
            out.push_str(&entry.name);
            out.push('\t');
            out.push_str(&entry.path.to_string_lossy());
            out.push('\n');
        }
        out
    }

    /// Parse stored text. Malformed lines are skipped rather than failing the
    /// whole file: a corrupt line should cost one bookmark, not all of them.
    pub fn from_text(text: &str) -> Self {
        let mut store = Self::new();
        for line in text.lines() {
            let line = line.trim_end_matches('\r');
            if line.trim().is_empty() {
                continue;
            }
            if let Some((name, path)) = line.split_once('\t') {
                if !name.trim().is_empty() && !path.is_empty() {
                    store.add(name, Path::new(path));
                }
            }
        }
        store
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn names(store: &Bookmarks) -> Vec<&str> {
        store.list().iter().map(|b| b.name.as_str()).collect()
    }

    #[test]
    fn add_then_resolve_returns_the_path() {
        let mut store = Bookmarks::new();
        assert!(store.add("code", Path::new("/home/me/code")));

        assert_eq!(store.resolve("code"), Some(Path::new("/home/me/code")));
    }

    #[test]
    fn resolve_is_none_for_an_unknown_name() {
        let store = Bookmarks::new();
        assert_eq!(store.resolve("nope"), None);
    }

    #[test]
    fn adding_the_same_name_moves_it_rather_than_duplicating() {
        let mut store = Bookmarks::new();
        store.add("work", Path::new("/old"));
        store.add("work", Path::new("/new"));

        assert_eq!(store.list().len(), 1);
        assert_eq!(store.resolve("work"), Some(Path::new("/new")));
    }

    #[test]
    fn entries_are_listed_sorted_by_name() {
        let mut store = Bookmarks::new();
        store.add("zed", Path::new("/z"));
        store.add("alpha", Path::new("/a"));
        store.add("mid", Path::new("/m"));

        assert_eq!(names(&store), vec!["alpha", "mid", "zed"]);
    }

    #[test]
    fn blank_and_separator_bearing_names_are_refused() {
        let mut store = Bookmarks::new();

        assert!(!store.add("   ", Path::new("/a")));
        // A tab or newline would break the stored line format.
        assert!(!store.add("a\tb", Path::new("/a")));
        assert!(!store.add("a\nb", Path::new("/a")));
        assert!(store.is_empty());
    }

    #[test]
    fn names_are_trimmed_on_the_way_in() {
        let mut store = Bookmarks::new();
        store.add("  code  ", Path::new("/c"));

        assert_eq!(names(&store), vec!["code"]);
    }

    #[test]
    fn remove_reports_whether_anything_went() {
        let mut store = Bookmarks::new();
        store.add("code", Path::new("/c"));

        assert!(store.remove("code"));
        assert!(!store.remove("code"));
        assert!(store.is_empty());
    }

    #[test]
    fn text_round_trips() {
        let mut store = Bookmarks::new();
        store.add("code", Path::new("/home/me/code"));
        store.add("docs", Path::new("/home/me/My Documents"));

        let restored = Bookmarks::from_text(&store.to_text());

        assert_eq!(restored, store);
    }

    #[test]
    fn paths_with_spaces_survive_the_round_trip() {
        let mut store = Bookmarks::new();
        store.add("space", Path::new("/a b/c d"));

        let restored = Bookmarks::from_text(&store.to_text());
        assert_eq!(restored.resolve("space"), Some(Path::new("/a b/c d")));
    }

    #[test]
    fn malformed_lines_cost_only_themselves() {
        let text = "good\t/a\nno-tab-here\n\ngood2\t/b\n\t/missing-name\n";
        let store = Bookmarks::from_text(text);

        assert_eq!(names(&store), vec!["good", "good2"]);
    }

    #[test]
    fn carriage_returns_are_tolerated() {
        let store = Bookmarks::from_text("code\t/c\r\ndocs\t/d\r\n");
        assert_eq!(names(&store), vec!["code", "docs"]);
    }

    #[test]
    fn empty_text_parses_to_an_empty_store() {
        assert!(Bookmarks::from_text("").is_empty());
    }
}