mini_cite/
bibliography.rs1use std::collections::BTreeMap;
4use std::fs;
5use std::path::{Path, PathBuf};
6
7use crate::parser::{parse_entries, Entry};
8use crate::{CiteError, Result};
9
10const BIB_EXTENSION: &str = "bib";
12
13#[derive(Debug, Clone, Default)]
16pub struct Bibliography {
17 entries: BTreeMap<String, Entry>,
18}
19
20impl Bibliography {
21 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 pub fn from_entries(entries: impl IntoIterator<Item = (String, Entry)>) -> Self {
71 Self {
72 entries: entries.into_iter().collect(),
73 }
74 }
75
76 pub fn get(&self, key: &str) -> Option<&Entry> {
79 self.entries.get(key)
80 }
81
82 pub fn len(&self) -> usize {
84 self.entries.len()
85 }
86
87 pub fn is_empty(&self) -> bool {
89 self.entries.is_empty()
90 }
91}
92
93fn 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
117fn 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;