Merge pull request #171 from matthiasbeyer/libimaglink/init

Libimaglink/init
This commit is contained in:
Matthias Beyer 2016-03-18 10:39:34 +01:00
commit cf20a23fec
6 changed files with 414 additions and 0 deletions

13
libimaglink/Cargo.toml Normal file
View file

@ -0,0 +1,13 @@
[package]
name = "libimaglink"
version = "0.1.0"
authors = ["Matthias Beyer <mail@beyermatthias.de>"]
[dependencies]
log = "0.3.4"
toml = "0.1.27"
url = "0.5.5"
[dependencies.libimagstore]
path = "../libimagstore"

84
libimaglink/src/error.rs Normal file
View file

@ -0,0 +1,84 @@
use std::error::Error;
use std::fmt::Error as FmtError;
use std::clone::Clone;
use std::fmt::{Debug, Display, Formatter};
use std::fmt;
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum LinkErrorKind {
EntryHeaderReadError,
EntryHeaderWriteError,
ExistingLinkTypeWrong,
LinkTargetDoesNotExist,
InternalConversionError,
InvalidUri,
}
fn link_error_type_as_str(e: &LinkErrorKind) -> &'static str {
match e {
&LinkErrorKind::EntryHeaderReadError
=> "Error while reading an entry header",
&LinkErrorKind::EntryHeaderWriteError
=> "Error while writing an entry header",
&LinkErrorKind::ExistingLinkTypeWrong
=> "Existing link entry has wrong type",
&LinkErrorKind::LinkTargetDoesNotExist
=> "Link target does not exist in the store",
&LinkErrorKind::InternalConversionError
=> "Error while converting values internally",
&LinkErrorKind::InvalidUri
=> "URI is not valid",
}
}
impl Display for LinkErrorKind {
fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> {
try!(write!(fmt, "{}", link_error_type_as_str(self)));
Ok(())
}
}
#[derive(Debug)]
pub struct LinkError {
kind: LinkErrorKind,
cause: Option<Box<Error>>,
}
impl LinkError {
pub fn new(errtype: LinkErrorKind, cause: Option<Box<Error>>) -> LinkError {
LinkError {
kind: errtype,
cause: cause,
}
}
}
impl Display for LinkError {
fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> {
try!(write!(fmt, "[{}]", link_error_type_as_str(&self.kind)));
Ok(())
}
}
impl Error for LinkError {
fn description(&self) -> &str {
link_error_type_as_str(&self.kind)
}
fn cause(&self) -> Option<&Error> {
self.cause.as_ref().map(|e| &**e)
}
}

140
libimaglink/src/external.rs Normal file
View file

@ -0,0 +1,140 @@
use std::convert::Into;
use libimagstore::store::Entry;
use libimagstore::store::EntryHeader;
use error::{LinkError, LinkErrorKind};
use result::Result;
use toml::Value;
use toml::Table;
use url::Url;
#[derive(PartialOrd, Ord, Eq, PartialEq, Clone, Debug)]
pub struct Link {
link: String
}
impl Link {
pub fn new(s: String) -> Link {
Link { link: s }
}
pub fn is_valid(&self) -> bool {
Url::parse(&self.link[..]).is_ok()
}
}
#[derive(Eq, PartialEq, Clone, Debug)]
pub struct Links {
links: Vec<Link>,
}
impl Links {
pub fn new(s: Vec<Link>) -> Links {
Links { links: s }
}
pub fn add(&mut self, l: Link) {
self.links.push(l);
}
pub fn remove(&mut self, l: Link) {
self.links.retain(|link| l != link.clone());
}
pub fn all_valid(&self) -> bool {
self.links.iter().all(|l| l.is_valid())
}
}
impl Into<String> for Link {
fn into(self) -> String {
self.link
}
}
impl Into<Vec<Link>> for Links {
fn into(self) -> Vec<Link> {
self.links
}
}
pub trait ExternalLinker {
/// get the external link from the implementor object
fn get_external_link(&self) -> Result<Option<Link>>;
/// set the external link for the implementor object and return the current link from the entry,
/// if any.
fn set_external_link(&mut self, l: Link) -> Result<Option<Link>>;
}
impl ExternalLinker for EntryHeader {
fn get_external_link(&self) -> Result<Option<Link>> {
let uri = self.read("imag.content.uri");
if uri.is_err() {
let kind = LinkErrorKind::EntryHeaderReadError;
let lerr = LinkError::new(kind, Some(Box::new(uri.err().unwrap())));
return Err(lerr);
}
let uri = uri.unwrap();
match uri {
Some(Value::String(s)) => Ok(Some(Link::new(s))),
_ => Err(LinkError::new(LinkErrorKind::ExistingLinkTypeWrong, None)),
}
}
/// Set an external link in the header
///
/// Return the previous set link if there was any
fn set_external_link(&mut self, l: Link) -> Result<Option<Link>> {
if !l.is_valid() {
return Err(LinkError::new(LinkErrorKind::InvalidUri, None));
}
let old_link = self.set("imag.content.uri", Value::String(l.into()));
if old_link.is_err() {
let kind = LinkErrorKind::EntryHeaderWriteError;
let lerr = LinkError::new(kind, Some(Box::new(old_link.err().unwrap())));
return Err(lerr);
}
let old_link = old_link.unwrap();
if old_link.is_none() {
return Ok(None);
}
match old_link.unwrap() {
Value::String(s) => Ok(Some(Link::new(s))),
// We don't do anything in this case and be glad we corrected the type error with this set()
_ => Ok(None),
}
}
}
impl ExternalLinker for Entry {
fn get_external_link(&self) -> Result<Option<Link>> {
self.get_header().get_external_link()
}
fn set_external_link(&mut self, l: Link) -> Result<Option<Link>> {
self.get_header_mut().set_external_link(l)
}
}

