From fc9e05ba09fd2e66fdae4c73c99e6b73dd61cc86 Mon Sep 17 00:00:00 2001 From: trivernis Date: Fri, 4 Sep 2020 20:25:46 +0200 Subject: [PATCH] Add function to parse a toml bibliography file Signed-off-by: trivernis --- Cargo.toml | 5 +++-- src/bib_manager.rs | 41 ++++++++++++++++++++++++++++++++++++++++- 2 files changed, 43 insertions(+), 3 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index ecfeba9..6cd9239 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bibliographix" description = "A bibliography management crate." -version = "0.3.2" +version = "0.4.0" authors = ["trivernis "] edition = "2018" license = "Apache-2.0" @@ -12,4 +12,5 @@ repository = "https://github.com/Trivernis/bibliographix" [dependencies] chrono = "0.4.15" -chrono-english = "0.1.4" \ No newline at end of file +chrono-english = "0.1.4" +toml = "0.5.6" \ No newline at end of file diff --git a/src/bib_manager.rs b/src/bib_manager.rs index e55157b..5cda345 100644 --- a/src/bib_manager.rs +++ b/src/bib_manager.rs @@ -1,7 +1,14 @@ use crate::bibliography::bibliography_dict::BibliographyDictionary; -use crate::bibliography::bibliography_entry::BibliographyEntryReference; +use crate::bibliography::bibliography_entry::{BibliographyEntry, BibliographyEntryReference}; +use crate::bibliography::keys::K_KEY; +use crate::bibliography::FromHashMap; use crate::references::anchor::BibListAnchor; +use std::collections::HashMap; +use std::io; +use std::io::BufRead; +use std::iter::FromIterator; use std::sync::{Arc, Mutex}; +use toml::Value; /// The root manager for that should be used for further reference operations that /// go beyond insertion. @@ -71,4 +78,36 @@ impl BibManager { entries } + + /// Reads a toml bibliography file and inserts each entry into the dictionary + pub fn read_bib_file(&self, reader: &mut impl BufRead) -> io::Result<()> { + let mut contents = String::new(); + reader.read_to_string(&mut contents)?; + let bib_content = contents.parse::()?; + let mut entry_dict = self.entry_dictionary.lock().unwrap(); + + if let Some(table) = bib_content.as_table() { + let mut entries = table + .iter() + .filter_map(|(k, v)| { + let entry_iter = v + .as_table()? + .iter() + .filter_map(|(k, v)| Some((k.clone(), v.as_str()?.to_string()))); + + let mut entry_map: HashMap = HashMap::from_iter(entry_iter); + + entry_map.insert(K_KEY.to_string(), k.clone()); + + Some(*BibliographyEntry::from_hash_map(&entry_map)?) + }) + .collect::>(); + + while let Some(entry) = entries.pop() { + entry_dict.insert(entry) + } + } + + Ok(()) + } }