use toml::Value;
use uuid::Uuid;
use libimagstore::store::Entry;
use libimagstore::store::FileLockEntry;
use libimagstore::store::Store;
use libimagstore::storeid::StoreIdIterator;
use libimagentrylink::linkable::Linkable;
use libimagentryutil::isa::Is;
use libimagentryutil::isa::IsKindHeaderPathProvider;
use toml_query::insert::TomlValueInsertExt;
use failure::Fallible as Result;
use failure::ResultExt;
use failure::Error;
use failure::err_msg;
pub trait Annotateable {
fn annotate<'a>(&mut self, store: &'a Store) -> Result<FileLockEntry<'a>>;
fn denotate<'a>(&mut self, store: &'a Store, ann_name: &str) -> Result<Option<FileLockEntry<'a>>>;
fn annotations(&self) -> Result<StoreIdIterator>;
fn is_annotation(&self) -> Result<bool>;
}
provide_kindflag_path!(IsAnnotation, "annotation.is_annotation");
impl Annotateable for Entry {
fn annotate<'a>(&mut self, store: &'a Store) -> Result<FileLockEntry<'a>> {
let ann_name = Uuid::new_v4().to_hyphenated().to_string();
debug!("Creating annotation with name = {}", ann_name);
store.retrieve(crate::module_path::new_id(ann_name.clone())?)
.and_then(|mut anno| {
{
anno.set_isflag::<IsAnnotation>()?;
let _ = anno
.get_header_mut()
.insert("annotation.name", Value::String(ann_name))?;
}
Ok(anno)
})
.and_then(|mut anno| {
anno.add_link(self)
.context(err_msg("Linking error"))
.map_err(Error::from)
.map(|_| anno)
})
}
fn denotate<'a>(&mut self, store: &'a Store, ann_name: &str) -> Result<Option<FileLockEntry<'a>>> {
if let Some(mut annotation) = store.get(crate::module_path::new_id(ann_name)?)? {
self.remove_link(&mut annotation)?;
Ok(Some(annotation))
} else {
Err(format_err!("Annotation '{}' does not exist", ann_name)).map_err(Error::from)
}
}
fn annotations(&self) -> Result<StoreIdIterator> {
self.links()
.map(|it| {
it.filter(|link| link.get_store_id().is_in_collection(&["annotation"]))
.map(|link| Ok(link.get_store_id().clone()))
})
.map(Box::new)
.map(|inner| StoreIdIterator::new(inner))
}
fn is_annotation(&self) -> Result<bool> {
self.is::<IsAnnotation>()
}
}