mini-cite 0.2.0

BibTeX-backed inline citations and footnotes for the mini-* family.
Documentation
//! Loads a directory of `.bib` files into one lookup table of citation keys.

use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};

use crate::parser::{parse_entries, Entry};
use crate::{CiteError, Result};

/// The file extension a bibliography source must carry to be loaded.
const BIB_EXTENSION: &str = "bib";

/// Every citation key defined by a directory of `.bib` files, and the entry each
/// key resolves to.
#[derive(Debug, Clone, Default)]
pub struct Bibliography {
    entries: BTreeMap<String, Entry>,
}

impl Bibliography {
    /// Loads every `*.bib` file directly inside `dir` (non-recursive) and merges
    /// their entries into one bibliography.
    ///
    /// Files are processed in sorted filename order. Directory read order is
    /// OS-dependent, so sorting first is what makes both iteration order and
    /// duplicate-key attribution reproducible across machines rather than incidental.
    ///
    /// A directory holding no `.bib` files loads to an empty bibliography rather than
    /// an error: a docs project can legitimately wire up its bibliography directory
    /// before writing the first citation.
    ///
    /// # Errors
    ///
    /// - [`CiteError::Io`] if `dir` or one of its `.bib` files cannot be read.
    /// - [`CiteError::Parse`], naming the offending file, if a `.bib` file is malformed.
    /// - [`CiteError::DuplicateKey`], naming both files, if two files define one key.
    pub fn load_dir(dir: impl AsRef<Path>) -> Result<Self> {
        let dir = dir.as_ref();
        let paths = bib_paths_sorted(dir)?;

        let mut entries = BTreeMap::new();
        let mut source_of: BTreeMap<String, PathBuf> = BTreeMap::new();

        for path in paths {
            let source = fs::read_to_string(&path).map_err(|source| CiteError::Io {
                path: path.clone(),
                source,
            })?;

            let parsed = parse_entries(&source).map_err(|error| attribute(error, &path))?;

            for (key, entry) in parsed {
                if let Some(first_file) = source_of.get(&key) {
                    return Err(CiteError::DuplicateKey {
                        key,
                        first_file: first_file.clone(),
                        second_file: path,
                    });
                }
                source_of.insert(key.clone(), path.clone());
                entries.insert(key, entry);
            }
        }

        Ok(Self { entries })
    }

    /// Builds a bibliography directly from parsed entries, for callers that hold
    /// `.bib` content in memory rather than on disk.
    pub fn from_entries(entries: impl IntoIterator<Item = (String, Entry)>) -> Self {
        Self {
            entries: entries.into_iter().collect(),
        }
    }

    /// Returns the entry a citation key resolves to, or `None` if no loaded file
    /// defines it.
    pub fn get(&self, key: &str) -> Option<&Entry> {
        self.entries.get(key)
    }

    /// Returns the number of distinct citation keys loaded.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Returns `true` when no citation keys were loaded.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }
}

/// Returns every `*.bib` path directly inside `dir`, sorted by filename.
fn bib_paths_sorted(dir: &Path) -> Result<Vec<PathBuf>> {
    let read_dir = fs::read_dir(dir).map_err(|source| CiteError::Io {
        path: dir.to_path_buf(),
        source,
    })?;

    let mut paths = Vec::new();
    for dir_entry in read_dir {
        let dir_entry = dir_entry.map_err(|source| CiteError::Io {
            path: dir.to_path_buf(),
            source,
        })?;
        let path = dir_entry.path();

        if path.is_file() && path.extension().is_some_and(|ext| ext == BIB_EXTENSION) {
            paths.push(path);
        }
    }
    paths.sort();

    Ok(paths)
}

/// Attaches the source file to a parse error raised by the file-agnostic parser.
fn attribute(error: CiteError, path: &Path) -> CiteError {
    match error {
        CiteError::Parse { file: None, message } => CiteError::Parse {
            file: Some(path.to_path_buf()),
            message,
        },
        other => other,
    }
}

#[cfg(test)]
#[path = "../tests/unit/bibliography.rs"]
mod tests;