Outsource header/content parsing from store.rs to util.rs for reusability

This commit is contained in:
Matthias Beyer 2017-06-18 00:50:18 +02:00
parent 91c427925b
commit c013ca8025
2 changed files with 39 additions and 25 deletions

View file

@ -24,7 +24,6 @@ use std::result::Result as RResult;
use std::sync::Arc;
use std::sync::RwLock;
use std::io::Read;
use std::convert::From;
use std::convert::Into;
use std::ops::Deref;
use std::ops::DerefMut;
@ -33,7 +32,6 @@ use std::fmt::Debug;
use std::fmt::Error as FMTError;
use toml::Value;
use regex::Regex;
use glob::glob;
use walkdir::WalkDir;
use walkdir::Iter as WalkDirIter;
@ -919,33 +917,14 @@ impl Entry {
/// - Header cannot be parsed into a TOML object
///
pub fn from_str<S: IntoStoreId>(loc: S, s: &str) -> Result<Entry> {
debug!("Building entry from string");
lazy_static! {
static ref RE: Regex = Regex::new(r"(?smx)
^---$
(?P<header>.*) # Header
^---$\n
(?P<content>.*) # Content
").unwrap();
}
use util::entry_buffer_to_header_content;
let matches = match RE.captures(s) {
None => return Err(SE::new(SEK::MalformedEntry, None)),
Some(s) => s,
};
let (header, content) = try!(entry_buffer_to_header_content(s));
let header = match matches.name("header") {
None => return Err(SE::new(SEK::MalformedEntry, None)),
Some(s) => s
};
let content = matches.name("content").map(|r| r.as_str()).unwrap_or("");
debug!("Header and content found. Yay! Building Entry object now");
Ok(Entry {
location: try!(loc.into_storeid()),
header: try!(Value::parse(header.as_str())),
content: String::from(content),
header: header,
content: content,
})
}

View file

@ -17,6 +17,15 @@
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
use regex::Regex;
use toml::Value;
use libimagerror::into::IntoError;
use store::Result;
use error::StoreErrorKind as SEK;
use toml_ext::Header;
#[cfg(feature = "early-panic")]
#[macro_export]
macro_rules! if_cfg_panic {
@ -33,3 +42,29 @@ macro_rules! if_cfg_panic {
($fmt:expr, $($arg:tt)+) => { };
}
pub fn entry_buffer_to_header_content(buf: &str) -> Result<(Value, String)> {
debug!("Building entry from string");
lazy_static! {
static ref RE: Regex = Regex::new(r"(?smx)
^---$
(?P<header>.*) # Header
^---$\n
(?P<content>.*) # Content
").unwrap();
}
let matches = match RE.captures(buf) {
None => return Err(SEK::MalformedEntry.into_error()),
Some(s) => s,
};
let header = match matches.name("header") {
None => return Err(SEK::MalformedEntry.into_error()),
Some(s) => s
};
let content = matches.name("content").map(|r| r.as_str()).unwrap_or("");
Ok((try!(Value::parse(header.as_str())), String::from(content)))
}