imag/lib/entry/libimagentrylink/src/linkable.rs

497 lines
19 KiB
Rust
Raw Normal View History

//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2019 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
use libimagstore::storeid::StoreId;
use libimagstore::store::Entry;
2018-02-25 16:04:05 +00:00
use libimagstore::store::Store;
use libimagerror::errors::ErrorMsg as EM;
2016-02-03 14:47:14 +00:00
2017-08-26 15:53:08 +00:00
use toml_query::read::TomlValueReadExt;
use toml_query::insert::TomlValueInsertExt;
use failure::ResultExt;
use failure::Fallible as Result;
use failure::Error;
use failure::err_msg;
2017-08-26 15:53:08 +00:00
use crate::iter::LinkIter;
use crate::iter::IntoValues;
use crate::link::Link;
2016-02-03 14:47:14 +00:00
2016-02-07 15:25:17 +00:00
use toml::Value;
pub trait Linkable {
2016-02-03 14:47:14 +00:00
/// Get the internal links from the implementor object
fn links(&self) -> Result<LinkIter>;
/// Add an internal link to the implementor object
fn add_link(&mut self, link: &mut Entry) -> Result<()>;
/// Remove an internal link from the implementor object
fn remove_link(&mut self, link: &mut Entry) -> Result<()>;
2016-02-03 14:47:14 +00:00
2018-02-25 16:04:05 +00:00
/// Remove _all_ internal links
fn unlink(&mut self, store: &Store) -> Result<()>;
/// Add internal annotated link
fn add_annotated_link(&mut self, link: &mut Entry, annotation: String) -> Result<()>;
2016-02-03 14:47:14 +00:00
}
impl Linkable for Entry {
fn links(&self) -> Result<LinkIter> {
2018-04-30 13:48:08 +00:00
debug!("Getting internal links");
trace!("Getting internal links from header of '{}' = {:?}", self.get_location(), self.get_header());
2017-08-26 15:53:08 +00:00
let res = self
.get_header()
.read("links.internal")
.context(format_err!("Failed to read header 'links.internal' of '{}'", self.get_location()))
.context(EM::EntryHeaderReadError)
.context(EM::EntryHeaderError)
.map_err(Error::from)
2017-08-26 15:53:08 +00:00
.map(|r| r.cloned());
process_rw_result(res)
}
fn add_link(&mut self, link: &mut Entry) -> Result<()> {
2018-04-30 13:48:08 +00:00
debug!("Adding internal link: {:?}", link);
let location = link.get_location().clone().into();
add_link_with_instance(self, link, location)
}
fn remove_link(&mut self, link: &mut Entry) -> Result<()> {
2018-04-30 13:48:08 +00:00
debug!("Removing internal link: {:?}", link);
// Cloning because of borrowing
let own_loc = self.get_location().clone();
let other_loc = link.get_location().clone();
2016-10-15 09:24:14 +00:00
debug!("Removing internal link from {:?} to {:?}", own_loc, other_loc);
let links = link.links()?;
debug!("Rewriting own links for {:?}, without {:?}", other_loc, own_loc);
let links = links.filter(|l| !l.eq_store_id(&own_loc));
let _ = rewrite_links(link.get_header_mut(), links)?;
self.links()
.and_then(|links| {
debug!("Rewriting own links for {:?}, without {:?}", own_loc, other_loc);
let links = links.filter(|l| !l.eq_store_id(&other_loc));
rewrite_links(self.get_header_mut(), links)
})
}
2018-02-25 16:04:05 +00:00
fn unlink(&mut self, store: &Store) -> Result<()> {
for id in self.links()?.map(|l| l.get_store_id().clone()) {
match store.get(id).context("Failed to get entry")? {
Some(mut entry) => self.remove_link(&mut entry)?,
None => return Err(err_msg("Link target does not exist")),
2018-02-25 16:04:05 +00:00
}
}
Ok(())
}
fn add_annotated_link(&mut self, link: &mut Entry, annotation: String) -> Result<()> {
let new_link = Link::Annotated {
link: link.get_location().clone(),
annotation: annotation,
};
add_link_with_instance(self, link, new_link)
}
}
fn add_link_with_instance(this: &mut Entry, link: &mut Entry, instance: Link) -> Result<()> {
debug!("Adding internal link from {:?} to {:?}", this.get_location(), instance);
add_foreign_link(link, this.get_location().clone())
.and_then(|_| {
this.links()
.and_then(|links| {
let links = links.chain(LinkIter::new(vec![instance]));
rewrite_links(this.get_header_mut(), links)
})
})
2016-02-15 12:19:34 +00:00
}
fn rewrite_links<I: Iterator<Item = Link>>(header: &mut Value, links: I) -> Result<()> {
let links = links.into_values()
.into_iter()
.fold(Ok(vec![]), |acc: Result<Vec<_>>, elem| {
2016-08-03 09:29:38 +00:00
acc.and_then(move |mut v| {
v.push(elem.context(EM::ConversionError)?);
Ok(v)
2016-08-03 09:29:38 +00:00
})
})?;
2016-08-03 09:29:38 +00:00
2016-10-15 09:24:14 +00:00
debug!("Setting new link array: {:?}", links);
2017-08-26 15:53:08 +00:00
let process = header
.insert("links.internal", Value::Array(links))
.context(format_err!("Failed to insert header 'links.internal'"))
.context(EM::EntryHeaderReadError)
.map_err(Error::from);
2016-08-03 09:29:38 +00:00
process_rw_result(process).map(|_| ())
2016-04-08 22:07:30 +00:00
}
/// 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<()> {
2016-10-15 09:24:14 +00:00
debug!("Linking back from {:?} to {:?}", target.get_location(), from);
target.links()
.and_then(|links| {
let links = links
.chain(LinkIter::new(vec![from.into()]))
.into_values()
.into_iter()
.fold(Ok(vec![]), |acc: Result<Vec<_>>, elem| {
2016-08-03 09:30:23 +00:00
acc.and_then(move |mut v| {
v.push(elem.context(EM::ConversionError)?);
Ok(v)
2016-08-03 09:30:23 +00:00
})
})?;
2016-10-15 09:24:14 +00:00
debug!("Setting links in {:?}: {:?}", target.get_location(), links);
2017-08-26 15:53:08 +00:00
let res = target
.get_header_mut()
.insert("links.internal", Value::Array(links))
.context(format_err!("Failed to insert header 'links.internal'"))
.context(EM::EntryHeaderReadError)
.map_err(Error::from);
2017-08-26 15:53:08 +00:00
process_rw_result(res).map(|_| ())
})
}
2017-08-26 15:53:08 +00:00
fn process_rw_result(links: Result<Option<Value>>) -> Result<LinkIter> {
use std::path::PathBuf;
let links = match links {
Err(e) => {
debug!("RW action on store failed. Generating LinkError");
return Err(e).context(EM::EntryHeaderReadError).map_err(Error::from)
},
Ok(None) => {
debug!("We got no value from the header!");
return Ok(LinkIter::new(vec![]))
},
Ok(Some(Value::Array(l))) => l,
Ok(Some(_)) => {
debug!("We expected an Array for the links, but there was a non-Array!");
return Err(err_msg("Link type error"));
}
};
if !links.iter().all(|l| is_match!(*l, Value::String(_)) || is_match!(*l, Value::Table(_))) {
debug!("At least one of the Values which were expected in the Array of links is not a String or a Table!");
debug!("Generating LinkError");
return Err(err_msg("Existing Link type error"));
2016-02-14 16:50:06 +00:00
}
let links : Vec<Link> = links.into_iter()
2016-02-14 16:50:06 +00:00
.map(|link| {
debug!("Matching the link: {:?}", link);
2016-02-14 16:50:06 +00:00
match link {
Value::String(s) => StoreId::new(PathBuf::from(s))
.map(|s| Link::Id { link: s })
.map_err(From::from)
,
Value::Table(mut tab) => {
debug!("Destructuring table");
if !tab.contains_key("link")
|| !tab.contains_key("annotation") {
debug!("Things missing... returning Error instance");
Err(err_msg("Link parser error"))
} else {
let link = tab.remove("link")
.ok_or(err_msg("Link parser: field missing"))?;
let anno = tab.remove("annotation")
.ok_or(err_msg("Link parser: Field missing"))?;
debug!("Ok, here we go with building a Link::Annotated");
match (link, anno) {
(Value::String(link), Value::String(anno)) => {
StoreId::new(PathBuf::from(link))
.map_err(From::from)
.map(|link| {
Link::Annotated {
link: link,
annotation: anno,
}
})
},
_ => Err(err_msg("Link parser: Field type error")),
}
}
}
2016-02-14 16:50:06 +00:00
_ => unreachable!(),
}
})
.collect::<Result<Vec<Link>>>()?;
2016-02-14 16:50:06 +00:00
debug!("Ok, the RW action was successful, returning link vector now!");
Ok(LinkIter::new(links))
2016-02-14 16:50:06 +00:00
}
2016-10-15 08:33:30 +00:00
#[cfg(test)]
mod test {
use std::path::PathBuf;
use libimagstore::store::Store;
use super::Linkable;
2017-09-23 12:13:16 +00:00
use super::Link;
2016-10-15 08:33:30 +00:00
2016-10-15 08:58:50 +00:00
fn setup_logging() {
2017-12-07 21:07:01 +00:00
let _ = ::env_logger::try_init();
2016-10-15 08:58:50 +00:00
}
2016-10-15 08:33:30 +00:00
pub fn get_store() -> Store {
Store::new_inmemory(PathBuf::from("/"), &None).unwrap()
2016-10-15 08:33:30 +00:00
}
#[test]
fn test_new_entry_no_links() {
2016-10-15 08:58:50 +00:00
setup_logging();
2016-10-15 08:33:30 +00:00
let store = get_store();
let entry = store.create(PathBuf::from("test_new_entry_no_links")).unwrap();
let links = entry.links();
2016-10-15 08:33:30 +00:00
assert!(links.is_ok());
let links = links.unwrap();
assert_eq!(links.collect::<Vec<_>>().len(), 0);
}
2016-10-15 08:41:13 +00:00
#[test]
fn test_link_two_entries() {
2016-10-15 08:58:50 +00:00
setup_logging();
2016-10-15 08:41:13 +00:00
let store = get_store();
let mut e1 = store.create(PathBuf::from("test_link_two_entries1")).unwrap();
assert!(e1.links().is_ok());
2016-10-15 08:41:13 +00:00
let mut e2 = store.create(PathBuf::from("test_link_two_entries2")).unwrap();
assert!(e2.links().is_ok());
2016-10-15 08:41:13 +00:00
{
assert!(e1.add_link(&mut e2).is_ok());
2016-10-15 08:41:13 +00:00
let e1_links = e1.links().unwrap().collect::<Vec<_>>();
let e2_links = e2.links().unwrap().collect::<Vec<_>>();
2016-10-15 08:41:13 +00:00
2016-10-15 09:24:14 +00:00
debug!("1 has links: {:?}", e1_links);
debug!("2 has links: {:?}", e2_links);
2016-10-15 08:41:13 +00:00
assert_eq!(e1_links.len(), 1);
assert_eq!(e2_links.len(), 1);
assert!(e1_links.first().map(|l| l.clone().eq_store_id(e2.get_location())).unwrap_or(false));
assert!(e2_links.first().map(|l| l.clone().eq_store_id(e1.get_location())).unwrap_or(false));
2016-10-15 08:41:13 +00:00
}
{
assert!(e1.remove_link(&mut e2).is_ok());
2016-10-15 08:41:13 +00:00
2018-11-01 10:51:07 +00:00
debug!("{:?}", e2.to_str());
let e2_links = e2.links().unwrap().collect::<Vec<_>>();
2016-10-15 08:41:13 +00:00
assert_eq!(e2_links.len(), 0, "Expected [], got: {:?}", e2_links);
2018-11-01 10:51:07 +00:00
debug!("{:?}", e1.to_str());
let e1_links = e1.links().unwrap().collect::<Vec<_>>();
2016-10-15 08:41:13 +00:00
assert_eq!(e1_links.len(), 0, "Expected [], got: {:?}", e1_links);
}
}
2016-10-15 09:31:30 +00:00
#[test]
fn test_multiple_links() {
setup_logging();
let store = get_store();
let mut e1 = store.retrieve(PathBuf::from("1")).unwrap();
let mut e2 = store.retrieve(PathBuf::from("2")).unwrap();
let mut e3 = store.retrieve(PathBuf::from("3")).unwrap();
let mut e4 = store.retrieve(PathBuf::from("4")).unwrap();
let mut e5 = store.retrieve(PathBuf::from("5")).unwrap();
assert!(e1.add_link(&mut e2).is_ok());
2016-10-15 09:31:30 +00:00
assert_eq!(e1.links().unwrap().collect::<Vec<_>>().len(), 1);
assert_eq!(e2.links().unwrap().collect::<Vec<_>>().len(), 1);
assert_eq!(e3.links().unwrap().collect::<Vec<_>>().len(), 0);
assert_eq!(e4.links().unwrap().collect::<Vec<_>>().len(), 0);
assert_eq!(e5.links().unwrap().collect::<Vec<_>>().len(), 0);
2016-10-15 09:31:30 +00:00
assert!(e1.add_link(&mut e3).is_ok());
2016-10-15 09:31:30 +00:00
assert_eq!(e1.links().unwrap().collect::<Vec<_>>().len(), 2);
assert_eq!(e2.links().unwrap().collect::<Vec<_>>().len(), 1);
assert_eq!(e3.links().unwrap().collect::<Vec<_>>().len(), 1);
assert_eq!(e4.links().unwrap().collect::<Vec<_>>().len(), 0);
assert_eq!(e5.links().unwrap().collect::<Vec<_>>().len(), 0);
2016-10-15 09:31:30 +00:00
assert!(e1.add_link(&mut e4).is_ok());
2016-10-15 09:31:30 +00:00
assert_eq!(e1.links().unwrap().collect::<Vec<_>>().len(), 3);
assert_eq!(e2.links().unwrap().collect::<Vec<_>>().len(), 1);
assert_eq!(e3.links().unwrap().collect::<Vec<_>>().len(), 1);
assert_eq!(e4.links().unwrap().collect::<Vec<_>>().len(), 1);
assert_eq!(e5.links().unwrap().collect::<Vec<_>>().len(), 0);
2016-10-15 09:31:30 +00:00
assert!(e1.add_link(&mut e5).is_ok());
2016-10-15 09:31:30 +00:00
assert_eq!(e1.links().unwrap().collect::<Vec<_>>().len(), 4);
assert_eq!(e2.links().unwrap().collect::<Vec<_>>().len(), 1);
assert_eq!(e3.links().unwrap().collect::<Vec<_>>().len(), 1);
assert_eq!(e4.links().unwrap().collect::<Vec<_>>().len(), 1);
assert_eq!(e5.links().unwrap().collect::<Vec<_>>().len(), 1);
2016-10-15 09:31:30 +00:00
assert!(e5.remove_link(&mut e1).is_ok());
2016-10-15 09:31:30 +00:00
assert_eq!(e1.links().unwrap().collect::<Vec<_>>().len(), 3);
assert_eq!(e2.links().unwrap().collect::<Vec<_>>().len(), 1);
assert_eq!(e3.links().unwrap().collect::<Vec<_>>().len(), 1);
assert_eq!(e4.links().unwrap().collect::<Vec<_>>().len(), 1);
assert_eq!(e5.links().unwrap().collect::<Vec<_>>().len(), 0);
2016-10-15 09:31:30 +00:00
assert!(e4.remove_link(&mut e1).is_ok());
2016-10-15 09:31:30 +00:00
assert_eq!(e1.links().unwrap().collect::<Vec<_>>().len(), 2);
assert_eq!(e2.links().unwrap().collect::<Vec<_>>().len(), 1);
assert_eq!(e3.links().unwrap().collect::<Vec<_>>().len(), 1);
assert_eq!(e4.links().unwrap().collect::<Vec<_>>().len(), 0);
assert_eq!(e5.links().unwrap().collect::<Vec<_>>().len(), 0);
2016-10-15 09:31:30 +00:00
assert!(e3.remove_link(&mut e1).is_ok());
2016-10-15 09:31:30 +00:00
assert_eq!(e1.links().unwrap().collect::<Vec<_>>().len(), 1);
assert_eq!(e2.links().unwrap().collect::<Vec<_>>().len(), 1);
assert_eq!(e3.links().unwrap().collect::<Vec<_>>().len(), 0);
assert_eq!(e4.links().unwrap().collect::<Vec<_>>().len(), 0);
assert_eq!(e5.links().unwrap().collect::<Vec<_>>().len(), 0);
2016-10-15 09:31:30 +00:00
assert!(e2.remove_link(&mut e1).is_ok());
2016-10-15 09:31:30 +00:00
assert_eq!(e1.links().unwrap().collect::<Vec<_>>().len(), 0);
assert_eq!(e2.links().unwrap().collect::<Vec<_>>().len(), 0);
assert_eq!(e3.links().unwrap().collect::<Vec<_>>().len(), 0);
assert_eq!(e4.links().unwrap().collect::<Vec<_>>().len(), 0);
assert_eq!(e5.links().unwrap().collect::<Vec<_>>().len(), 0);
2016-10-15 09:31:30 +00:00
}
2017-07-14 21:17:32 +00:00
#[test]
fn test_link_deleting() {
setup_logging();
let store = get_store();
let mut e1 = store.retrieve(PathBuf::from("1")).unwrap();
let mut e2 = store.retrieve(PathBuf::from("2")).unwrap();
assert_eq!(e1.links().unwrap().collect::<Vec<_>>().len(), 0);
assert_eq!(e2.links().unwrap().collect::<Vec<_>>().len(), 0);
2017-07-14 21:17:32 +00:00
assert!(e1.add_link(&mut e2).is_ok());
2017-07-14 21:17:32 +00:00
assert_eq!(e1.links().unwrap().collect::<Vec<_>>().len(), 1);
assert_eq!(e2.links().unwrap().collect::<Vec<_>>().len(), 1);
2017-07-14 21:17:32 +00:00
assert!(e1.remove_link(&mut e2).is_ok());
2017-07-14 21:17:32 +00:00
assert_eq!(e1.links().unwrap().collect::<Vec<_>>().len(), 0);
assert_eq!(e2.links().unwrap().collect::<Vec<_>>().len(), 0);
2017-07-14 21:17:32 +00:00
}
2017-07-14 21:21:38 +00:00
#[test]
fn test_link_deleting_multiple_links() {
setup_logging();
let store = get_store();
let mut e1 = store.retrieve(PathBuf::from("1")).unwrap();
let mut e2 = store.retrieve(PathBuf::from("2")).unwrap();
let mut e3 = store.retrieve(PathBuf::from("3")).unwrap();
assert_eq!(e1.links().unwrap().collect::<Vec<_>>().len(), 0);
assert_eq!(e2.links().unwrap().collect::<Vec<_>>().len(), 0);
assert_eq!(e3.links().unwrap().collect::<Vec<_>>().len(), 0);
2017-07-14 21:21:38 +00:00
assert!(e1.add_link(&mut e2).is_ok()); // 1-2
assert!(e1.add_link(&mut e3).is_ok()); // 1-2, 1-3
2017-07-14 21:21:38 +00:00
assert_eq!(e1.links().unwrap().collect::<Vec<_>>().len(), 2);
assert_eq!(e2.links().unwrap().collect::<Vec<_>>().len(), 1);
assert_eq!(e3.links().unwrap().collect::<Vec<_>>().len(), 1);
2017-07-14 21:21:38 +00:00
assert!(e2.add_link(&mut e3).is_ok()); // 1-2, 1-3, 2-3
2017-07-14 21:21:38 +00:00
assert_eq!(e1.links().unwrap().collect::<Vec<_>>().len(), 2);
assert_eq!(e2.links().unwrap().collect::<Vec<_>>().len(), 2);
assert_eq!(e3.links().unwrap().collect::<Vec<_>>().len(), 2);
2017-07-14 21:21:38 +00:00
assert!(e1.remove_link(&mut e2).is_ok()); // 1-3, 2-3
2017-07-14 21:21:38 +00:00
assert_eq!(e1.links().unwrap().collect::<Vec<_>>().len(), 1);
assert_eq!(e2.links().unwrap().collect::<Vec<_>>().len(), 1);
assert_eq!(e3.links().unwrap().collect::<Vec<_>>().len(), 2);
2017-07-14 21:21:38 +00:00
assert!(e1.remove_link(&mut e3).is_ok()); // 2-3
2017-07-14 21:21:38 +00:00
assert_eq!(e1.links().unwrap().collect::<Vec<_>>().len(), 0);
assert_eq!(e2.links().unwrap().collect::<Vec<_>>().len(), 1);
assert_eq!(e3.links().unwrap().collect::<Vec<_>>().len(), 1);
2017-07-14 21:21:38 +00:00
assert!(e2.remove_link(&mut e3).is_ok());
2017-07-14 21:21:38 +00:00
assert_eq!(e1.links().unwrap().collect::<Vec<_>>().len(), 0);
assert_eq!(e2.links().unwrap().collect::<Vec<_>>().len(), 0);
assert_eq!(e3.links().unwrap().collect::<Vec<_>>().len(), 0);
2017-07-14 21:21:38 +00:00
}
2017-09-23 12:13:16 +00:00
#[test]
fn test_link_annotating() {
setup_logging();
let store = get_store();
let mut entry1 = store.create(PathBuf::from("test_link_annotating-1")).unwrap();
let mut entry2 = store.create(PathBuf::from("test_link_annotating-2")).unwrap();
let res = entry1.add_annotated_link(&mut entry2, String::from("annotation"));
2017-09-23 12:13:16 +00:00
assert!(res.is_ok());
{
for link in entry1.links().unwrap() {
2017-09-23 12:13:16 +00:00
match link {
Link::Annotated {annotation, ..} => assert_eq!(annotation, "annotation"),
_ => assert!(false, "Non-annotated link found"),
}
}
}
{
for link in entry2.links().unwrap() {
2017-09-23 12:13:16 +00:00
match link {
Link::Id {..} => {},
Link::Annotated {..} => assert!(false, "Annotated link found"),
}
}
}
}
2016-10-15 08:33:30 +00:00
}