Implement entry reading

This commit is contained in:
Marcel Müller 2016-01-23 17:30:01 +01:00
parent 97b7090824
commit a64ffdfc56
No known key found for this signature in database
GPG Key ID: DD4ED37D0CAC76E2
2 changed files with 54 additions and 5 deletions

View File

@ -3,6 +3,7 @@ use std::fmt::Error as FmtError;
use std::clone::Clone;
use std::fmt::{Debug, Display, Formatter};
use std::fmt;
use std::convert::From;
use toml;
/**
@ -19,7 +20,8 @@ pub enum StoreErrorKind {
StorePathExists,
StorePathCreate,
LockPoisoned,
EntryAlreadyBorrowed
EntryAlreadyBorrowed,
MalformedEntry,
// maybe more
}
@ -36,6 +38,7 @@ fn store_error_type_as_str(e: &StoreErrorKind) -> &'static str {
&StoreErrorKind::LockPoisoned
=> "The internal Store Lock has been poisoned",
&StoreErrorKind::EntryAlreadyBorrowed => "Entry is already borrowed",
&StoreErrorKind::MalformedEntry => "Entry has invalid formatting, missing header",
}
}
@ -101,6 +104,14 @@ impl Error for StoreError {
}
impl From<ParserError> for StoreError {
fn from(ps: ParserError) -> StoreError {
StoreError {
err_type: StoreErrorKind::MalformedEntry,
cause: Some(Box::new(ps)),
}
}
}
#[derive(Clone)]
pub enum ParserErrorKind {

View File

@ -11,6 +11,7 @@ use std::collections::BTreeMap;
use fs2::FileExt;
use toml::{Table, Value};
use regex::Regex;
use error::{ParserErrorKind, ParserError};
use error::{StoreError, StoreErrorKind};
@ -44,7 +45,7 @@ impl StoreEntry {
fn get_entry(&mut self) -> Result<Entry> {
if !self.is_borrowed() {
let file = self.file.get_file();
let file = self.file.get_file_mut();
if let Err(err) = file {
if err.err_type() == StoreErrorKind::FileNotFound {
Ok(Entry::new(self.id.clone()))
@ -53,7 +54,7 @@ impl StoreEntry {
}
} else {
// TODO:
unimplemented!()
Entry::from_file(self.id.clone(), file.unwrap())
}
} else {
return Err(StoreError::new(StoreErrorKind::EntryAlreadyBorrowed, None))
@ -335,6 +336,43 @@ impl Entry {
}
}
fn from_file(loc: StoreId, file: &mut File) -> Result<Entry> {
use std::io::Read;
let file = {
let mut buff = String::new();
file.read_to_string(&mut buff);
buff
};
let re = Regex::new(r"(?smx)
^---$
(?P<header>.*) # Header
^---$
(?P<content>.*) # Content
").unwrap();
let matches = re.captures(&file[..]);
if matches.is_none() {
return Err(StoreError::new(StoreErrorKind::MalformedEntry, None));
}
let matches = matches.unwrap();
let header = matches.name("header");
let content = matches.name("content").unwrap_or("");
if header.is_none() {
return Err(StoreError::new(StoreErrorKind::MalformedEntry, None));
}
Ok(Entry {
location: loc,
header: try!(EntryHeader::parse(header.unwrap())),
content: content.into(),
})
}
pub fn get_location(&self) -> &StoreId {
&self.location
}