160
libimaglink/src/internal.rs Normal file
View file

@ -0,0 +1,160 @@
use libimagstore::storeid::StoreId;
use libimagstore::store::Entry;
use libimagstore::store::EntryHeader;
use libimagstore::store::Result as StoreResult;
use error::{LinkError, LinkErrorKind};
use result::Result;
use toml::Value;
pub type Link = String;
pub trait InternalLinker {
/// Get the internal links from the implementor object
fn get_internal_links(&self) -> Result<Vec<Link>>;
/// Set the internal links for the implementor object
fn set_internal_links(&mut self, links: Vec<&mut Entry>) -> Result<Vec<Link>>;
/// Add an internal link to the implementor object
fn add_internal_link(&mut self, link: &mut Entry) -> Result<()>;
/// Remove an internal link from the implementor object
fn remove_internal_link(&mut self, link: &mut Entry) -> Result<()>;
}
impl InternalLinker for Entry {
fn get_internal_links(&self) -> Result<Vec<Link>> {
process_rw_result(self.get_header().read("imag.links"))
}
/// Set the links in a header and return the old links, if any.
fn set_internal_links(&mut self, links: Vec<&mut Entry>) -> Result<Vec<Link>> {
let self_location = self.get_location().clone();
let mut new_links = vec![];
for link in links {
if let Err(e) = add_foreign_link(link, self_location.clone()) {
return Err(e);
}
let link = link.get_location().clone();
let link = link.to_str();
if link.is_none() {
return Err(LinkError::new(LinkErrorKind::InternalConversionError, None));
}
let link = link.unwrap();
new_links.push(Value::String(String::from(link)));
}
process_rw_result(self.get_header_mut().set("imag.links", Value::Array(new_links)))
}
fn add_internal_link(&mut self, link: &mut Entry) -> Result<()> {
let new_link = link.get_location().clone();
let new_link = new_link.to_str();
if new_link.is_none() {
return Err(LinkError::new(LinkErrorKind::InternalConversionError, None));
}
let new_link = new_link.unwrap();
add_foreign_link(link, self.get_location().clone())
.and_then(|_| {
self.get_internal_links()
.and_then(|mut links| {
links.push(String::from(new_link));
let links = links.into_iter().map(|s| Value::String(s)).collect();
let process = self.get_header_mut().set("imag.links", Value::Array(links));
process_rw_result(process)
.map(|_| ())
})
})
}
fn remove_internal_link(&mut self, link: &mut Entry) -> Result<()> {
let own_loc = link.get_location().clone();
let own_loc = own_loc.to_str();
if own_loc.is_none() {
return Err(LinkError::new(LinkErrorKind::InternalConversionError, None));
}
let own_loc = own_loc.unwrap();
let other_loc = link.get_location().clone();
let other_loc = other_loc.to_str();
if other_loc.is_none() {
return Err(LinkError::new(LinkErrorKind::InternalConversionError, None));
}
let other_loc = other_loc.unwrap();
link.get_internal_links()
.and_then(|mut links| {
let links = links.into_iter()
.filter(|l| l.clone() != own_loc)
.map(|s| Value::String(s))
.collect();
process_rw_result(link.get_header_mut().set("imag.links", Value::Array(links)))
.map(|_| ())
})
.and_then(|_| {
self.get_internal_links()
.and_then(|mut links| {
let links = links
.into_iter()
.filter(|l| l.clone() != other_loc)
.map(|s| Value::String(s))
.collect();
process_rw_result(self.get_header_mut().set("imag.links", Value::Array(links)))
.map(|_| ())
})
})
}
}
/// When Linking A -> B, the specification wants us to link back B -> A.
/// This is a helper function which does this.
fn add_foreign_link(target: &mut Entry, from: StoreId) -> Result<()> {
let from = from.to_str();
if from.is_none() {
debug!("Cannot convert pathbuf '{:?}' to String", from);
return Err(LinkError::new(LinkErrorKind::InternalConversionError, None));
}
let from = from.unwrap();
target.get_internal_links()
.and_then(|mut links| {
links.push(String::from(from));
let links = links.into_iter().map(|s| Value::String(s)).collect();
process_rw_result(target.get_header_mut().set("imag.links", Value::Array(links)))
.map(|_| ())
})
}
fn process_rw_result(links: StoreResult<Option<Value>>) -> Result<Vec<Link>> {
if links.is_err() {
let lerr = LinkError::new(LinkErrorKind::EntryHeaderReadError,
Some(Box::new(links.err().unwrap())));
return Err(lerr);
}
let links = links.unwrap();
if links.iter().any(|l| match l { &Value::String(_) => true, _ => false }) {
return Err(LinkError::new(LinkErrorKind::ExistingLinkTypeWrong, None));
}
let links : Vec<Link> = links.into_iter()
.map(|link| {
match link {
Value::String(s) => String::from(s),
_ => unreachable!(),
}
})
.collect();
Ok(links)
}

11
libimaglink/src/lib.rs Normal file
View file

@ -0,0 +1,11 @@
#[macro_use] extern crate log;
extern crate toml;
extern crate url;
extern crate libimagstore;
pub mod error;
pub mod external;
pub mod internal;
pub mod result;

View file

@ -0,0 +1,6 @@
use std::result::Result as RResult;
use error::LinkError;
pub type Result<T> = RResult<T, LinkError>;