Skip to main content

mini_cite/
bibliography.rs

1//! Loads a directory of `.bib` files into one lookup table of citation keys.
2
3use std::collections::BTreeMap;
4use std::fs;
5use std::path::{Path, PathBuf};
6
7use crate::parser::{parse_entries, Entry};
8use crate::{CiteError, Result};
9
10/// The file extension a bibliography source must carry to be loaded.
11const BIB_EXTENSION: &str = "bib";
12
13/// Every citation key defined by a directory of `.bib` files, and the entry each
14/// key resolves to.
15#[derive(Debug, Clone, Default)]
16pub struct Bibliography {
17    entries: BTreeMap<String, Entry>,
18}
19
20impl Bibliography {
21    /// Loads every `*.bib` file directly inside `dir` (non-recursive) and merges
22    /// their entries into one bibliography.
23    ///
24    /// Files are processed in sorted filename order. Directory read order is
25    /// OS-dependent, so sorting first is what makes both iteration order and
26    /// duplicate-key attribution reproducible across machines rather than incidental.
27    ///
28    /// A directory holding no `.bib` files loads to an empty bibliography rather than
29    /// an error: a docs project can legitimately wire up its bibliography directory
30    /// before writing the first citation.
31    ///
32    /// # Errors
33    ///
34    /// - [`CiteError::Io`] if `dir` or one of its `.bib` files cannot be read.
35    /// - [`CiteError::Parse`], naming the offending file, if a `.bib` file is malformed.
36    /// - [`CiteError::DuplicateKey`], naming both files, if two files define one key.
37    pub fn load_dir(dir: impl AsRef<Path>) -> Result<Self> {
38        let dir = dir.as_ref();
39        let paths = bib_paths_sorted(dir)?;
40
41        let mut entries = BTreeMap::new();
42        let mut source_of: BTreeMap<String, PathBuf> = BTreeMap::new();
43
44        for path in paths {
45            let source = fs::read_to_string(&path).map_err(|source| CiteError::Io {
46                path: path.clone(),
47                source,
48            })?;
49
50            let parsed = parse_entries(&source).map_err(|error| attribute(error, &path))?;
51
52            for (key, entry) in parsed {
53                if let Some(first_file) = source_of.get(&key) {
54                    return Err(CiteError::DuplicateKey {
55                        key,
56                        first_file: first_file.clone(),
57                        second_file: path,
58                    });
59                }
60                source_of.insert(key.clone(), path.clone());
61                entries.insert(key, entry);
62            }
63        }
64
65        Ok(Self { entries })
66    }
67
68    /// Builds a bibliography directly from parsed entries, for callers that hold
69    /// `.bib` content in memory rather than on disk.
70    pub fn from_entries(entries: impl IntoIterator<Item = (String, Entry)>) -> Self {
71        Self {
72            entries: entries.into_iter().collect(),
73        }
74    }
75
76    /// Returns the entry a citation key resolves to, or `None` if no loaded file
77    /// defines it.
78    pub fn get(&self, key: &str) -> Option<&Entry> {
79        self.entries.get(key)
80    }
81
82    /// Returns the number of distinct citation keys loaded.
83    pub fn len(&self) -> usize {
84        self.entries.len()
85    }
86
87    /// Returns `true` when no citation keys were loaded.
88    pub fn is_empty(&self) -> bool {
89        self.entries.is_empty()
90    }
91}
92
93/// Returns every `*.bib` path directly inside `dir`, sorted by filename.
94fn bib_paths_sorted(dir: &Path) -> Result<Vec<PathBuf>> {
95    let read_dir = fs::read_dir(dir).map_err(|source| CiteError::Io {
96        path: dir.to_path_buf(),
97        source,
98    })?;
99
100    let mut paths = Vec::new();
101    for dir_entry in read_dir {
102        let dir_entry = dir_entry.map_err(|source| CiteError::Io {
103            path: dir.to_path_buf(),
104            source,
105        })?;
106        let path = dir_entry.path();
107
108        if path.is_file() && path.extension().is_some_and(|ext| ext == BIB_EXTENSION) {
109            paths.push(path);
110        }
111    }
112    paths.sort();
113
114    Ok(paths)
115}
116
117/// Attaches the source file to a parse error raised by the file-agnostic parser.
118fn attribute(error: CiteError, path: &Path) -> CiteError {
119    match error {
120        CiteError::Parse { file: None, message } => CiteError::Parse {
121            file: Some(path.to_path_buf()),
122            message,
123        },
124        other => other,
125    }
126}
127
128#[cfg(test)]
129#[path = "../tests/unit/bibliography.rs"]
130mod tests;