From 770cc3e86ba495034865b1771e86eaf48882a85c Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sat, 16 Apr 2016 17:03:30 +0200 Subject: [PATCH 001/288] Add dependency: walkdir = 0.1.5 --- libimagstore/Cargo.toml | 1 + libimagstore/src/lib.rs | 1 + 2 files changed, 2 insertions(+) diff --git a/libimagstore/Cargo.toml b/libimagstore/Cargo.toml index 6cde98bf..f2af405f 100644 --- a/libimagstore/Cargo.toml +++ b/libimagstore/Cargo.toml @@ -13,6 +13,7 @@ semver = "0.2" toml = "0.1.25" version = "2.0.1" crossbeam = "0.2.8" +walkdir = "0.1.5" [dev-dependencies] tempdir = "0.3.4" diff --git a/libimagstore/src/lib.rs b/libimagstore/src/lib.rs index 2396a672..e7efa3be 100644 --- a/libimagstore/src/lib.rs +++ b/libimagstore/src/lib.rs @@ -22,6 +22,7 @@ extern crate toml; #[cfg(test)] extern crate tempdir; extern crate semver; extern crate crossbeam; +extern crate walkdir; pub mod storeid; pub mod error; From 799b9e27a50e0cc52a78d48a9c4159aacf9d4773 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Thu, 14 Apr 2016 13:20:35 +0200 Subject: [PATCH 002/288] Remove typedef for StoreId type MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit but make it a new type instead. Also derive and implement as many traits as possible for it, so we keep backwards compatibility as much as possible. Anyways, we need to rewrite some code for this. Suggested-by: Marcel Müller Signed-off-by: Matthias Beyer --- libimagstore/src/storeid.rs | 46 ++++++++++++++++++++++++++++++++++++- 1 file changed, 45 insertions(+), 1 deletion(-) diff --git a/libimagstore/src/storeid.rs b/libimagstore/src/storeid.rs index 7c5940c1..87f432e7 100644 --- a/libimagstore/src/storeid.rs +++ b/libimagstore/src/storeid.rs @@ -1,4 +1,7 @@ use std::path::PathBuf; +use std::path::Path; +use std::borrow::Borrow; + use glob::Paths; use semver::Version; use std::fmt::{Debug, Formatter}; @@ -10,7 +13,48 @@ use store::Result; use store::Store; /// The Index into the Store -pub type StoreId = PathBuf; +#[derive(Debug, Clone, PartialEq, Hash, Eq, PartialOrd, Ord)] +pub struct StoreId(PathBuf); + +impl Into for StoreId { + + fn into(self) -> PathBuf { + self.0 + } + +} + +impl From for StoreId { + + fn from(pb: PathBuf) -> StoreId { + StoreId(pb) + } + +} + +impl From for StoreId { + + fn from(string: String) -> StoreId { + StoreId(string.into()) + } + +} + +impl AsRef for StoreId { + + fn as_ref(&self) -> &Path { + self.0.as_ref() + } + +} + +impl Borrow for StoreId { + + fn borrow(&self) -> &Path { + self.0.borrow() + } + +} /// This Trait allows you to convert various representations to a single one /// suitable for usage in the Store From 4d4acf916859d4029e9b7c34730f68dac7831855 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Tue, 3 May 2016 14:36:24 +0200 Subject: [PATCH 003/288] Fix IntoStoreId implementation --- libimagstore/src/store.rs | 4 ++-- libimagstore/src/storeid.rs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/libimagstore/src/store.rs b/libimagstore/src/store.rs index 9d174e24..7d4febdc 100644 --- a/libimagstore/src/store.rs +++ b/libimagstore/src/store.rs @@ -57,7 +57,7 @@ impl StoreEntry { fn new(id: StoreId) -> StoreEntry { StoreEntry { id: id.clone(), - file: LazyFile::Absent(id), + file: LazyFile::Absent(id.into()), status: StoreEntryStatus::Present, } } @@ -241,7 +241,7 @@ impl Store { let mut new_id = self.location.clone(); new_id.push(id); debug!("Created: '{:?}'", new_id); - new_id + StoreId::from(new_id) } /// Creates the Entry at the given location (inside the entry) diff --git a/libimagstore/src/storeid.rs b/libimagstore/src/storeid.rs index 87f432e7..d2b0dc25 100644 --- a/libimagstore/src/storeid.rs +++ b/libimagstore/src/storeid.rs @@ -64,7 +64,7 @@ pub trait IntoStoreId { impl IntoStoreId for PathBuf { fn into_storeid(self) -> StoreId { - self + StoreId(self) } } @@ -163,7 +163,7 @@ impl Iterator for StoreIdIterator { type Item = StoreId; fn next(&mut self) -> Option { - self.paths.next().and_then(|o| o.ok()) + self.paths.next().and_then(|o| o.ok()).map(|p| StoreId::from(p)) } } From b4db587a100e8b9585254ffc32e8a151f1f36616 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Tue, 3 May 2016 14:45:33 +0200 Subject: [PATCH 004/288] Impl Deref for StoreId --- libimagstore/src/storeid.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/libimagstore/src/storeid.rs b/libimagstore/src/storeid.rs index d2b0dc25..3734e08a 100644 --- a/libimagstore/src/storeid.rs +++ b/libimagstore/src/storeid.rs @@ -1,6 +1,7 @@ use std::path::PathBuf; use std::path::Path; use std::borrow::Borrow; +use std::ops::Deref; use glob::Paths; use semver::Version; @@ -24,6 +25,15 @@ impl Into for StoreId { } +impl Deref for StoreId { + type Target = PathBuf; + + fn deref(&self) -> &PathBuf { + &self.0 + } + +} + impl From for StoreId { fn from(pb: PathBuf) -> StoreId { From 7e17e213be8c92e531ef6bab8d9a5ba38578ab17 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Tue, 3 May 2016 14:53:14 +0200 Subject: [PATCH 005/288] Fixup ModuleEntryPath macro type --- libimagstore/src/storeid.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/libimagstore/src/storeid.rs b/libimagstore/src/storeid.rs index 3734e08a..22390ccd 100644 --- a/libimagstore/src/storeid.rs +++ b/libimagstore/src/storeid.rs @@ -116,6 +116,8 @@ macro_rules! module_entry_path_mod { use std::path::Path; use std::path::PathBuf; + use $crate::storeid::StoreId; + /// A Struct giving you the ability to choose store entries assigned /// to it. /// @@ -140,7 +142,7 @@ macro_rules! module_entry_path_mod { impl $crate::storeid::IntoStoreId for ModuleEntryPath { fn into_storeid(self) -> $crate::storeid::StoreId { - self.0 + StoreId::from(self.0) } } } From 24ddf5d53bfedaeccf3da67466a612237a42fa20 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Tue, 3 May 2016 15:45:06 +0200 Subject: [PATCH 006/288] Impl IntoStoreId for StoreId --- libimagstore/src/storeid.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/libimagstore/src/storeid.rs b/libimagstore/src/storeid.rs index 22390ccd..d5229e2b 100644 --- a/libimagstore/src/storeid.rs +++ b/libimagstore/src/storeid.rs @@ -78,6 +78,12 @@ impl IntoStoreId for PathBuf { } } +impl IntoStoreId for StoreId { + fn into_storeid(self) -> StoreId { + self + } +} + pub fn build_entry_path(store: &Store, path_elem: &str) -> Result { debug!("Checking path element for version"); if path_elem.split("~").last().map(|v| Version::parse(v).is_err()).unwrap_or(false) { From 5d6c2269531c42661864ce222ecb5428fbc8e1e3 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Tue, 3 May 2016 15:49:33 +0200 Subject: [PATCH 007/288] Make some store functions generic over IntoStoreId --- libimagstore/src/store.rs | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/libimagstore/src/store.rs b/libimagstore/src/store.rs index 7d4febdc..5052a0b2 100644 --- a/libimagstore/src/store.rs +++ b/libimagstore/src/store.rs @@ -23,7 +23,7 @@ use glob::glob; use error::{ParserErrorKind, ParserError}; use error::{StoreError, StoreErrorKind}; -use storeid::{StoreId, StoreIdIterator}; +use storeid::{IntoStoreId, StoreId, StoreIdIterator}; use lazyfile::LazyFile; use hook::aspect::Aspect; @@ -245,8 +245,8 @@ impl Store { } /// Creates the Entry at the given location (inside the entry) - pub fn create<'a>(&'a self, id: StoreId) -> Result> { - let id = self.storify_id(id); + pub fn create<'a, S: IntoStoreId>(&'a self, id: S) -> Result> { + let id = self.storify_id(id.into_storeid()); if let Err(e) = self.execute_hooks_for_id(self.pre_create_aspects.clone(), &id) { return Err(e); } @@ -273,8 +273,8 @@ impl Store { /// Borrow a given Entry. When the `FileLockEntry` is either `update`d or /// dropped, the new Entry is written to disk - pub fn retrieve<'a>(&'a self, id: StoreId) -> Result> { - let id = self.storify_id(id); + pub fn retrieve<'a, S: IntoStoreId>(&'a self, id: S) -> Result> { + let id = self.storify_id(id.into_storeid()); if let Err(e) = self.execute_hooks_for_id(self.pre_retrieve_aspects.clone(), &id) { return Err(e); } @@ -356,8 +356,8 @@ impl Store { /// Retrieve a copy of a given entry, this cannot be used to mutate /// the one on disk - pub fn retrieve_copy(&self, id: StoreId) -> Result { - let id = self.storify_id(id); + pub fn retrieve_copy(&self, id: S) -> Result { + let id = self.storify_id(id.into_storeid()); let entries_lock = self.entries.write(); if entries_lock.is_err() { return Err(StoreError::new(StoreErrorKind::LockPoisoned, None)) @@ -374,8 +374,8 @@ impl Store { } /// Delete an entry - pub fn delete(&self, id: StoreId) -> Result<()> { - let id = self.storify_id(id); + pub fn delete(&self, id: S) -> Result<()> { + let id = self.storify_id(id.into_storeid()); if let Err(e) = self.execute_hooks_for_id(self.pre_delete_aspects.clone(), &id) { return Err(e); } From 79f585def9ccacb8ea2548d84404b652c18a9d55 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Tue, 3 May 2016 16:18:53 +0200 Subject: [PATCH 008/288] Fix libimagentrylist::listers::path --- libimagentrylist/src/listers/path.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libimagentrylist/src/listers/path.rs b/libimagentrylist/src/listers/path.rs index 0f1deac5..e3602770 100644 --- a/libimagentrylist/src/listers/path.rs +++ b/libimagentrylist/src/listers/path.rs @@ -32,7 +32,7 @@ impl Lister for PathLister { if self.absolute { pb.canonicalize().map_err(|e| LE::new(LEK::FormatError, Some(Box::new(e)))) } else { - Ok(pb) + Ok(pb.into()) } }) .and_then(|pb| { From 3842e177d774fbfd09a8d48721905c7332e46676 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Wed, 4 May 2016 12:00:31 +0200 Subject: [PATCH 009/288] Make Entry::{from_file,from_str} generic over IntoStoreId --- libimagstore/src/store.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/libimagstore/src/store.rs b/libimagstore/src/store.rs index 5052a0b2..faf1d784 100644 --- a/libimagstore/src/store.rs +++ b/libimagstore/src/store.rs @@ -1119,7 +1119,7 @@ impl Entry { } } - pub fn from_file(loc: StoreId, file: &mut File) -> Result { + pub fn from_file(loc: S, file: &mut File) -> Result { let text = { use std::io::Read; let mut s = String::new(); @@ -1129,7 +1129,7 @@ impl Entry { Self::from_str(loc, &text[..]) } - pub fn from_str(loc: StoreId, s: &str) -> Result { + pub fn from_str(loc: S, s: &str) -> Result { debug!("Building entry from string"); lazy_static! { static ref RE: Regex = Regex::new(r"(?smx) @@ -1157,7 +1157,7 @@ impl Entry { debug!("Header and content found. Yay! Building Entry object now"); Ok(Entry { - location: loc, + location: loc.into_storeid(), header: try!(EntryHeader::parse(header.unwrap())), content: content.into(), }) From 025ea4b03bda9d16ce3e3b2f90c756551eae3bf6 Mon Sep 17 00:00:00 2001 From: Ron Dahlgren Date: Fri, 6 May 2016 21:40:15 -0400 Subject: [PATCH 010/288] Fixes coice / choice typo in README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e51719f8..351d39a0 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # imag Imag is a CLI PIM suite with a nice API-ish commandline interface, so you can -integrate it in your tools of coice (Editor, MUA, RSS reader, etc etc). +integrate it in your tools of choice (Editor, MUA, RSS reader, etc etc). ## Goal From c32065c2d65c4042332395bcb3f86685d230a9c2 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sat, 16 Apr 2016 17:03:41 +0200 Subject: [PATCH 011/288] Implement Store::walk() --- libimagstore/src/store.rs | 58 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/libimagstore/src/store.rs b/libimagstore/src/store.rs index 9d174e24..e6f46829 100644 --- a/libimagstore/src/store.rs +++ b/libimagstore/src/store.rs @@ -20,6 +20,8 @@ use std::fmt::Error as FMTError; use toml::{Table, Value}; use regex::Regex; use glob::glob; +use walkdir::WalkDir; +use walkdir::Iter as WalkDirIter; use error::{ParserErrorKind, ParserError}; use error::{StoreError, StoreErrorKind}; @@ -52,6 +54,57 @@ struct StoreEntry { status: StoreEntryStatus, } +pub enum StoreObject { + Id(StoreId), + Collection(PathBuf), +} + +pub struct Walk { + dirwalker: WalkDirIter, +} + +impl Walk { + + fn new(mut store_path: PathBuf, mod_name: &str) -> Walk { + store_path.push(mod_name); + Walk { + dirwalker: WalkDir::new(store_path).into_iter(), + } + } +} + +impl ::std::ops::Deref for Walk { + type Target = WalkDirIter; + + fn deref(&self) -> &Self::Target { + &self.dirwalker + } +} + +impl Iterator for Walk { + type Item = StoreObject; + + fn next(&mut self) -> Option { + while let Some(something) = self.dirwalker.next() { + match something { + Ok(next) => if next.file_type().is_dir() { + return Some(StoreObject::Collection(next.path().to_path_buf())) + } else if next.file_type().is_file() { + return Some(StoreObject::Id(next.path().to_path_buf().into())) + }, + Err(e) => { + warn!("Error in Walker"); + debug!("{:?}", e); + return None; + } + } + } + + return None; + } +} + + impl StoreEntry { fn new(id: StoreId) -> StoreEntry { @@ -315,6 +368,11 @@ impl Store { } } + // Walk the store tree for the module + pub fn walk<'a>(&'a self, mod_name: &str) -> Walk { + Walk::new(self.path().clone(), mod_name) + } + /// Return the `FileLockEntry` and write to disk pub fn update<'a>(&'a self, mut entry: FileLockEntry<'a>) -> Result<()> { if let Err(e) = self.execute_hooks_for_mut_file(self.pre_update_aspects.clone(), &mut entry) { From 87c55d590605af88f5446e2a73d255f3f0f58ed2 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Mon, 9 May 2016 17:11:59 +0200 Subject: [PATCH 012/288] Remove old check from config validation These keys are not used, actually. --- libimagstore/src/configuration.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/libimagstore/src/configuration.rs b/libimagstore/src/configuration.rs index 95e8b2fc..20e18362 100644 --- a/libimagstore/src/configuration.rs +++ b/libimagstore/src/configuration.rs @@ -120,8 +120,6 @@ pub fn config_is_valid(config: &Option) -> bool { match config { &Some(Value::Table(ref t)) => { - has_key_with_string_ary(t, "pre-read-hook-aspects") && - has_key_with_string_ary(t, "post-read-hook-aspects") && has_key_with_string_ary(t, "pre-create-hook-aspects") && has_key_with_string_ary(t, "post-create-hook-aspects") && has_key_with_string_ary(t, "pre-retrieve-hook-aspects") && From 987605322f5ee8c97b2ad568bab777168f7b3f9a Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Mon, 9 May 2016 17:12:55 +0200 Subject: [PATCH 013/288] Add missing "return None" in file opening error case --- libimagrt/src/configuration.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/libimagrt/src/configuration.rs b/libimagrt/src/configuration.rs index 0913d90a..eb199a53 100644 --- a/libimagrt/src/configuration.rs +++ b/libimagrt/src/configuration.rs @@ -244,13 +244,16 @@ fn fetch_config(rtp: &PathBuf) -> Result { let mut s = String::new(); let f = File::open(path); if f.is_err() { + return None } let mut f = f.unwrap(); f.read_to_string(&mut s).ok(); s }; + let mut parser = Parser::new(&content[..]); let res = parser.parse(); + if res.is_none() { write!(stderr(), "Config file parser error:").ok(); for error in parser.errors { From 4d9ef9604c6549cb6d0c9e82a6883a504b405f0e Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Mon, 9 May 2016 17:13:17 +0200 Subject: [PATCH 014/288] Add example configuration file --- imagrc.toml | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 imagrc.toml diff --git a/imagrc.toml b/imagrc.toml new file mode 100644 index 00000000..8c65046f --- /dev/null +++ b/imagrc.toml @@ -0,0 +1,27 @@ +# This is a example configuration file for the imag suite. +# It is written in TOML + +[store] + + +pre-create-hook-aspects = [ "debug" ] +post-create-hook-aspects = [ "debug" ] + +pre-retrieve-hook-aspects = [ "debug" ] +post-retrieve-hook-aspects = [ "debug" ] + +pre-update-hook-aspects = [ "debug" ] +post-update-hook-aspects = [ "debug" ] + +pre-delete-hook-aspects = [ "debug" ] +post-delete-hook-aspects = [ "debug" ] + +[store.aspects] + +[[aspects.debug]] +parallel = false + +[store.hooks] + +[[hooks.debug]] +aspect = "debug" From 96b7a7622743e5fd9b9884c8dfbbab4acfea35d0 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Tue, 10 May 2016 17:54:47 +0200 Subject: [PATCH 015/288] Update log: 0.3.* -> 0.3 --- imag-counter/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imag-counter/Cargo.toml b/imag-counter/Cargo.toml index 5ef71d51..d3441fbb 100644 --- a/imag-counter/Cargo.toml +++ b/imag-counter/Cargo.toml @@ -5,7 +5,7 @@ authors = ["Matthias Beyer "] [dependencies] clap = "2.1.1" -log = "0.3.5" +log = "0.3" version = "2.0.1" [dependencies.libimagrt] From 465f43cd6e951e47bd0a1dc4fea63bffb093a54b Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Tue, 10 May 2016 17:54:47 +0200 Subject: [PATCH 016/288] Update log: 0.3.* -> 0.3 --- imag-link/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imag-link/Cargo.toml b/imag-link/Cargo.toml index 70df3df5..21e4e72b 100644 --- a/imag-link/Cargo.toml +++ b/imag-link/Cargo.toml @@ -6,7 +6,7 @@ authors = ["Matthias Beyer "] [dependencies] semver = "0.2.1" clap = "2.1.1" -log = "0.3.5" +log = "0.3" version = "2.0.1" toml = "0.1.25" url = "0.5.5" From a2ca6b4feb195873e379c21f9a32b2a1b58fe948 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Tue, 10 May 2016 17:54:47 +0200 Subject: [PATCH 017/288] Update log: 0.3.* -> 0.3 --- imag-notes/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imag-notes/Cargo.toml b/imag-notes/Cargo.toml index fac64742..64f9f990 100644 --- a/imag-notes/Cargo.toml +++ b/imag-notes/Cargo.toml @@ -6,7 +6,7 @@ authors = ["Matthias Beyer "] [dependencies] semver = "0.2.1" clap = "2.1.1" -log = "0.3.5" +log = "0.3" version = "2.0.1" [dependencies.libimagrt] From e3105fe085667ea3258596b3f78c83e846519f56 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Tue, 10 May 2016 17:54:47 +0200 Subject: [PATCH 018/288] Update log: 0.3.* -> 0.3 --- imag-store/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imag-store/Cargo.toml b/imag-store/Cargo.toml index cadd37d0..0deba5a0 100644 --- a/imag-store/Cargo.toml +++ b/imag-store/Cargo.toml @@ -5,7 +5,7 @@ authors = ["Matthias Beyer "] [dependencies] clap = "2.1.1" -log = "0.3.5" +log = "0.3" version = "2.0.1" semver = "0.2.1" toml = "0.1.25" From 1b280b2f186bcee997bcb556840063de5b28a687 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Tue, 10 May 2016 17:54:47 +0200 Subject: [PATCH 019/288] Update log: 0.3.* -> 0.3 --- imag-tag/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imag-tag/Cargo.toml b/imag-tag/Cargo.toml index 5cd1df03..c3ed51ef 100644 --- a/imag-tag/Cargo.toml +++ b/imag-tag/Cargo.toml @@ -5,7 +5,7 @@ authors = ["Matthias Beyer "] [dependencies] clap = "2.1.1" -log = "0.3.5" +log = "0.3" version = "2.0.1" semver = "0.2.1" toml = "0.1.25" From c29c6bf4a38dd90dd2a953b0118451332f2866cc Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Tue, 10 May 2016 17:54:47 +0200 Subject: [PATCH 020/288] Update log: 0.3.* -> 0.3 --- imag-view/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imag-view/Cargo.toml b/imag-view/Cargo.toml index 5dd2504d..b3a52460 100644 --- a/imag-view/Cargo.toml +++ b/imag-view/Cargo.toml @@ -6,7 +6,7 @@ authors = ["Matthias Beyer "] [dependencies] clap = "2.1.1" glob = "0.2.11" -log = "0.3.5" +log = "0.3" rustbox = "0.8.1" semver = "0.2.1" toml = "0.1.25" From 15986cba3490053d72095a004dbc8bc037b64dbe Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Tue, 10 May 2016 17:54:47 +0200 Subject: [PATCH 021/288] Update log: 0.3.* -> 0.3 --- libimagcounter/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libimagcounter/Cargo.toml b/libimagcounter/Cargo.toml index 15ec9add..8d880182 100644 --- a/libimagcounter/Cargo.toml +++ b/libimagcounter/Cargo.toml @@ -4,7 +4,7 @@ version = "0.1.0" authors = ["Matthias Beyer "] [dependencies] -log = "0.3.5" +log = "0.3" toml = "0.1.25" semver = "0.2" From f168d8c871eea8483dc175aba1dd904e955fd9c5 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Tue, 10 May 2016 17:54:47 +0200 Subject: [PATCH 022/288] Update log: 0.3.* -> 0.3 --- libimagentryfilter/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libimagentryfilter/Cargo.toml b/libimagentryfilter/Cargo.toml index e4ff3aa0..f746a223 100644 --- a/libimagentryfilter/Cargo.toml +++ b/libimagentryfilter/Cargo.toml @@ -6,7 +6,7 @@ authors = ["Matthias Beyer "] [dependencies] clap = "2.1.1" itertools = "0.4" -log = "0.3.4" +log = "0.3" regex = "0.1" toml = "0.1.27" semver = "0.2.1" From abcbfd7f27791f95e4e8a4ff9657d5df15ddf06b Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Tue, 10 May 2016 17:54:47 +0200 Subject: [PATCH 023/288] Update log: 0.3.* -> 0.3 --- libimagentrylink/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libimagentrylink/Cargo.toml b/libimagentrylink/Cargo.toml index 266f9571..6dfef016 100644 --- a/libimagentrylink/Cargo.toml +++ b/libimagentrylink/Cargo.toml @@ -5,7 +5,7 @@ authors = ["Matthias Beyer "] [dependencies] itertools = "0.4" -log = "0.3.4" +log = "0.3" toml = "0.1.27" semver = "0.2" url = "0.5.5" From 72e53e16f637edc4eeda53cfc4a005f3f9b60db2 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Tue, 10 May 2016 17:54:47 +0200 Subject: [PATCH 024/288] Update log: 0.3.* -> 0.3 --- libimagentrylist/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libimagentrylist/Cargo.toml b/libimagentrylist/Cargo.toml index 8093905d..e8905dfe 100644 --- a/libimagentrylist/Cargo.toml +++ b/libimagentrylist/Cargo.toml @@ -5,7 +5,7 @@ authors = ["Matthias Beyer "] [dependencies] clap = "2.1.1" -log = "0.3.5" +log = "0.3" toml = "0.1.25" [dependencies.libimagstore] From eb8f5a7c92108e4743e20ece9fc1371990d5255f Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Tue, 10 May 2016 17:54:47 +0200 Subject: [PATCH 025/288] Update log: 0.3.* -> 0.3 --- libimagentrytag/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libimagentrytag/Cargo.toml b/libimagentrytag/Cargo.toml index 9b5d0b64..db2df486 100644 --- a/libimagentrytag/Cargo.toml +++ b/libimagentrytag/Cargo.toml @@ -5,7 +5,7 @@ authors = ["Matthias Beyer "] [dependencies] clap = "2.1.1" -log = "0.3.5" +log = "0.3" regex = "0.1" toml = "0.1.25" itertools = "0.4" From 40fed760d588f9ccfb9165530784e95e6e20b1fe Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Tue, 10 May 2016 17:54:47 +0200 Subject: [PATCH 026/288] Update log: 0.3.* -> 0.3 --- libimaginteraction/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libimaginteraction/Cargo.toml b/libimaginteraction/Cargo.toml index f1457ac1..e0bea398 100644 --- a/libimaginteraction/Cargo.toml +++ b/libimaginteraction/Cargo.toml @@ -6,7 +6,7 @@ authors = ["Matthias Beyer "] [dependencies] spinner = "0.4" interactor = "0.1" -log = "0.3.5" +log = "0.3" ansi_term = "0.7.2" regex = "0.1" lazy_static = "0.1.15" From dda40fb5d2f7bbd4e1b1f7128dea1c6ba9ca9dbc Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Tue, 10 May 2016 17:54:47 +0200 Subject: [PATCH 027/288] Update log: 0.3.* -> 0.3 --- libimagnotes/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libimagnotes/Cargo.toml b/libimagnotes/Cargo.toml index a6f41952..6bc99cee 100644 --- a/libimagnotes/Cargo.toml +++ b/libimagnotes/Cargo.toml @@ -5,7 +5,7 @@ authors = ["Matthias Beyer "] [dependencies] semver = "0.2" -log = "0.3.5" +log = "0.3" toml = "0.1.25" [dependencies.libimagstore] From acfff704988283a6a648c32dfd5e69145468c92e Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Tue, 10 May 2016 17:54:47 +0200 Subject: [PATCH 028/288] Update log: 0.3.* -> 0.3 --- libimagrt/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libimagrt/Cargo.toml b/libimagrt/Cargo.toml index bb37744a..6989ef69 100644 --- a/libimagrt/Cargo.toml +++ b/libimagrt/Cargo.toml @@ -6,7 +6,7 @@ authors = ["Matthias Beyer "] [dependencies] clap = "2.1.1" toml = "0.1.27" -log = "0.3.4" +log = "0.3" xdg-basedir = "0.2.2" itertools = "0.4" tempfile = "2.1.1" From 62f6478476b941794f7d7a5e21552549ac65efaa Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Tue, 10 May 2016 17:54:47 +0200 Subject: [PATCH 029/288] Update log: 0.3.* -> 0.3 --- libimagstore/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libimagstore/Cargo.toml b/libimagstore/Cargo.toml index f2af405f..7c0fbf49 100644 --- a/libimagstore/Cargo.toml +++ b/libimagstore/Cargo.toml @@ -7,7 +7,7 @@ authors = ["Matthias Beyer "] fs2 = "0.2.2" glob = "0.2.11" lazy_static = "0.1.15" -log = "0.3.5" +log = "0.3" regex = "0.1" semver = "0.2" toml = "0.1.25" From 9e0eb9f470c01a18517d0b99e8eec364e586cb52 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Tue, 10 May 2016 17:54:47 +0200 Subject: [PATCH 030/288] Update log: 0.3.* -> 0.3 --- libimagstorestdhook/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libimagstorestdhook/Cargo.toml b/libimagstorestdhook/Cargo.toml index 43bf50ed..81ba8f37 100644 --- a/libimagstorestdhook/Cargo.toml +++ b/libimagstorestdhook/Cargo.toml @@ -5,7 +5,7 @@ authors = ["Matthias Beyer "] [dependencies] toml = "0.1.25" -log = "0.3.5" +log = "0.3" fs2 = "0.2.3" [dependencies.libimagstore] From 111c8b73f04af1ae949906884ee1826bd8a859df Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Tue, 10 May 2016 17:54:47 +0200 Subject: [PATCH 031/288] Update log: 0.3.* -> 0.3 --- libimagutil/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libimagutil/Cargo.toml b/libimagutil/Cargo.toml index 873ff770..96638623 100644 --- a/libimagutil/Cargo.toml +++ b/libimagutil/Cargo.toml @@ -5,6 +5,6 @@ authors = ["Matthias Beyer "] [dependencies] lazy_static = "0.1.15" -log = "0.3.5" +log = "0.3" regex = "0.1" From 7c9e52c25e3b0623a441354749162def8eafe7c0 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Thu, 12 May 2016 17:11:58 +0200 Subject: [PATCH 032/288] Rename and make public: is_link_store_id() -> is_external_link_storeid() --- libimagentrylink/src/external.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/libimagentrylink/src/external.rs b/libimagentrylink/src/external.rs index e99abf42..0f4a06eb 100644 --- a/libimagentrylink/src/external.rs +++ b/libimagentrylink/src/external.rs @@ -105,7 +105,7 @@ pub trait ExternalLinker : InternalLinker { } /// Check whether the StoreId starts with `/link/external/` -fn is_link_store_id(id: &StoreId) -> bool { +pub fn is_external_link_storeid(id: &StoreId) -> bool { debug!("Checking whether this is a /link/external/*: '{:?}'", id); id.starts_with("/link/external/") } @@ -129,7 +129,7 @@ impl ExternalLinker for Entry { .map(|vect| { debug!("Getting external links"); vect.into_iter() - .filter(is_link_store_id) + .filter(is_external_link_storeid) .map(|id| { debug!("Retrieving entry for id: '{:?}'", id); match store.retrieve(id.clone()) { From 5972ce7f37ab630b0bf20624630bae13b5ee2beb Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Thu, 12 May 2016 17:21:04 +0200 Subject: [PATCH 033/288] Make StoreIdIterator generic This patch makes the StoreIdIterator type generic over all iterators with Item = StoreId. As the StoreIdIterator type was previousely used for iterating over a glob() result, I had to wrap this result type in another iterator type which is then wrapped in StoreIdIterator. With this patch applied, other libraries may use the StoreIdIterator type to abstract things away in their implementation. --- libimagstore/src/store.rs | 4 ++-- libimagstore/src/storeid.rs | 39 +++++++++++++++++++++++++++++++++---- 2 files changed, 37 insertions(+), 6 deletions(-) diff --git a/libimagstore/src/store.rs b/libimagstore/src/store.rs index c4d08326..db9eac3f 100644 --- a/libimagstore/src/store.rs +++ b/libimagstore/src/store.rs @@ -25,7 +25,7 @@ use walkdir::Iter as WalkDirIter; use error::{ParserErrorKind, ParserError}; use error::{StoreError, StoreErrorKind}; -use storeid::{IntoStoreId, StoreId, StoreIdIterator}; +use storeid::{IntoStoreId, StoreId, GlobStoreIdIterator, StoreIdIterator}; use lazyfile::LazyFile; use hook::aspect::Aspect; @@ -361,7 +361,7 @@ impl Store { let path = [ path, "/*" ].join(""); debug!("glob()ing with '{}'", path); glob(&path[..]) - .map(StoreIdIterator::new) + .map(|paths| StoreIdIterator::new(Box::new(GlobStoreIdIterator::new(paths)))) .map_err(|e| StoreError::new(StoreErrorKind::GlobError, Some(Box::new(e)))) } else { Err(StoreError::new(StoreErrorKind::EncodingError, None)) diff --git a/libimagstore/src/storeid.rs b/libimagstore/src/storeid.rs index d5229e2b..cdcf1676 100644 --- a/libimagstore/src/storeid.rs +++ b/libimagstore/src/storeid.rs @@ -155,10 +155,41 @@ macro_rules! module_entry_path_mod { ) } -pub struct StoreIdIterator { +pub struct GlobStoreIdIterator { paths: Paths, } +impl Debug for GlobStoreIdIterator { + + fn fmt(&self, fmt: &mut Formatter) -> RResult<(), FmtError> { + write!(fmt, "GlobStoreIdIterator") + } + +} + +impl GlobStoreIdIterator { + + pub fn new(paths: Paths) -> GlobStoreIdIterator { + GlobStoreIdIterator { + paths: paths, + } + } + +} + +impl Iterator for GlobStoreIdIterator { + type Item = StoreId; + + fn next(&mut self) -> Option { + self.paths.next().and_then(|o| o.ok()).map(|p| StoreId::from(p)) + } + +} + +pub struct StoreIdIterator { + iter: Box>, +} + impl Debug for StoreIdIterator { fn fmt(&self, fmt: &mut Formatter) -> RResult<(), FmtError> { @@ -169,9 +200,9 @@ impl Debug for StoreIdIterator { impl StoreIdIterator { - pub fn new(paths: Paths) -> StoreIdIterator { + pub fn new(iter: Box>) -> StoreIdIterator { StoreIdIterator { - paths: paths, + iter: iter, } } @@ -181,7 +212,7 @@ impl Iterator for StoreIdIterator { type Item = StoreId; fn next(&mut self) -> Option { - self.paths.next().and_then(|o| o.ok()).map(|p| StoreId::from(p)) + self.iter.next() } } From a510e1b6b6b9e2bce9b84ef94dbd61a9bb3a4c45 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Thu, 12 May 2016 17:24:27 +0200 Subject: [PATCH 034/288] Add error printing (debug) in GlobStoreIdIterator helper type --- libimagstore/src/storeid.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/libimagstore/src/storeid.rs b/libimagstore/src/storeid.rs index cdcf1676..770e620e 100644 --- a/libimagstore/src/storeid.rs +++ b/libimagstore/src/storeid.rs @@ -181,7 +181,15 @@ impl Iterator for GlobStoreIdIterator { type Item = StoreId; fn next(&mut self) -> Option { - self.paths.next().and_then(|o| o.ok()).map(|p| StoreId::from(p)) + self.paths.next().and_then(|o| { + match o { + Ok(o) => Some(o), + Err(e) => { + debug!("GlobStoreIdIterator error: {:?}", e); + None + }, + } + }).map(|p| StoreId::from(p)) } } From b9d8e5728b5246efd824f2ce77fdd5143fb86fc6 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Thu, 12 May 2016 17:27:41 +0200 Subject: [PATCH 035/288] Move GlobStoreIdIterator implementation so we can have it non-public --- libimagstore/src/store.rs | 51 ++++++++++++++++++++++++++++++++++++- libimagstore/src/storeid.rs | 40 ----------------------------- 2 files changed, 50 insertions(+), 41 deletions(-) diff --git a/libimagstore/src/store.rs b/libimagstore/src/store.rs index db9eac3f..a3f6955e 100644 --- a/libimagstore/src/store.rs +++ b/libimagstore/src/store.rs @@ -25,7 +25,7 @@ use walkdir::Iter as WalkDirIter; use error::{ParserErrorKind, ParserError}; use error::{StoreError, StoreErrorKind}; -use storeid::{IntoStoreId, StoreId, GlobStoreIdIterator, StoreIdIterator}; +use storeid::{IntoStoreId, StoreId, StoreIdIterator}; use lazyfile::LazyFile; use hook::aspect::Aspect; @@ -35,6 +35,8 @@ use hook::accessor::{ MutableHookDataAccessor, use hook::position::HookPosition; use hook::Hook; +use self::glob_store_iter::*; + /// The Result Type returned by any interaction with the store that could fail pub type Result = RResult; @@ -1253,6 +1255,53 @@ impl Entry { } +mod glob_store_iter { + use std::fmt::{Debug, Formatter}; + use std::fmt::Error as FmtError; + use glob::Paths; + use storeid::StoreId; + + pub struct GlobStoreIdIterator { + paths: Paths, + } + + impl Debug for GlobStoreIdIterator { + + fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> { + write!(fmt, "GlobStoreIdIterator") + } + + } + + impl GlobStoreIdIterator { + + pub fn new(paths: Paths) -> GlobStoreIdIterator { + GlobStoreIdIterator { + paths: paths, + } + } + + } + + impl Iterator for GlobStoreIdIterator { + type Item = StoreId; + + fn next(&mut self) -> Option { + self.paths.next().and_then(|o| { + match o { + Ok(o) => Some(o), + Err(e) => { + debug!("GlobStoreIdIterator error: {:?}", e); + None + }, + } + }).map(|p| StoreId::from(p)) + } + + } + +} + #[cfg(test)] mod test { diff --git a/libimagstore/src/storeid.rs b/libimagstore/src/storeid.rs index 770e620e..7481b6f8 100644 --- a/libimagstore/src/storeid.rs +++ b/libimagstore/src/storeid.rs @@ -3,7 +3,6 @@ use std::path::Path; use std::borrow::Borrow; use std::ops::Deref; -use glob::Paths; use semver::Version; use std::fmt::{Debug, Formatter}; use std::fmt::Error as FmtError; @@ -155,45 +154,6 @@ macro_rules! module_entry_path_mod { ) } -pub struct GlobStoreIdIterator { - paths: Paths, -} - -impl Debug for GlobStoreIdIterator { - - fn fmt(&self, fmt: &mut Formatter) -> RResult<(), FmtError> { - write!(fmt, "GlobStoreIdIterator") - } - -} - -impl GlobStoreIdIterator { - - pub fn new(paths: Paths) -> GlobStoreIdIterator { - GlobStoreIdIterator { - paths: paths, - } - } - -} - -impl Iterator for GlobStoreIdIterator { - type Item = StoreId; - - fn next(&mut self) -> Option { - self.paths.next().and_then(|o| { - match o { - Ok(o) => Some(o), - Err(e) => { - debug!("GlobStoreIdIterator error: {:?}", e); - None - }, - } - }).map(|p| StoreId::from(p)) - } - -} - pub struct StoreIdIterator { iter: Box>, } From 86f3119dd53aacf99e1f564dd782fd26639b8ca5 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Thu, 12 May 2016 16:40:06 +0200 Subject: [PATCH 036/288] Update dependency: url: 0.5.5 -> 1.1 --- imag-link/Cargo.toml | 2 +- libimagentrylink/Cargo.toml | 2 +- libimagentrylink/src/external.rs | 6 +++--- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/imag-link/Cargo.toml b/imag-link/Cargo.toml index 21e4e72b..858ff6f0 100644 --- a/imag-link/Cargo.toml +++ b/imag-link/Cargo.toml @@ -9,7 +9,7 @@ clap = "2.1.1" log = "0.3" version = "2.0.1" toml = "0.1.25" -url = "0.5.5" +url = "1.1" [dependencies.libimagstore] path = "../libimagstore" diff --git a/libimagentrylink/Cargo.toml b/libimagentrylink/Cargo.toml index 6dfef016..7ac8457e 100644 --- a/libimagentrylink/Cargo.toml +++ b/libimagentrylink/Cargo.toml @@ -8,7 +8,7 @@ itertools = "0.4" log = "0.3" toml = "0.1.27" semver = "0.2" -url = "0.5.5" +url = "1.1" rust-crypto = "0.2.35" [dependencies.libimagstore] diff --git a/libimagentrylink/src/external.rs b/libimagentrylink/src/external.rs index e99abf42..d83a1b9d 100644 --- a/libimagentrylink/src/external.rs +++ b/libimagentrylink/src/external.rs @@ -156,7 +156,7 @@ impl ExternalLinker for Entry { for link in links { // for all links let hash = { let mut s = Sha1::new(); - s.input_str(&link.serialize()[..]); + s.input_str(&link.as_str()[..]); s.result_str() }; let file_id = ModuleEntryPath::new(format!("external/{}", hash)).into_storeid(); @@ -189,7 +189,7 @@ impl ExternalLinker for Entry { Err(e) => return Err(LE::new(LEK::StoreWriteError, Some(Box::new(e)))), }; - let v = Value::String(link.serialize()); + let v = Value::String(link.into_string()); debug!("setting URL = '{:?}", v); table.insert(String::from("url"), v); @@ -231,7 +231,7 @@ impl ExternalLinker for Entry { .and_then(|links| { debug!("Removing link = '{:?}' from links = {:?}", link, links); let links = links.into_iter() - .filter(|l| l.serialize() != link.serialize()) + .filter(|l| l.as_str() != link.as_str()) .collect(); self.set_external_links(store, links) }) From 27124c2a832d1c9ecbc1f8ebef8108ee6e2621f7 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Thu, 12 May 2016 18:49:14 +0200 Subject: [PATCH 037/288] Rewrite imag binary in Rust --- bin/Cargo.toml | 10 +++ bin/imag | 79 ---------------------- bin/src/main.rs | 174 ++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 184 insertions(+), 79 deletions(-) create mode 100644 bin/Cargo.toml delete mode 100755 bin/imag create mode 100644 bin/src/main.rs diff --git a/bin/Cargo.toml b/bin/Cargo.toml new file mode 100644 index 00000000..b9d6cf22 --- /dev/null +++ b/bin/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "imag" +version = "0.1.0" +authors = ["Matthias Beyer "] + +[dependencies] +version = "2.0" +walkdir = "0.1.5" +crossbeam = "0.2.9" + diff --git a/bin/imag b/bin/imag deleted file mode 100755 index 552ea9b4..00000000 --- a/bin/imag +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/env bash - -version() { - echo "0.1.0" -} - -help() { - local cmds="$(commands)" - - echo " _ "; - echo " (_)_ __ ___ __ _ __ _ "; - echo " | | '_ \` _ \ / _\` |/ _\` |"; - echo " | | | | | | | (_| | (_| |"; - echo " |_|_| |_| |_|\__,_|\__, |"; - echo " |___/ "; - echo " -------------------------"; - cat < - - imag - the personal information management suite for the commandline - - imag is a PIM suite for the commandline. It consists of several commands, - called "modules". Each module implements one PIM aspect and all of these - modules can be used independently. - - Available commands: - $(for cmd in $cmds; do - echo -e "\t$(echo $cmd | sed -r 's,(.*)/imag-(.*),\2,')"; - done) - - Call a command with "imag " - Each command can be called with "--help" to get the respective helptext. - - Please visit https://github.com/matthiasbeyer/imag to view the source code, - follow the development of imag or maybe even contribute to imag. - - imag is free software. It is released under the terms of LGPLv2.1 - - (c) 2016 Matthias Beyer and contributors -EOS -} - -commands() { - [[ ! -z "$IMAG_IS_THE_SHIT" ]] && \ - find $IMAG_IS_THE_SHIT -type f -iname "imag-*" -print 2>/dev/null - find ${PATH//:/ } -maxdepth 1 -type f -iname "imag-*" -print 2>/dev/null -} - -main() { - case $1 in - --versions) - echo -n "imag "; version - for command in $(commands); do - $command --version - done - exit 0 - ;; - - --version) - version - exit 0 - ;; - - --help | -h) - help - exit 0 - ;; - - *) - local cmd=$1; shift - local executable=$(commands | grep $cmd | head -n 1) - exec $executable $* - ;; - - esac -} - -main $* diff --git a/bin/src/main.rs b/bin/src/main.rs new file mode 100644 index 00000000..7e23d5b7 --- /dev/null +++ b/bin/src/main.rs @@ -0,0 +1,174 @@ +extern crate crossbeam; +#[macro_use] extern crate version; +extern crate walkdir; + +use std::env; +use std::process::exit; +use std::process::Command; +use std::process::Stdio; +use std::io::ErrorKind; + +use walkdir::WalkDir; +use crossbeam::*; + +fn help(cmds: Vec) { + println!(r#" + + _ + (_)_ __ ___ __ _ __ _ + | | '_ \` _ \/ _\`|/ _\`| + | | | | | | | (_| | (_| | + |_|_| |_| |_|\__,_|\__, | + |___/ + ------------------------- + + Usage: imag [--version | --versions | -h | --help] + + imag - the personal information management suite for the commandline + + imag is a PIM suite for the commandline. It consists of several commands, + called "modules". Each module implements one PIM aspect and all of these + modules can be used independently. + + Available commands: + "#); + + for cmd in cmds.iter() { + println!("\t{}", cmd); + } + + println!(r#" + + Call a command with 'imag ' + Each command can be called with "--help" to get the respective helptext. + + Please visit https://github.com/matthiasbeyer/imag to view the source code, + follow the development of imag or maybe even contribute to imag. + + imag is free software. It is released under the terms of LGPLv2.1 + + (c) 2016 Matthias Beyer and contributors"#); +} + +fn get_commands() -> Vec { + let path = env::var("PATH"); + if path.is_err() { + println!("PATH error: {:?}", path); + exit(1); + } + let pathelements = path.unwrap(); + let pathelements = pathelements.split(":"); + + let joinhandles : Vec>> = pathelements + .map(|elem| { + crossbeam::scope(|scope| { + scope.spawn(|| { + WalkDir::new(elem) + .max_depth(1) + .into_iter() + .filter(|path| { + match path { + &Ok(ref path) => path.path().starts_with(format!("{}/imag-", elem)), + &Err(_) => false, + } + }) + .filter_map(|x| x.ok()) + .map(|path| { + path.path() + .to_str() + .map(String::from) + }) + .filter_map(|x| x) + .collect() + }) + }) + }) + .collect(); + + let mut execs = vec![]; + for joinhandle in joinhandles.into_iter() { + let mut v = joinhandle.join(); + execs.append(&mut v); + } + + execs +} + +fn main() { + let commands = get_commands(); + let mut args = env::args(); + let _ = args.next(); + let first_arg = match args.next() { + Some(s) => s, + None => { + help(commands); + exit(0); + }, + }; + + match &first_arg[..] { + "--help" | "-h" => { + help(commands); + exit(0); + }, + + "--version" => println!("imag {}", &version!()[..]), + + "--versions" => { + let mut result = vec![]; + for command in commands.iter() { + result.push(crossbeam::scope(|scope| { + scope.spawn(|| { + let v = Command::new(command).arg("--version").output(); + match v { + Ok(v) => match String::from_utf8(v.stdout) { + Ok(s) => format!("{} -> {}", command, s), + Err(e) => format!("Failed calling {} -> {:?}", command, e), + }, + Err(e) => format!("Failed calling {} -> {:?}", command, e), + } + }) + })) + } + + for versionstring in result.into_iter().map(|handle| handle.join()) { + println!("{}", versionstring); + } + }, + + s => { + match Command::new(format!("imag-{}", s)) + .stdin(Stdio::inherit()) + .stdout(Stdio::inherit()) + .stderr(Stdio::inherit()) + .spawn() + .and_then(|mut handle| handle.wait()) + { + Ok(exit_status) => { + if !exit_status.success() { + println!("{} exited with non-zero exit code", s); + exit(exit_status.code().unwrap_or(42)); + } + }, + + Err(e) => { + match e.kind() { + ErrorKind::NotFound => { + println!("No such command: 'imag-{}'", s); + exit(2); + }, + ErrorKind::PermissionDenied => { + println!("No permission to execute: 'imag-{}'", s); + exit(1); + }, + _ => { + println!("Error spawning: {:?}", e); + exit(1337); + } + } + } + } + + }, + } +} From 580c9e5286bddd5cea02721e72438a786edbb1b5 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Fri, 13 May 2016 14:41:11 +0200 Subject: [PATCH 038/288] Add command finder helper function --- bin/src/main.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/bin/src/main.rs b/bin/src/main.rs index 7e23d5b7..925fb49f 100644 --- a/bin/src/main.rs +++ b/bin/src/main.rs @@ -94,11 +94,15 @@ fn get_commands() -> Vec { execs } +fn find_command() -> Option { + env::args().skip(1).filter(|x| !x.starts_with("-")).next() +} + fn main() { let commands = get_commands(); let mut args = env::args(); let _ = args.next(); - let first_arg = match args.next() { + let first_arg = match find_command() { Some(s) => s, None => { help(commands); From eca41e04dd8879592fba1a900342e817c3543555 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Fri, 13 May 2016 14:41:19 +0200 Subject: [PATCH 039/288] Add argument finder helper function --- bin/src/main.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/bin/src/main.rs b/bin/src/main.rs index 925fb49f..3b154a47 100644 --- a/bin/src/main.rs +++ b/bin/src/main.rs @@ -98,6 +98,14 @@ fn find_command() -> Option { env::args().skip(1).filter(|x| !x.starts_with("-")).next() } +fn find_args(command: &str) -> Vec { + env::args() + .skip(1) + .position(|e| e == command) + .map(|pos| env::args().skip(pos + 2).collect::>()) + .unwrap_or(vec![]) +} + fn main() { let commands = get_commands(); let mut args = env::args(); @@ -145,6 +153,7 @@ fn main() { .stdin(Stdio::inherit()) .stdout(Stdio::inherit()) .stderr(Stdio::inherit()) + .args(&find_args(s)[..]) .spawn() .and_then(|mut handle| handle.wait()) { From dfd6a9b0d370b841d6591e0d292bc5c7fa2fe76f Mon Sep 17 00:00:00 2001 From: Andre Bogus Date: Tue, 3 May 2016 00:57:41 +0200 Subject: [PATCH 040/288] style adaptations these were introduced following suggestions from https://crates.io/crate/clippy --- imag-counter/src/create.rs | 2 +- imag-counter/src/interactive.rs | 12 ++--- imag-counter/src/list.rs | 9 ++-- imag-link/src/main.rs | 12 ++--- imag-notes/src/main.rs | 7 ++- imag-store/src/create.rs | 30 +++++------- imag-store/src/error.rs | 24 ++++------ imag-store/src/util.rs | 48 ++++++++++--------- imag-tag/src/main.rs | 8 ++-- imag-view/src/error.rs | 16 +++---- imag-view/src/main.rs | 6 +-- libimagcounter/src/counter.rs | 4 +- libimagcounter/src/error.rs | 17 ++++--- .../src/builtin/header/field_gt.rs | 6 +-- .../src/builtin/header/field_isempty.rs | 6 +-- .../src/builtin/header/field_istype.rs | 10 ++-- .../src/builtin/header/field_lt.rs | 6 +-- .../src/builtin/header/version/eq.rs | 3 +- .../src/builtin/header/version/gt.rs | 3 +- .../src/builtin/header/version/lt.rs | 3 +- 20 files changed, 105 insertions(+), 127 deletions(-) diff --git a/imag-counter/src/create.rs b/imag-counter/src/create.rs index 66f6590d..1b2838a5 100644 --- a/imag-counter/src/create.rs +++ b/imag-counter/src/create.rs @@ -17,7 +17,7 @@ pub fn create(rt: &Runtime) { .and_then(|i| FromStr::from_str(i).ok()) .unwrap_or(0); - match Counter::new(rt.store(), String::from(name.clone()), init) { + match Counter::new(rt.store(), String::from(name), init) { Err(e) => { warn!("Could not create Counter '{}' with initial value '{}'", name, init); trace_error(&e); diff --git a/imag-counter/src/interactive.rs b/imag-counter/src/interactive.rs index 03e6b40e..5a2b1e01 100644 --- a/imag-counter/src/interactive.rs +++ b/imag-counter/src/interactive.rs @@ -51,7 +51,7 @@ pub fn interactive(rt: &Runtime) { exit(1); } - let cont = if input.len() > 0 { + let cont = if !input.is_empty() { let increment = match input.chars().next() { Some('-') => false, _ => true }; input.chars().all(|chr| { match pairs.get_mut(&chr) { @@ -94,8 +94,8 @@ pub fn interactive(rt: &Runtime) { fn has_quit_binding(pairs: &BTreeMap) -> bool { pairs.iter() .any(|(_, bind)| { - match bind { - &Binding::Function(ref name, _) => name == "quit", + match *bind { + Binding::Function(ref name, _) => name == "quit", _ => false, } }) @@ -109,8 +109,8 @@ enum Binding<'a> { impl<'a> Display for Binding<'a> { fn fmt(&self, fmt: &mut Formatter) -> RResult<(), Error> { - match self { - &Binding::Counter(ref c) => { + match *self { + Binding::Counter(ref c) => { match c.name() { Ok(name) => { try!(write!(fmt, "{}", name)); @@ -122,7 +122,7 @@ impl<'a> Display for Binding<'a> { }, } }, - &Binding::Function(ref name, _) => write!(fmt, "{}()", name), + Binding::Function(ref name, _) => write!(fmt, "{}()", name), } } diff --git a/imag-counter/src/list.rs b/imag-counter/src/list.rs index b7276957..41e9ce62 100644 --- a/imag-counter/src/list.rs +++ b/imag-counter/src/list.rs @@ -16,13 +16,10 @@ pub fn list(rt: &Runtime) { if name.is_err() { trace_error(&name.unwrap_err()); + } else if value.is_err() { + trace_error(&value.unwrap_err()); } else { - - if value.is_err() { - trace_error(&value.unwrap_err()); - } else { - println!("{} - {}", name.unwrap(), value.unwrap()); - } + println!("{} - {}", name.unwrap(), value.unwrap()); } }) .map_err(|e| trace_error(&e)) diff --git a/imag-link/src/main.rs b/imag-link/src/main.rs index 70f1d019..2c1cf5fb 100644 --- a/imag-link/src/main.rs +++ b/imag-link/src/main.rs @@ -81,16 +81,14 @@ fn handle_internal_linking(rt: &Runtime) { if cmd.is_present("list") { debug!("List..."); - for entry in cmd.value_of("list").unwrap().split(",") { + for entry in cmd.value_of("list").unwrap().split(',') { debug!("Listing for '{}'", entry); match get_entry_by_name(rt, entry) { Ok(e) => { e.get_internal_links() .map(|links| { - let mut i = 0; - for link in links.iter().map(|l| l.to_str()).filter_map(|x| x) { + for (i, link) in links.iter().map(|l| l.to_str()).filter_map(|x| x).enumerate() { println!("{: <3}: {}", i, link); - i += 1; } }) .map_err(|e| trace_error(&e)) @@ -275,7 +273,7 @@ fn set_links_for_entry(store: &Store, matches: &ArgMatches, entry: &mut FileLock .value_of("links") .map(String::from) .unwrap() - .split(",") + .split(',') .map(|uri| { match Url::parse(uri) { Err(e) => { @@ -299,10 +297,8 @@ fn set_links_for_entry(store: &Store, matches: &ArgMatches, entry: &mut FileLock fn list_links_for_entry(store: &Store, entry: &mut FileLockEntry) { let res = entry.get_external_links(store) .and_then(|links| { - let mut i = 0; - for link in links { + for (i, link) in links.enumerate() { println!("{: <3}: {}", i, link); - i += 1; } Ok(()) }); diff --git a/imag-notes/src/main.rs b/imag-notes/src/main.rs index bea757fa..ee0df3d3 100644 --- a/imag-notes/src/main.rs +++ b/imag-notes/src/main.rs @@ -60,10 +60,9 @@ fn create(rt: &Runtime) { .map_err(|e| trace_error(&e)) .ok(); - if rt.cli().subcommand_matches("create").unwrap().is_present("edit") { - if !edit_entry(rt, name) { - exit(1); - } + if rt.cli().subcommand_matches("create").unwrap().is_present("edit") && + !edit_entry(rt, name) { + exit(1); } } diff --git a/imag-store/src/create.rs b/imag-store/src/create.rs index a8b85ad3..52c105b0 100644 --- a/imag-store/src/create.rs +++ b/imag-store/src/create.rs @@ -60,30 +60,24 @@ pub fn create(rt: &Runtime) { fn create_from_cli_spec(rt: &Runtime, matches: &ArgMatches, path: &PathBuf) -> Result<()> { let content = matches.subcommand_matches("entry") - .map(|entry_subcommand| { + .map_or_else(|| { + debug!("Didn't find entry subcommand, getting raw content"); + matches.value_of("from-raw") + .map_or_else(String::new, string_from_raw_src) + }, |entry_subcommand| { debug!("Found entry subcommand, parsing content"); entry_subcommand .value_of("content") - .map(String::from) - .unwrap_or_else(|| { - entry_subcommand - .value_of("content-from") - .map(|src| string_from_raw_src(src)) - .unwrap_or(String::new()) - }) - }) - .unwrap_or_else(|| { - debug!("Didn't find entry subcommand, getting raw content"); - matches.value_of("from-raw") - .map(|raw_src| string_from_raw_src(raw_src)) - .unwrap_or(String::new()) + .map_or_else(|| { + entry_subcommand.value_of("content-from") + .map_or_else(String::new, string_from_raw_src) + }, String::from) }); - debug!("Got content with len = {}", content.len()); let header = matches.subcommand_matches("entry") - .map(|entry_matches| build_toml_header(entry_matches, EntryHeader::new())) - .unwrap_or(EntryHeader::new()); + .map_or_else(EntryHeader::new, + |entry_matches| build_toml_header(entry_matches, EntryHeader::new())); create_with_content_and_header(rt, path, content, header) } @@ -91,7 +85,7 @@ fn create_from_cli_spec(rt: &Runtime, matches: &ArgMatches, path: &PathBuf) -> R fn create_from_source(rt: &Runtime, matches: &ArgMatches, path: &PathBuf) -> Result<()> { let content = matches .value_of("from-raw") - .ok_or(StoreError::new(StoreErrorKind::NoCommandlineCall, None)) + .ok_or_else(|| StoreError::new(StoreErrorKind::NoCommandlineCall, None)) .map(|raw_src| string_from_raw_src(raw_src)); if content.is_err() { diff --git a/imag-store/src/error.rs b/imag-store/src/error.rs index a9884250..30c9c8b5 100644 --- a/imag-store/src/error.rs +++ b/imag-store/src/error.rs @@ -3,20 +3,18 @@ use std::fmt::Error as FmtError; use std::clone::Clone; use std::fmt::{Display, Formatter}; -/** - * Kind of store error - */ #[derive(Clone, Copy, Debug, PartialEq)] +/// Kind of store error pub enum StoreErrorKind { BackendError, NoCommandlineCall, - // maybe more + // maybe more } fn store_error_type_as_str(e: &StoreErrorKind) -> &'static str { - match e { - &StoreErrorKind::BackendError => "Backend Error", - &StoreErrorKind::NoCommandlineCall => "No commandline call", + match *e { + StoreErrorKind::BackendError => "Backend Error", + StoreErrorKind::NoCommandlineCall => "No commandline call", } } @@ -37,9 +35,7 @@ pub struct StoreError { impl StoreError { - /** - * Build a new StoreError from an StoreErrorKind, optionally with cause - */ + ///Build a new StoreError from an StoreErrorKind, optionally with cause pub fn new(errtype: StoreErrorKind, cause: Option>) -> StoreError { @@ -49,11 +45,9 @@ impl StoreError { } } - /** - * Get the error type of this StoreError - */ + /// Get the error type of this StoreError pub fn err_type(&self) -> StoreErrorKind { - self.err_type.clone() + self.err_type } } @@ -70,7 +64,7 @@ impl Display for StoreError { impl Error for StoreError { fn description(&self) -> &str { - store_error_type_as_str(&self.err_type.clone()) + store_error_type_as_str(&self.err_type) } fn cause(&self) -> Option<&Error> { diff --git a/imag-store/src/util.rs b/imag-store/src/util.rs index f14d462b..197f2846 100644 --- a/imag-store/src/util.rs +++ b/imag-store/src/util.rs @@ -1,4 +1,5 @@ -use std::collections::BTreeMap; +use std::borrow::Cow; +use std::collections::btree_map::{BTreeMap, Entry}; use std::str::Split; use clap::ArgMatches; @@ -21,10 +22,10 @@ pub fn build_toml_header(matches: &ArgMatches, header: EntryHeader) -> EntryHead for tpl in kvs { let (key, value) = tpl.into(); debug!("Splitting: {:?}", key); - let mut split = key.split("."); + let mut split = key.split('.'); let current = split.next(); if current.is_some() { - insert_key_into(String::from(current.unwrap()), &mut split, value, &mut main); + insert_key_into(String::from(current.unwrap()), &mut split, Cow::Owned(value), &mut main); } } @@ -36,9 +37,9 @@ pub fn build_toml_header(matches: &ArgMatches, header: EntryHeader) -> EntryHead } } -fn insert_key_into(current: String, - rest_path: &mut Split<&str>, - value: String, +fn insert_key_into<'a>(current: String, + rest_path: &mut Split, + value: Cow<'a, str>, map: &mut BTreeMap) { let next = rest_path.next(); @@ -47,27 +48,30 @@ fn insert_key_into(current: String, map.insert(current, parse_value(value)); } else { debug!("Inserting into {:?} ... = {:?}", current, value); - if map.contains_key(¤t) { - match map.get_mut(¤t).unwrap() { - &mut Value::Table(ref mut t) => { - insert_key_into(String::from(next.unwrap()), rest_path, value, t); - }, - _ => unreachable!(), + match map.entry(current) { + Entry::Occupied(ref mut e) => { + match *e.get_mut() { + Value::Table(ref mut t) => { + insert_key_into(String::from(next.unwrap()), rest_path, value, t); + }, + _ => unreachable!(), + } + }, + Entry::Vacant(v) => { v.insert(Value::Table( { + let mut submap = BTreeMap::new(); + insert_key_into(String::from(next.unwrap()), rest_path, value, &mut submap); + debug!("Inserting submap = {:?}", submap); + submap })); } - } else { - let mut submap = BTreeMap::new(); - insert_key_into(String::from(next.unwrap()), rest_path, value, &mut submap); - debug!("Inserting submap = {:?}", submap); - map.insert(current, Value::Table(submap)); } } } -fn parse_value(value: String) -> Value { +fn parse_value(value: Cow) -> Value { use std::str::FromStr; - fn is_ary(v: &String) -> bool { - v.chars().next() == Some('[') && v.chars().last() == Some(']') && v.len() >= 3 + fn is_ary(v: &str) -> bool { + v.starts_with('[') && v.ends_with(']') && v.len() >= 3 } if value == "true" { @@ -79,7 +83,7 @@ fn parse_value(value: String) -> Value { } else if is_ary(&value) { debug!("Building Array out of: {:?}...", value); let sub = &value[1..(value.len()-1)]; - Value::Array(sub.split(",").map(|v| parse_value(String::from(v))).collect()) + Value::Array(sub.split(',').map(|x| parse_value(Cow::from(x))).collect()) } else { FromStr::from_str(&value[..]) .map(|i: i64| { @@ -94,7 +98,7 @@ fn parse_value(value: String) -> Value { }) .unwrap_or_else(|_| { debug!("Building String out of: {:?}...", value); - Value::String(value) + Value::String(value.into_owned()) }) }) } diff --git a/imag-tag/src/main.rs b/imag-tag/src/main.rs index e1a35a34..9ed409a3 100644 --- a/imag-tag/src/main.rs +++ b/imag-tag/src/main.rs @@ -77,8 +77,7 @@ fn alter(rt: &Runtime, id: &str, add: Option<&str>, rem: Option<&str>, set: Opti .retrieve(path) .map(|mut e| { add.map(|tags| { - let tags = tags.split(","); - for tag in tags { + for tag in tags.split(',') { info!("Adding tag '{}'", tag); if let Err(e) = e.add_tag(String::from(tag)) { trace_error(&e); @@ -87,8 +86,7 @@ fn alter(rt: &Runtime, id: &str, add: Option<&str>, rem: Option<&str>, set: Opti }); rem.map(|tags| { - let tags = tags.split(","); - for tag in tags { + for tag in tags.split(',') { info!("Removing tag '{}'", tag); if let Err(e) = e.remove_tag(String::from(tag)) { trace_error(&e); @@ -98,7 +96,7 @@ fn alter(rt: &Runtime, id: &str, add: Option<&str>, rem: Option<&str>, set: Opti set.map(|tags| { info!("Setting tags '{}'", tags); - let tags = tags.split(",").map(String::from).collect(); + let tags = tags.split(',').map(String::from).collect(); if let Err(e) = e.set_tags(tags) { trace_error(&e); } diff --git a/imag-view/src/error.rs b/imag-view/src/error.rs index bdbb1d76..ab73bfe8 100644 --- a/imag-view/src/error.rs +++ b/imag-view/src/error.rs @@ -15,11 +15,11 @@ pub enum ViewErrorKind { } fn view_error_type_as_str(e: &ViewErrorKind) -> &'static str { - match e { - &ViewErrorKind::StoreError => "Store error", - &ViewErrorKind::NoVersion => "No version specified", - &ViewErrorKind::PatternError => "Error in Pattern", - &ViewErrorKind::GlobBuildError => "Could not build glob() Argument", + match *e { + ViewErrorKind::StoreError => "Store error", + ViewErrorKind::NoVersion => "No version specified", + ViewErrorKind::PatternError => "Error in Pattern", + ViewErrorKind::GlobBuildError => "Could not build glob() Argument", } } @@ -59,7 +59,7 @@ impl ViewError { * Get the error type of this ViewError */ pub fn err_type(&self) -> ViewErrorKind { - self.err_type.clone() + self.err_type } } @@ -67,7 +67,7 @@ impl ViewError { impl Display for ViewError { fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> { - try!(write!(fmt, "[{}]", view_error_type_as_str(&self.err_type.clone()))); + try!(write!(fmt, "[{}]", view_error_type_as_str(&self.err_type))); Ok(()) } @@ -76,7 +76,7 @@ impl Display for ViewError { impl Error for ViewError { fn description(&self) -> &str { - view_error_type_as_str(&self.err_type.clone()) + view_error_type_as_str(&self.err_type) } fn cause(&self) -> Option<&Error> { diff --git a/imag-view/src/main.rs b/imag-view/src/main.rs index f12e639d..100d9aab 100644 --- a/imag-view/src/main.rs +++ b/imag-view/src/main.rs @@ -129,7 +129,7 @@ fn load_entry<'a>(id: &str, let version = { if version.is_none() { - let r = id.split("~").last(); + let r = id.split('~').last(); if r.is_none() { warn!("No version"); return Err(ViewError::new(ViewErrorKind::NoVersion, None)); @@ -144,7 +144,7 @@ fn load_entry<'a>(id: &str, debug!("Building path from {:?} and {:?}", id, version); let mut path = rt.store().path().clone(); - if id.chars().next() == Some('/') { + if id.starts_with('/') { path.push(format!("{}~{}", &id[1..id.len()], version)); } else { path.push(format!("{}~{}", id, version)); @@ -161,7 +161,7 @@ fn view_versions_of(id: &str, rt: &Runtime) -> Result<()> { let mut path = rt.store().path().clone(); - if id.chars().next() == Some('/') { + if id.starts_with('/') { path.push(format!("{}~*", &id[1..id.len()])); } else { path.push(format!("{}~*", id)); diff --git a/libimagcounter/src/counter.rs b/libimagcounter/src/counter.rs index 2285071f..a93046f7 100644 --- a/libimagcounter/src/counter.rs +++ b/libimagcounter/src/counter.rs @@ -144,12 +144,12 @@ impl<'a> Counter<'a> { } trait FromStoreId { - fn from_storeid<'a>(&'a Store, StoreId) -> Result>; + fn from_storeid(&Store, StoreId) -> Result; } impl<'a> FromStoreId for Counter<'a> { - fn from_storeid<'b>(store: &'b Store, id: StoreId) -> Result> { + fn from_storeid(store: &Store, id: StoreId) -> Result { debug!("Loading counter from storeid: '{:?}'", id); match store.retrieve(id) { Err(e) => Err(CE::new(CEK::StoreReadError, Some(Box::new(e)))), diff --git a/libimagcounter/src/error.rs b/libimagcounter/src/error.rs index f1c842f7..1aa347a6 100644 --- a/libimagcounter/src/error.rs +++ b/libimagcounter/src/error.rs @@ -1,6 +1,5 @@ use std::error::Error; use std::fmt::Error as FmtError; -use std::clone::Clone; use std::fmt::{Display, Formatter}; /** @@ -15,11 +14,11 @@ pub enum CounterErrorKind { } fn counter_error_type_as_str(e: &CounterErrorKind) -> &'static str { - match e { - &CounterErrorKind::StoreReadError => "Store read error", - &CounterErrorKind::StoreWriteError => "Store write error", - &CounterErrorKind::HeaderTypeError => "Header type error", - &CounterErrorKind::HeaderFieldMissingError => "Header field missing error", + match *e { + CounterErrorKind::StoreReadError => "Store read error", + CounterErrorKind::StoreWriteError => "Store write error", + CounterErrorKind::HeaderTypeError => "Header type error", + CounterErrorKind::HeaderFieldMissingError => "Header field missing error", } } @@ -59,7 +58,7 @@ impl CounterError { * Get the error type of this CounterError */ pub fn err_type(&self) -> CounterErrorKind { - self.err_type.clone() + self.err_type } } @@ -67,7 +66,7 @@ impl CounterError { impl Display for CounterError { fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> { - try!(write!(fmt, "[{}]", counter_error_type_as_str(&self.err_type.clone()))); + try!(write!(fmt, "[{}]", counter_error_type_as_str(&self.err_type))); Ok(()) } @@ -76,7 +75,7 @@ impl Display for CounterError { impl Error for CounterError { fn description(&self) -> &str { - counter_error_type_as_str(&self.err_type.clone()) + counter_error_type_as_str(&self.err_type) } fn cause(&self) -> Option<&Error> { diff --git a/libimagentryfilter/src/builtin/header/field_gt.rs b/libimagentryfilter/src/builtin/header/field_gt.rs index 6975737b..7067399d 100644 --- a/libimagentryfilter/src/builtin/header/field_gt.rs +++ b/libimagentryfilter/src/builtin/header/field_gt.rs @@ -14,15 +14,15 @@ struct EqGt { impl Predicate for EqGt { fn evaluate(&self, v: Value) -> bool { - match &self.comp { - &Value::Integer(i) => { + match self.comp { + Value::Integer(i) => { match v { Value::Integer(j) => i > j, Value::Float(f) => (i as f64) > f, _ => false, } }, - &Value::Float(f) => { + Value::Float(f) => { match v { Value::Integer(i) => f > (i as f64), Value::Float(d) => f > d, diff --git a/libimagentryfilter/src/builtin/header/field_isempty.rs b/libimagentryfilter/src/builtin/header/field_isempty.rs index a7ff4ab1..3da9360f 100644 --- a/libimagentryfilter/src/builtin/header/field_isempty.rs +++ b/libimagentryfilter/src/builtin/header/field_isempty.rs @@ -27,11 +27,11 @@ impl Filter for FieldIsEmpty { .map(|v| { match v { Some(Value::Array(a)) => a.is_empty(), - Some(Value::Boolean(_)) => false, - Some(Value::Float(_)) => false, - Some(Value::Integer(_)) => false, Some(Value::String(s)) => s.is_empty(), Some(Value::Table(t)) => t.is_empty(), + Some(Value::Boolean(_)) | + Some(Value::Float(_)) | + Some(Value::Integer(_)) => false, _ => true, } }) diff --git a/libimagentryfilter/src/builtin/header/field_istype.rs b/libimagentryfilter/src/builtin/header/field_istype.rs index 8423c0ab..5af73623 100644 --- a/libimagentryfilter/src/builtin/header/field_istype.rs +++ b/libimagentryfilter/src/builtin/header/field_istype.rs @@ -21,11 +21,11 @@ impl Type { fn matches(&self, v: &Value) -> bool { match (self, v) { - (&Type::String, &Value::String(_)) => true, - (&Type::Integer, &Value::Integer(_)) => true, - (&Type::Float, &Value::Float(_)) => true, - (&Type::Boolean, &Value::Boolean(_)) => true, - (&Type::Array, &Value::Array(_)) => true, + (&Type::String, &Value::String(_)) | + (&Type::Integer, &Value::Integer(_)) | + (&Type::Float, &Value::Float(_)) | + (&Type::Boolean, &Value::Boolean(_)) | + (&Type::Array, &Value::Array(_)) | (&Type::Table, &Value::Table(_)) => true, _ => false, } diff --git a/libimagentryfilter/src/builtin/header/field_lt.rs b/libimagentryfilter/src/builtin/header/field_lt.rs index 15558d4b..dee98476 100644 --- a/libimagentryfilter/src/builtin/header/field_lt.rs +++ b/libimagentryfilter/src/builtin/header/field_lt.rs @@ -14,15 +14,15 @@ struct EqLt { impl Predicate for EqLt { fn evaluate(&self, v: Value) -> bool { - match &self.comp { - &Value::Integer(i) => { + match self.comp { + Value::Integer(i) => { match v { Value::Integer(j) => i < j, Value::Float(f) => (i as f64) < f, _ => false, } }, - &Value::Float(f) => { + Value::Float(f) => { match v { Value::Integer(i) => f < (i as f64), Value::Float(d) => f < d, diff --git a/libimagentryfilter/src/builtin/header/version/eq.rs b/libimagentryfilter/src/builtin/header/version/eq.rs index 0e28cfb2..e6b93893 100644 --- a/libimagentryfilter/src/builtin/header/version/eq.rs +++ b/libimagentryfilter/src/builtin/header/version/eq.rs @@ -23,7 +23,7 @@ impl Filter for VersionEq { e.get_header() .read("imag.version") .map(|val| { - val.map(|v| { + val.map_or(false, |v| { match v { Value::String(s) => { match Version::parse(&s[..]) { @@ -34,7 +34,6 @@ impl Filter for VersionEq { _ => false, } }) - .unwrap_or(false) }) .unwrap_or(false) } diff --git a/libimagentryfilter/src/builtin/header/version/gt.rs b/libimagentryfilter/src/builtin/header/version/gt.rs index 119e64a8..f03b0fa9 100644 --- a/libimagentryfilter/src/builtin/header/version/gt.rs +++ b/libimagentryfilter/src/builtin/header/version/gt.rs @@ -23,7 +23,7 @@ impl Filter for VersionGt { e.get_header() .read("imag.version") .map(|val| { - val.map(|v| { + val.map_or(false, |v| { match v { Value::String(s) => { match Version::parse(&s[..]) { @@ -34,7 +34,6 @@ impl Filter for VersionGt { _ => false, } }) - .unwrap_or(false) }) .unwrap_or(false) } diff --git a/libimagentryfilter/src/builtin/header/version/lt.rs b/libimagentryfilter/src/builtin/header/version/lt.rs index 6263f6de..5be6a191 100644 --- a/libimagentryfilter/src/builtin/header/version/lt.rs +++ b/libimagentryfilter/src/builtin/header/version/lt.rs @@ -23,7 +23,7 @@ impl Filter for VersionLt { e.get_header() .read("imag.version") .map(|val| { - val.map(|v| { + val.map_or(false, |v| { match v { Value::String(s) => { match Version::parse(&s[..]) { @@ -34,7 +34,6 @@ impl Filter for VersionLt { _ => false, } }) - .unwrap_or(false) }) .unwrap_or(false) } From 5ac661c3347e5aa3e141e3065e8c077053f4d34c Mon Sep 17 00:00:00 2001 From: Andre Bogus Date: Tue, 3 May 2016 01:23:06 +0200 Subject: [PATCH 041/288] fixed imag-link iterator error --- imag-link/src/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imag-link/src/main.rs b/imag-link/src/main.rs index 2c1cf5fb..8e2399df 100644 --- a/imag-link/src/main.rs +++ b/imag-link/src/main.rs @@ -297,7 +297,7 @@ fn set_links_for_entry(store: &Store, matches: &ArgMatches, entry: &mut FileLock fn list_links_for_entry(store: &Store, entry: &mut FileLockEntry) { let res = entry.get_external_links(store) .and_then(|links| { - for (i, link) in links.enumerate() { + for (i, link) in links.iter().enumerate() { println!("{: <3}: {}", i, link); } Ok(()) From 7a46df312549d6bf97b6ebcb40599061c57ca55e Mon Sep 17 00:00:00 2001 From: Andre Bogus Date: Tue, 3 May 2016 01:24:38 +0200 Subject: [PATCH 042/288] fixed unneeded import --- imag-view/src/error.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/imag-view/src/error.rs b/imag-view/src/error.rs index ab73bfe8..7a1ede78 100644 --- a/imag-view/src/error.rs +++ b/imag-view/src/error.rs @@ -1,6 +1,5 @@ use std::error::Error; use std::fmt::Error as FmtError; -use std::clone::Clone; use std::fmt::{Display, Formatter}; /** From 981707c9c959668e09f83926f6dafa296e84ebf0 Mon Sep 17 00:00:00 2001 From: Andre Bogus Date: Tue, 3 May 2016 23:10:32 +0200 Subject: [PATCH 043/288] more style adaptations again following clippy --- libimagentrylink/src/error.rs | 18 ++--- libimagentrylink/src/external.rs | 8 +- libimagentrylink/src/internal.rs | 6 +- libimagentrylist/src/error.rs | 17 ++-- libimagentrytag/src/error.rs | 15 ++-- libimagentrytag/src/exec.rs | 14 ++-- libimagentrytag/src/tag.rs | 1 + libimagentrytag/src/tagable.rs | 42 +++++----- libimagentrytag/src/ui.rs | 6 +- libimagentrytag/src/util.rs | 2 +- libimagentryview/src/error.rs | 7 +- libimaginteraction/src/ask.rs | 31 +++---- libimaginteraction/src/error.rs | 11 ++- libimagnotes/src/error.rs | 17 ++-- libimagnotes/src/note.rs | 12 +-- libimagrt/src/configuration.rs | 93 ++++++++------------- libimagrt/src/error.rs | 8 +- libimagrt/src/runtime.rs | 20 +++-- libimagstore/src/configuration.rs | 74 ++++++++--------- libimagstore/src/error.rs | 63 +++++++-------- libimagstore/src/hook/aspect.rs | 18 ++--- libimagstore/src/hook/error.rs | 13 ++- libimagstore/src/lazyfile.rs | 8 +- libimagstore/src/store.rs | 112 ++++++++++++-------------- libimagstore/src/storeid.rs | 6 +- libimagstorestdhook/src/debug.rs | 14 ++-- libimagstorestdhook/src/flock.rs | 6 +- libimagstorestdhook/src/linkverify.rs | 6 +- libimagutil/src/trace.rs | 2 +- 29 files changed, 298 insertions(+), 352 deletions(-) diff --git a/libimagentrylink/src/error.rs b/libimagentrylink/src/error.rs index bdf7ccb1..a26e3d58 100644 --- a/libimagentrylink/src/error.rs +++ b/libimagentrylink/src/error.rs @@ -15,29 +15,29 @@ pub enum LinkErrorKind { } fn link_error_type_as_str(e: &LinkErrorKind) -> &'static str { - match e { - &LinkErrorKind::EntryHeaderReadError + match *e { + LinkErrorKind::EntryHeaderReadError => "Error while reading an entry header", - &LinkErrorKind::EntryHeaderWriteError + LinkErrorKind::EntryHeaderWriteError => "Error while writing an entry header", - &LinkErrorKind::ExistingLinkTypeWrong + LinkErrorKind::ExistingLinkTypeWrong => "Existing link entry has wrong type", - &LinkErrorKind::LinkTargetDoesNotExist + LinkErrorKind::LinkTargetDoesNotExist => "Link target does not exist in the store", - &LinkErrorKind::InternalConversionError + LinkErrorKind::InternalConversionError => "Error while converting values internally", - &LinkErrorKind::InvalidUri + LinkErrorKind::InvalidUri => "URI is not valid", - &LinkErrorKind::StoreReadError + LinkErrorKind::StoreReadError => "Store read error", - &LinkErrorKind::StoreWriteError + LinkErrorKind::StoreWriteError => "Store write error", } } diff --git a/libimagentrylink/src/external.rs b/libimagentrylink/src/external.rs index fb791b9e..486ab306 100644 --- a/libimagentrylink/src/external.rs +++ b/libimagentrylink/src/external.rs @@ -31,7 +31,7 @@ use url::Url; use crypto::sha1::Sha1; use crypto::digest::Digest; -/// "Link" Type, just an abstraction over FileLockEntry to have some convenience internally. +/// "Link" Type, just an abstraction over `FileLockEntry` to have some convenience internally. struct Link<'a> { link: FileLockEntry<'a> } @@ -57,7 +57,7 @@ impl<'a> Link<'a> { .map_err(|e| LE::new(LEK::StoreReadError, Some(Box::new(e)))) } - /// Get a link Url object from a FileLockEntry, ignore errors. + /// Get a link Url object from a `FileLockEntry`, ignore errors. fn get_link_uri_from_filelockentry(file: &FileLockEntry<'a>) -> Option { file.get_header() .read("imag.content.uri") @@ -78,7 +78,7 @@ impl<'a> Link<'a> { match opt { Ok(Some(Value::String(s))) => { Url::parse(&s[..]) - .map(|s| Some(s)) + .map(Some) .map_err(|e| LE::new(LEK::EntryHeaderReadError, Some(Box::new(e)))) }, Ok(None) => Ok(None), @@ -115,7 +115,7 @@ fn get_external_link_from_file(entry: &FileLockEntry) -> Result { .ok_or(LE::new(LEK::StoreReadError, None)) } -/// Implement ExternalLinker for Entry, hiding the fact that there is no such thing as an external +/// Implement `ExternalLinker` for `Entry`, hiding the fact that there is no such thing as an external /// link in an entry, but internal links to other entries which serve as external links, as one /// entry in the store can only have one external link. impl ExternalLinker for Entry { diff --git a/libimagentrylink/src/internal.rs b/libimagentrylink/src/internal.rs index a410349a..16186ddb 100644 --- a/libimagentrylink/src/internal.rs +++ b/libimagentrylink/src/internal.rs @@ -92,9 +92,9 @@ impl InternalLinker for Entry { fn links_into_values(links: Vec) -> Vec> { links .into_iter() - .map(|s| s.to_str().map(|s| String::from(s))) + .map(|s| s.to_str().map(String::from)) .unique() - .map(|elem| elem.map(|s| Value::String(s))) + .map(|elem| elem.map(Value::String)) .sorted_by(|a, b| { match (a, b) { (&Some(Value::String(ref a)), &Some(Value::String(ref b))) => Ord::cmp(a, b), @@ -160,7 +160,7 @@ fn process_rw_result(links: StoreResult>) -> Result> { } }; - if !links.iter().all(|l| match l { &Value::String(_) => true, _ => false }) { + if !links.iter().all(|l| match *l { Value::String(_) => true, _ => false }) { debug!("At least one of the Values which were expected in the Array of links is a non-String!"); debug!("Generating LinkError"); return Err(LinkError::new(LinkErrorKind::ExistingLinkTypeWrong, None)); diff --git a/libimagentrylist/src/error.rs b/libimagentrylist/src/error.rs index f4b3c159..24051753 100644 --- a/libimagentrylist/src/error.rs +++ b/libimagentrylist/src/error.rs @@ -1,6 +1,5 @@ use std::error::Error; use std::fmt::Error as FmtError; -use std::clone::Clone; use std::fmt::{Display, Formatter}; /** @@ -15,11 +14,11 @@ pub enum ListErrorKind { } fn counter_error_type_as_str(err: &ListErrorKind) -> &'static str{ - match err { - &ListErrorKind::FormatError => "FormatError", - &ListErrorKind::EntryError => "EntryError", - &ListErrorKind::IterationError => "IterationError", - &ListErrorKind::CLIError => "No CLI subcommand for listing entries", + match *err { + ListErrorKind::FormatError => "FormatError", + ListErrorKind::EntryError => "EntryError", + ListErrorKind::IterationError => "IterationError", + ListErrorKind::CLIError => "No CLI subcommand for listing entries", } } @@ -57,7 +56,7 @@ impl ListError { * Get the error type of this ListError */ pub fn err_type(&self) -> ListErrorKind { - self.err_type.clone() + self.err_type } } @@ -65,7 +64,7 @@ impl ListError { impl Display for ListError { fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> { - try!(write!(fmt, "[{}]", counter_error_type_as_str(&self.err_type.clone()))); + try!(write!(fmt, "[{}]", counter_error_type_as_str(&self.err_type))); Ok(()) } @@ -74,7 +73,7 @@ impl Display for ListError { impl Error for ListError { fn description(&self) -> &str { - counter_error_type_as_str(&self.err_type.clone()) + counter_error_type_as_str(&self.err_type) } fn cause(&self) -> Option<&Error> { diff --git a/libimagentrytag/src/error.rs b/libimagentrytag/src/error.rs index 63d149e4..19d4a92e 100644 --- a/libimagentrytag/src/error.rs +++ b/libimagentrytag/src/error.rs @@ -1,6 +1,5 @@ use std::error::Error; use std::fmt::Error as FmtError; -use std::clone::Clone; use std::fmt::{Display, Formatter}; #[derive(Clone, Copy, Debug, PartialEq)] @@ -12,11 +11,11 @@ pub enum TagErrorKind { } fn tag_error_type_as_str(e: &TagErrorKind) -> &'static str { - match e { - &TagErrorKind::TagTypeError => "Entry Header Tag Type wrong", - &TagErrorKind::HeaderReadError => "Error while reading entry header", - &TagErrorKind::HeaderWriteError => "Error while writing entry header", - &TagErrorKind::NotATag => "String is not a tag", + match *e { + TagErrorKind::TagTypeError => "Entry Header Tag Type wrong", + TagErrorKind::HeaderReadError => "Error while reading entry header", + TagErrorKind::HeaderWriteError => "Error while writing entry header", + TagErrorKind::NotATag => "String is not a tag", } } @@ -49,7 +48,7 @@ impl TagError { impl Display for TagError { fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> { - try!(write!(fmt, "[{}]", tag_error_type_as_str(&self.kind.clone()))); + try!(write!(fmt, "[{}]", tag_error_type_as_str(&self.kind))); Ok(()) } @@ -58,7 +57,7 @@ impl Display for TagError { impl Error for TagError { fn description(&self) -> &str { - tag_error_type_as_str(&self.kind.clone()) + tag_error_type_as_str(&self.kind) } fn cause(&self) -> Option<&Error> { diff --git a/libimagentrytag/src/exec.rs b/libimagentrytag/src/exec.rs index e9603d87..8ea45142 100644 --- a/libimagentrytag/src/exec.rs +++ b/libimagentrytag/src/exec.rs @@ -7,22 +7,20 @@ use tagable::*; use ui::{get_add_tags, get_remove_tags}; pub fn exec_cli_for_entry(matches: &ArgMatches, entry: &mut FileLockEntry) -> Result<()> { - match get_add_tags(matches) { - Some(ts) => for t in ts { + if let Some(ts) = get_add_tags(matches) { + for t in ts { if let Err(e) = entry.add_tag(t) { return Err(e); } - }, - None => { }, + } } - match get_remove_tags(matches) { - Some(ts) => for t in ts { + if let Some(ts) = get_remove_tags(matches) { + for t in ts { if let Err(e) = entry.remove_tag(t) { return Err(e); } - }, - None => { }, + } } Ok(()) diff --git a/libimagentrytag/src/tag.rs b/libimagentrytag/src/tag.rs index cba2322e..ec72161c 100644 --- a/libimagentrytag/src/tag.rs +++ b/libimagentrytag/src/tag.rs @@ -1 +1,2 @@ pub type Tag = String; +pub type TagSlice<'a> = &'a str; diff --git a/libimagentrytag/src/tagable.rs b/libimagentrytag/src/tagable.rs index 4dbe4efb..6206a53e 100644 --- a/libimagentrytag/src/tagable.rs +++ b/libimagentrytag/src/tagable.rs @@ -7,7 +7,7 @@ use libimagstore::store::{Entry, EntryHeader, FileLockEntry}; use error::{TagError, TagErrorKind}; use result::Result; -use tag::Tag; +use tag::{Tag, TagSlice}; use util::is_tag; use toml::Value; @@ -15,13 +15,13 @@ use toml::Value; pub trait Tagable { fn get_tags(&self) -> Result>; - fn set_tags(&mut self, ts: Vec) -> Result<()>; + fn set_tags(&mut self, ts: &[Tag]) -> Result<()>; fn add_tag(&mut self, t: Tag) -> Result<()>; fn remove_tag(&mut self, t: Tag) -> Result<()>; - fn has_tag(&self, t: &Tag) -> Result; - fn has_tags(&self, ts: &Vec) -> Result; + fn has_tag(&self, t: TagSlice) -> Result; + fn has_tags(&self, ts: &[Tag]) -> Result; } @@ -37,11 +37,11 @@ impl Tagable for EntryHeader { match tags { Some(Value::Array(tags)) => { - if !tags.iter().all(|t| match t { &Value::String(_) => true, _ => false }) { + if !tags.iter().all(|t| match *t { Value::String(_) => true, _ => false }) { return Err(TagError::new(TagErrorKind::TagTypeError, None)); } - if tags.iter().any(|t| match t { - &Value::String(ref s) => !is_tag(&s), + if tags.iter().any(|t| match *t { + Value::String(ref s) => !is_tag(s), _ => unreachable!()}) { return Err(TagError::new(TagErrorKind::NotATag, None)); @@ -62,7 +62,7 @@ impl Tagable for EntryHeader { } } - fn set_tags(&mut self, ts: Vec) -> Result<()> { + fn set_tags(&mut self, ts: &[Tag]) -> Result<()> { if ts.iter().any(|tag| !is_tag(tag)) { debug!("Not a tag: '{}'", ts.iter().filter(|t| !is_tag(t)).next().unwrap()); return Err(TagError::new(TagErrorKind::NotATag, None)); @@ -83,7 +83,7 @@ impl Tagable for EntryHeader { self.get_tags() .map(|mut tags| { tags.push(t); - self.set_tags(tags.into_iter().unique().collect()) + self.set_tags(&tags.into_iter().unique().collect::>()[..]) }) .map(|_| ()) } @@ -97,12 +97,12 @@ impl Tagable for EntryHeader { self.get_tags() .map(|mut tags| { tags.retain(|tag| tag.clone() != t); - self.set_tags(tags) + self.set_tags(&tags[..]) }) .map(|_| ()) } - fn has_tag(&self, t: &Tag) -> Result { + fn has_tag(&self, t: TagSlice) -> Result { let tags = self.read("imag.tags"); if tags.is_err() { let kind = TagErrorKind::HeaderReadError; @@ -110,21 +110,21 @@ impl Tagable for EntryHeader { } let tags = tags.unwrap(); - if !tags.iter().all(|t| match t { &Value::String(_) => true, _ => false }) { + if !tags.iter().all(|t| match *t { Value::String(_) => true, _ => false }) { return Err(TagError::new(TagErrorKind::TagTypeError, None)); } Ok(tags .iter() .any(|tag| { - match tag { - &Value::String(ref s) => { s == t }, + match *tag { + Value::String(ref s) => { s == t }, _ => unreachable!() } })) } - fn has_tags(&self, tags: &Vec) -> Result { + fn has_tags(&self, tags: &[Tag]) -> Result { let mut result = true; for tag in tags { let check = self.has_tag(tag); @@ -147,7 +147,7 @@ impl Tagable for Entry { self.get_header().get_tags() } - fn set_tags(&mut self, ts: Vec) -> Result<()> { + fn set_tags(&mut self, ts: &[Tag]) -> Result<()> { self.get_header_mut().set_tags(ts) } @@ -159,11 +159,11 @@ impl Tagable for Entry { self.get_header_mut().remove_tag(t) } - fn has_tag(&self, t: &Tag) -> Result { + fn has_tag(&self, t: TagSlice) -> Result { self.get_header().has_tag(t) } - fn has_tags(&self, ts: &Vec) -> Result { + fn has_tags(&self, ts: &[Tag]) -> Result { self.get_header().has_tags(ts) } @@ -175,7 +175,7 @@ impl<'a> Tagable for FileLockEntry<'a> { self.deref().get_tags() } - fn set_tags(&mut self, ts: Vec) -> Result<()> { + fn set_tags(&mut self, ts: &[Tag]) -> Result<()> { self.deref_mut().set_tags(ts) } @@ -187,11 +187,11 @@ impl<'a> Tagable for FileLockEntry<'a> { self.deref_mut().remove_tag(t) } - fn has_tag(&self, t: &Tag) -> Result { + fn has_tag(&self, t: TagSlice) -> Result { self.deref().has_tag(t) } - fn has_tags(&self, ts: &Vec) -> Result { + fn has_tags(&self, ts: &[Tag]) -> Result { self.deref().has_tags(ts) } diff --git a/libimagentrytag/src/ui.rs b/libimagentrytag/src/ui.rs index 9f9cf2c8..ecef19d6 100644 --- a/libimagentrytag/src/ui.rs +++ b/libimagentrytag/src/ui.rs @@ -2,7 +2,7 @@ use clap::{Arg, ArgMatches, App, SubCommand}; use tag::Tag; -/// Generates a clap::SubCommand to be integrated in the commandline-ui builder for building a +/// Generates a `clap::SubCommand` to be integrated in the commandline-ui builder for building a /// "tags --add foo --remove bar" subcommand to do tagging action. pub fn tag_subcommand<'a, 'b>() -> App<'a, 'b> { SubCommand::with_name(tag_subcommand_name()) @@ -41,7 +41,7 @@ pub fn tag_subcommand_names() -> Vec<&'static str> { vec![tag_subcommand_add_arg_name(), tag_subcommand_remove_arg_name()] } -/// Generates a clap::Arg which can be integrated into the commandline-ui builder for building a +/// Generates a `clap::Arg` which can be integrated into the commandline-ui builder for building a /// "-t" or "--tags" argument which takes values for tagging actions (add, remove) pub fn tag_argument<'a, 'b>() -> Arg<'a, 'b> { Arg::with_name(tag_argument_name()) @@ -79,7 +79,7 @@ fn extract_tags(matches: &ArgMatches, specifier: &str, specchar: char) -> Option .map(|argmatches| { argmatches .map(String::from) - .filter(|s| s.chars().next() == Some(specchar)) + .filter(|s| s.starts_with(specchar)) .map(|s| { String::from(s.split_at(1).1) }) diff --git a/libimagentrytag/src/util.rs b/libimagentrytag/src/util.rs index caa32539..42765193 100644 --- a/libimagentrytag/src/util.rs +++ b/libimagentrytag/src/util.rs @@ -1,5 +1,5 @@ use regex::Regex; -pub fn is_tag(s: &String) -> bool { +pub fn is_tag(s: &str) -> bool { Regex::new("^[a-zA-Z]([a-zA-Z0-9_-]*)$").unwrap().captures(&s[..]).is_some() } diff --git a/libimagentryview/src/error.rs b/libimagentryview/src/error.rs index 108529cc..4bc8af54 100644 --- a/libimagentryview/src/error.rs +++ b/libimagentryview/src/error.rs @@ -1,6 +1,5 @@ use std::error::Error; use std::fmt::Error as FmtError; -use std::clone::Clone; use std::fmt::{Display, Formatter}; /** @@ -52,7 +51,7 @@ impl ViewError { * Get the error type of this ViewError */ pub fn err_type(&self) -> ViewErrorKind { - self.err_type.clone() + self.err_type } } @@ -60,7 +59,7 @@ impl ViewError { impl Display for ViewError { fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> { - try!(write!(fmt, "[{}]", counter_error_type_as_str(&self.err_type.clone()))); + try!(write!(fmt, "[{}]", counter_error_type_as_str(&self.err_type))); Ok(()) } @@ -69,7 +68,7 @@ impl Display for ViewError { impl Error for ViewError { fn description(&self) -> &str { - counter_error_type_as_str(&self.err_type.clone()) + counter_error_type_as_str(&self.err_type) } fn cause(&self) -> Option<&Error> { diff --git a/libimaginteraction/src/ask.rs b/libimaginteraction/src/ask.rs index 88d44b6a..7a2c905d 100644 --- a/libimaginteraction/src/ask.rs +++ b/libimaginteraction/src/ask.rs @@ -40,13 +40,10 @@ fn ask_bool_(s: &str, default: Option, input: &mut R) -> bool return true } else if R_NO.is_match(&s[..]) { return false - } else { - if default.is_some() { - return default.unwrap(); - } - - // else again... + } else if default.is_some() { + return default.unwrap(); } + // else again... } } @@ -123,26 +120,24 @@ pub fn ask_string_(s: &str, let _ = input.read_line(&mut s); if permit_multiline { - if permit_multiline && eof.map(|e| e == s).unwrap_or(false) { + if permit_multiline && eof.map_or(false, |e| e == s) { return v.join("\n"); } - if permit_empty || v.len() != 0 { + if permit_empty || !v.is_empty() { v.push(s); } print!("{}", prompt); - } else { - if s.len() == 0 && permit_empty { - return s; - } else if s.len() == 0 && !permit_empty { - if default.is_some() { - return default.unwrap(); - } else { - continue; - } + } else if s.is_empty() && permit_empty { + return s; + } else if s.is_empty() && !permit_empty { + if default.is_some() { + return default.unwrap(); } else { - return s; + continue; } + } else { + return s; } } } diff --git a/libimaginteraction/src/error.rs b/libimaginteraction/src/error.rs index a31e3a53..ed7d974e 100644 --- a/libimaginteraction/src/error.rs +++ b/libimaginteraction/src/error.rs @@ -1,6 +1,5 @@ use std::error::Error; use std::fmt::Error as FmtError; -use std::clone::Clone; use std::fmt::{Display, Formatter}; /** @@ -12,8 +11,8 @@ pub enum InteractionErrorKind { } fn interaction_error_type_as_str(e: &InteractionErrorKind) -> &'static str { - match e { - &InteractionErrorKind::Unknown => "Unknown Error", + match *e { + InteractionErrorKind::Unknown => "Unknown Error", } } @@ -50,7 +49,7 @@ impl InteractionError { * Get the error type of this InteractionError */ pub fn err_type(&self) -> InteractionErrorKind { - self.err_type.clone() + self.err_type } } @@ -58,7 +57,7 @@ impl InteractionError { impl Display for InteractionError { fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> { - try!(write!(fmt, "[{}]", interaction_error_type_as_str(&self.err_type.clone()))); + try!(write!(fmt, "[{}]", interaction_error_type_as_str(&self.err_type))); Ok(()) } @@ -67,7 +66,7 @@ impl Display for InteractionError { impl Error for InteractionError { fn description(&self) -> &str { - interaction_error_type_as_str(&self.err_type.clone()) + interaction_error_type_as_str(&self.err_type) } fn cause(&self) -> Option<&Error> { diff --git a/libimagnotes/src/error.rs b/libimagnotes/src/error.rs index b55659f6..ec1f5535 100644 --- a/libimagnotes/src/error.rs +++ b/libimagnotes/src/error.rs @@ -1,6 +1,5 @@ use std::error::Error; use std::fmt::Error as FmtError; -use std::clone::Clone; use std::fmt::{Display, Formatter}; /** @@ -16,11 +15,11 @@ pub enum NoteErrorKind { } fn note_error_type_as_str(e: &NoteErrorKind) -> &'static str { - match e { - &NoteErrorKind::StoreWriteError => "Error writing store", - &NoteErrorKind::StoreReadError => "Error reading store", - &NoteErrorKind::HeaderTypeError => "Header type error", - &NoteErrorKind::NoteToEntryConversion => "Error converting Note instance to Entry instance", + match *e { + NoteErrorKind::StoreWriteError => "Error writing store", + NoteErrorKind::StoreReadError => "Error reading store", + NoteErrorKind::HeaderTypeError => "Header type error", + NoteErrorKind::NoteToEntryConversion => "Error converting Note instance to Entry instance", } } @@ -58,7 +57,7 @@ impl NoteError { * Get the error type of this NoteError */ pub fn err_type(&self) -> NoteErrorKind { - self.err_type.clone() + self.err_type } } @@ -66,7 +65,7 @@ impl NoteError { impl Display for NoteError { fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> { - try!(write!(fmt, "[{}]", note_error_type_as_str(&self.err_type.clone()))); + try!(write!(fmt, "[{}]", note_error_type_as_str(&self.err_type))); Ok(()) } @@ -75,7 +74,7 @@ impl Display for NoteError { impl Error for NoteError { fn description(&self) -> &str { - note_error_type_as_str(&self.err_type.clone()) + note_error_type_as_str(&self.err_type) } fn cause(&self) -> Option<&Error> { diff --git a/libimagnotes/src/note.rs b/libimagnotes/src/note.rs index 2728b768..8847b888 100644 --- a/libimagnotes/src/note.rs +++ b/libimagnotes/src/note.rs @@ -10,7 +10,7 @@ use libimagstore::storeid::StoreId; use libimagstore::storeid::StoreIdIterator; use libimagstore::store::FileLockEntry; use libimagstore::store::Store; -use libimagentrytag::tag::Tag; +use libimagentrytag::tag::{Tag, TagSlice}; use libimagentrytag::tagable::Tagable; use libimagentrytag::result::Result as TagResult; @@ -124,7 +124,7 @@ impl<'a> Tagable for Note<'a> { self.entry.get_tags() } - fn set_tags(&mut self, ts: Vec) -> TagResult<()> { + fn set_tags(&mut self, ts: &[Tag]) -> TagResult<()> { self.entry.set_tags(ts) } @@ -136,23 +136,23 @@ impl<'a> Tagable for Note<'a> { self.entry.remove_tag(t) } - fn has_tag(&self, t: &Tag) -> TagResult { + fn has_tag(&self, t: TagSlice) -> TagResult { self.entry.has_tag(t) } - fn has_tags(&self, ts: &Vec) -> TagResult { + fn has_tags(&self, ts: &[Tag]) -> TagResult { self.entry.has_tags(ts) } } trait FromStoreId { - fn from_storeid<'a>(&'a Store, StoreId) -> Result>; + fn from_storeid(&Store, StoreId) -> Result; } impl<'a> FromStoreId for Note<'a> { - fn from_storeid<'b>(store: &'b Store, id: StoreId) -> Result> { + fn from_storeid(store: &Store, id: StoreId) -> Result { debug!("Loading note from storeid: '{:?}'", id); match store.retrieve(id) { Err(e) => Err(NE::new(NEK::StoreReadError, Some(Box::new(e)))), diff --git a/libimagrt/src/configuration.rs b/libimagrt/src/configuration.rs index eb199a53..15b94e09 100644 --- a/libimagrt/src/configuration.rs +++ b/libimagrt/src/configuration.rs @@ -12,17 +12,13 @@ pub mod error { use std::fmt::{Display, Formatter}; use std::fmt::Error as FmtError; - /** - * The kind of an error - */ + /// The kind of an error #[derive(Clone, Debug, PartialEq)] pub enum ConfigErrorKind { NoConfigFileFound, } - /** - * Configuration error type - */ + /// Configuration error type #[derive(Debug)] pub struct ConfigError { kind: ConfigErrorKind, @@ -31,9 +27,7 @@ pub mod error { impl ConfigError { - /** - * Instantiate a new ConfigError, optionally with cause - */ + /// Instantiate a new `ConfigError`, optionally with cause pub fn new(kind: ConfigErrorKind, cause: Option>) -> ConfigError { ConfigError { kind: kind, @@ -41,16 +35,12 @@ pub mod error { } } - /** - * get the Kind of the Error - */ + ///get the Kind of the Error pub fn err_type(&self) -> ConfigErrorKind { self.kind.clone() } - /** - * Get the string, the ConfigError can be described with - */ + /// Get the string, the `ConfigError` can be described with pub fn as_str(e: &ConfigError) -> &'static str { match e.err_type() { ConfigErrorKind::NoConfigFileFound => "No config file found", @@ -86,51 +76,39 @@ use self::error::{ConfigError, ConfigErrorKind}; /** - * Result type of this module. Either T or ConfigError + * Result type of this module. Either `T` or `ConfigError` */ pub type Result = RResult; -/** - * Configuration object - * - * Holds all config variables which are globally available plus the configuration object from the - * config parser, which can be accessed. - */ +/// `Configuration` object +/// +/// Holds all config variables which are globally available plus the configuration object from the +/// config parser, which can be accessed. #[derive(Debug)] pub struct Configuration { - /** - * The plain configuration object for direct access if necessary - */ + /// The plain configuration object for direct access if necessary config: Value, - /** - * The verbosity the program should run with - */ + /// The verbosity the program should run with verbosity: bool, - /** - * The editor which should be used - */ + /// The editor which should be used editor: Option, - /** - * The options the editor should get when opening some file - */ + ///The options the editor should get when opening some file editor_opts: String, } impl Configuration { - /** - * Get a new configuration object. - * - * The passed runtimepath is used for searching the configuration file, whereas several file - * names are tested. If that does not work, the home directory and the XDG basedir are tested - * with all variants. - * - * If that doesn't work either, an error is returned. - */ + /// Get a new configuration object. + /// + /// The passed runtimepath is used for searching the configuration file, whereas several file + /// names are tested. If that does not work, the home directory and the XDG basedir are tested + /// with all variants. + /// + /// If that doesn't work either, an error is returned. pub fn new(rtp: &PathBuf) -> Result { fetch_config(&rtp).map(|cfg| { let verbosity = get_verbosity(&cfg); @@ -161,8 +139,8 @@ impl Configuration { } pub fn store_config(&self) -> Option<&Value> { - match &self.config { - &Value::Table(ref tabl) => tabl.get("store"), + match self.config { + Value::Table(ref tabl) => tabl.get("store"), _ => None, } } @@ -179,27 +157,26 @@ impl Deref for Configuration { } fn get_verbosity(v: &Value) -> bool { - match v { - &Value::Table(ref t) => t.get("verbose") - .map(|v| match v { &Value::Boolean(b) => b, _ => false, }) - .unwrap_or(false), + match *v { + Value::Table(ref t) => t.get("verbose") + .map_or(false, |v| match *v { Value::Boolean(b) => b, _ => false, }), _ => false, } } fn get_editor(v: &Value) -> Option { - match v { - &Value::Table(ref t) => t.get("editor") - .and_then(|v| match v { &Value::String(ref s) => Some(s.clone()), _ => None, }), + match *v { + Value::Table(ref t) => t.get("editor") + .and_then(|v| match *v { Value::String(ref s) => Some(s.clone()), _ => None, }), _ => None, } } fn get_editor_opts(v: &Value) -> String { - match v { - &Value::Table(ref t) => t.get("editor-opts") - .and_then(|v| match v { &Value::String(ref s) => Some(s.clone()), _ => None, }) - .unwrap_or(String::new()), + match *v { + Value::Table(ref t) => t.get("editor-opts") + .and_then(|v| match *v { Value::String(ref s) => Some(s.clone()), _ => None, }) + .unwrap_or_default(), _ => String::new(), } } @@ -224,7 +201,7 @@ fn fetch_config(rtp: &PathBuf) -> Result { let variants = vec!["config", "config.toml", "imagrc", "imagrc.toml"]; let modifier = |base: &PathBuf, v: &'static str| { let mut base = base.clone(); - base.push(format!("{}", v)); + base.push(String::from(v)); base }; @@ -268,6 +245,6 @@ fn fetch_config(rtp: &PathBuf) -> Result { .filter(|loaded| loaded.is_some()) .nth(0) .map(|inner| Value::Table(inner.unwrap())) - .ok_or(ConfigError::new(ConfigErrorKind::NoConfigFileFound, None)) + .ok_or_else(|| ConfigError::new(ConfigErrorKind::NoConfigFileFound, None)) } diff --git a/libimagrt/src/error.rs b/libimagrt/src/error.rs index 5ad5ea3d..ca343ede 100644 --- a/libimagrt/src/error.rs +++ b/libimagrt/src/error.rs @@ -31,10 +31,10 @@ impl RuntimeError { } fn runtime_error_kind_as_str(e: &RuntimeErrorKind) -> &'static str { - match e { - &RuntimeErrorKind::Instantiate => "Could not instantiate", - &RuntimeErrorKind::IOError => "IO Error", - &RuntimeErrorKind::ProcessExitFailure => "Process exited with failure", + match *e { + RuntimeErrorKind::Instantiate => "Could not instantiate", + RuntimeErrorKind::IOError => "IO Error", + RuntimeErrorKind::ProcessExitFailure => "Process exited with failure", } } diff --git a/libimagrt/src/runtime.rs b/libimagrt/src/runtime.rs index 7319958f..c67422cc 100644 --- a/libimagrt/src/runtime.rs +++ b/libimagrt/src/runtime.rs @@ -55,22 +55,20 @@ impl<'a> Runtime<'a> { Runtime::init_logger(is_debugging, is_verbose); let rtp : PathBuf = matches.value_of("runtimepath") - .map(PathBuf::from) - .unwrap_or_else(|| { + .map_or_else(|| { env::var("HOME") .map(PathBuf::from) .map(|mut p| { p.push(".imag"); p}) .unwrap_or_else(|_| { panic!("You seem to be $HOME-less. Please get a $HOME before using this software. We are sorry for you and hope you have some accommodation anyways."); }) - }); + }, PathBuf::from); let storepath = matches.value_of("storepath") - .map(PathBuf::from) - .unwrap_or({ + .map_or_else(|| { let mut spath = rtp.clone(); spath.push("store"); spath - }); + }, PathBuf::from); let cfg = Configuration::new(&rtp); let cfg = if cfg.is_err() { @@ -87,9 +85,9 @@ impl<'a> Runtime<'a> { }; let store_config = { - match &cfg { - &Some(ref c) => c.store_config().map(|c| c.clone()), - &None => None, + match cfg { + Some(ref c) => c.store_config().cloned(), + None => None, } }; @@ -268,8 +266,8 @@ impl<'a> Runtime<'a> { .value_of("editor") .map(String::from) .or({ - match &self.configuration { - &Some(ref c) => c.editor().map(|s| s.clone()), + match self.configuration { + Some(ref c) => c.editor().cloned(), _ => None, } }) diff --git a/libimagstore/src/configuration.rs b/libimagstore/src/configuration.rs index 20e18362..6004a3d8 100644 --- a/libimagstore/src/configuration.rs +++ b/libimagstore/src/configuration.rs @@ -51,10 +51,13 @@ pub fn config_is_valid(config: &Option) -> bool { fn has_key_with_string_ary(v: &BTreeMap, key: &str) -> bool { v.get(key) - .map(|t| match t { - &Value::Array(ref a) => a.iter().all(|elem| { - match elem { - &Value::String(_) => true, + .map_or_else(|| { + write!(stderr(), "Required key '{}' is not in store config", key).ok(); + false + }, |t| match *t { + Value::Array(ref a) => a.iter().all(|elem| { + match *elem { + Value::String(_) => true, _ => false, } }), @@ -63,9 +66,6 @@ pub fn config_is_valid(config: &Option) -> bool { .ok(); false } - }).unwrap_or_else(|| { - write!(stderr(), "Required key '{}' is not in store config", key).ok(); - false }) } @@ -84,18 +84,21 @@ pub fn config_is_valid(config: &Option) -> bool { where F: Fn(&Value) -> bool { store_config.get(section) // The store config has the section `section` - .map(|section_table| { - match section_table { // which is - &Value::Table(ref section_table) => // a table + .map_or_else(|| { + write!(stderr(), "Store config expects section '{}' to be present, but isn't.", + section).ok(); + false + }, |section_table| { + match *section_table { // which is + Value::Table(ref section_table) => // a table section_table .iter() // which has values, .all(|(inner_key, cfg)| { // and all of these values - match cfg { - &Value::Table(ref hook_config) => { // are tables + match *cfg { + Value::Table(ref hook_config) => { // are tables hook_config.get(key) // with a key // fullfilling this constraint - .map(|hook_aspect| f(&hook_aspect)) - .unwrap_or(false) + .map_or(false, |hook_aspect| f(&hook_aspect)) }, _ => { write!(stderr(), "Store config expects '{}' to be in '{}.{}', but isn't.", @@ -111,16 +114,10 @@ pub fn config_is_valid(config: &Option) -> bool { } } }) - .unwrap_or_else(|| { - write!(stderr(), "Store config expects section '{}' to be present, but isn't.", - section).ok(); - false - }) } - match config { - &Some(Value::Table(ref t)) => { - has_key_with_string_ary(t, "pre-create-hook-aspects") && + match *config { + Some(Value::Table(ref t)) => { has_key_with_string_ary(t, "pre-create-hook-aspects") && has_key_with_string_ary(t, "post-create-hook-aspects") && has_key_with_string_ary(t, "pre-retrieve-hook-aspects") && has_key_with_string_ary(t, "post-retrieve-hook-aspects") && @@ -132,15 +129,13 @@ pub fn config_is_valid(config: &Option) -> bool { // The section "hooks" has maps which have a key "aspect" which has a value of type // String check_all_inner_maps_have_key_with(t, "hooks", "aspect", |asp| { - let res = match asp { &Value::String(_) => true, _ => false }; - res + match *asp { Value::String(_) => true, _ => false } }) && // The section "aspects" has maps which have a key "parllel" which has a value of type // Boolean check_all_inner_maps_have_key_with(t, "aspects", "parallel", |asp| { - let res = match asp { &Value::Boolean(_) => true, _ => false, }; - res + match *asp { Value::Boolean(_) => true, _ => false, } }) } _ => { @@ -199,16 +194,15 @@ impl AspectConfig { } fn is_parallel(init: &Value) -> bool { - match init { - &Value::Table(ref t) => + match *init { + Value::Table(ref t) => t.get("parallel") - .map(|value| { - match value { - &Value::Boolean(b) => b, + .map_or(false, |value| { + match *value { + Value::Boolean(b) => b, _ => false, } - }) - .unwrap_or(false), + }), _ => false, } } @@ -219,8 +213,8 @@ impl AspectConfig { /// /// Returns `None` if one of the keys in the chain is not available pub fn get_for(v: &Option, a_name: String) -> Option { - match v { - &Some(Value::Table(ref tabl)) => tabl.get(&a_name[..]) + match *v { + Some(Value::Table(ref tabl)) => tabl.get(&a_name[..]) .map(|asp| AspectConfig::new(asp.clone())), _ => None, } @@ -231,13 +225,13 @@ impl AspectConfig { fn get_aspect_names_for_aspect_position(config_name: &'static str, value: &Option) -> Vec { let mut v = vec![]; - match value { - &Some(Value::Table(ref t)) => { + match *value { + Some(Value::Table(ref t)) => { match t.get(config_name) { Some(&Value::Array(ref a)) => { for elem in a { - match elem { - &Value::String(ref s) => v.push(s.clone()), + match *elem { + Value::String(ref s) => v.push(s.clone()), _ => warn!("Non-String in configuration, inside '{}'", config_name), } } @@ -245,7 +239,7 @@ fn get_aspect_names_for_aspect_position(config_name: &'static str, value: &Optio _ => warn!("'{}' configuration key should contain Array, does not", config_name), }; }, - &None => warn!("No store configuration"), + None => warn!("No store configuration"), _ => warn!("Configuration is not a table"), } v diff --git a/libimagstore/src/error.rs b/libimagstore/src/error.rs index 4fea66f0..1976622d 100644 --- a/libimagstore/src/error.rs +++ b/libimagstore/src/error.rs @@ -1,6 +1,5 @@ use std::error::Error; use std::fmt::Error as FmtError; -use std::clone::Clone; use std::fmt::{Debug, Display, Formatter}; use std::fmt; use std::convert::From; @@ -41,35 +40,35 @@ pub enum StoreErrorKind { } fn store_error_type_as_str(e: &StoreErrorKind) -> &'static str { - match e { - &StoreErrorKind::ConfigurationError => "Store Configuration Error", - &StoreErrorKind::FileError => "File Error", - &StoreErrorKind::IdLocked => "ID locked", - &StoreErrorKind::IdNotFound => "ID not found", - &StoreErrorKind::OutOfMemory => "Out of Memory", - &StoreErrorKind::FileNotFound => "File corresponding to ID not found", - &StoreErrorKind::FileNotCreated => "File corresponding to ID could not be created", - &StoreErrorKind::IoError => "File Error", - &StoreErrorKind::StorePathExists => "Store path exists", - &StoreErrorKind::StorePathCreate => "Store path create", - &StoreErrorKind::LockError => "Error locking datastructure", - &StoreErrorKind::LockPoisoned + match *e { + StoreErrorKind::ConfigurationError => "Store Configuration Error", + StoreErrorKind::FileError | + StoreErrorKind::IoError => "File Error", + StoreErrorKind::IdLocked => "ID locked", + StoreErrorKind::IdNotFound => "ID not found", + StoreErrorKind::OutOfMemory => "Out of Memory", + StoreErrorKind::FileNotFound => "File corresponding to ID not found", + StoreErrorKind::FileNotCreated => "File corresponding to ID could not be created", + StoreErrorKind::StorePathExists | + StoreErrorKind::StorePathCreate => "Store path create", + StoreErrorKind::LockError => "Error locking datastructure", + StoreErrorKind::LockPoisoned => "The internal Store Lock has been poisoned", - &StoreErrorKind::EntryAlreadyBorrowed => "Entry is already borrowed", - &StoreErrorKind::EntryAlreadyExists => "Entry already exists", - &StoreErrorKind::MalformedEntry => "Entry has invalid formatting, missing header", - &StoreErrorKind::HeaderPathSyntaxError => "Syntax error in accessor string", - &StoreErrorKind::HeaderPathTypeFailure => "Header has wrong type for path", - &StoreErrorKind::HeaderKeyNotFound => "Header Key not found", - &StoreErrorKind::HeaderTypeFailure => "Header type is wrong", - &StoreErrorKind::HookRegisterError => "Hook register error", - &StoreErrorKind::AspectNameNotFoundError => "Aspect name not found", - &StoreErrorKind::HookExecutionError => "Hook execution error", - &StoreErrorKind::PreHookExecuteError => "Pre-Hook execution error", - &StoreErrorKind::PostHookExecuteError => "Post-Hook execution error", - &StoreErrorKind::StorePathLacksVersion => "The supplied store path has no version part", - &StoreErrorKind::GlobError => "glob() error", - &StoreErrorKind::EncodingError => "Encoding error", + StoreErrorKind::EntryAlreadyBorrowed => "Entry is already borrowed", + StoreErrorKind::EntryAlreadyExists => "Entry already exists", + StoreErrorKind::MalformedEntry => "Entry has invalid formatting, missing header", + StoreErrorKind::HeaderPathSyntaxError => "Syntax error in accessor string", + StoreErrorKind::HeaderPathTypeFailure => "Header has wrong type for path", + StoreErrorKind::HeaderKeyNotFound => "Header Key not found", + StoreErrorKind::HeaderTypeFailure => "Header type is wrong", + StoreErrorKind::HookRegisterError => "Hook register error", + StoreErrorKind::AspectNameNotFoundError => "Aspect name not found", + StoreErrorKind::HookExecutionError => "Hook execution error", + StoreErrorKind::PreHookExecuteError => "Pre-Hook execution error", + StoreErrorKind::PostHookExecuteError => "Post-Hook execution error", + StoreErrorKind::StorePathLacksVersion => "The supplied store path has no version part", + StoreErrorKind::GlobError => "glob() error", + StoreErrorKind::EncodingError => "Encoding error", } } @@ -109,7 +108,7 @@ impl StoreError { * Get the error type of this StoreError */ pub fn err_type(&self) -> StoreErrorKind { - self.err_type.clone() + self.err_type } } @@ -117,7 +116,7 @@ impl StoreError { impl Display for StoreError { fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> { - try!(write!(fmt, "[{}]", store_error_type_as_str(&self.err_type.clone()))); + try!(write!(fmt, "[{}]", store_error_type_as_str(&self.err_type))); Ok(()) } @@ -126,7 +125,7 @@ impl Display for StoreError { impl Error for StoreError { fn description(&self) -> &str { - store_error_type_as_str(&self.err_type.clone()) + store_error_type_as_str(&self.err_type) } fn cause(&self) -> Option<&Error> { diff --git a/libimagstore/src/hook/aspect.rs b/libimagstore/src/hook/aspect.rs index 8a9e81c8..f3d914e4 100644 --- a/libimagstore/src/hook/aspect.rs +++ b/libimagstore/src/hook/aspect.rs @@ -41,7 +41,7 @@ impl StoreIdAccessor for Aspect { use crossbeam; let accessors : Vec = self.hooks.iter().map(|h| h.accessor()).collect(); - if !accessors.iter().all(|a| match a { &HDA::StoreIdAccess(_) => true, _ => false }) { + if !accessors.iter().all(|a| match *a { HDA::StoreIdAccess(_) => true, _ => false }) { return Err(HE::new(HEK::AccessTypeViolation, None)); } @@ -50,8 +50,8 @@ impl StoreIdAccessor for Aspect { .map(|accessor| { crossbeam::scope(|scope| { scope.spawn(|| { - match accessor { - &HDA::StoreIdAccess(accessor) => accessor.access(id), + match *accessor { + HDA::StoreIdAccess(accessor) => accessor.access(id), _ => unreachable!(), } .map_err(|_| ()) // TODO: We're losing the error cause here @@ -76,9 +76,9 @@ impl MutableHookDataAccessor for Aspect { let accessors : Vec = self.hooks.iter().map(|h| h.accessor()).collect(); fn is_file_accessor(a: &HDA) -> bool { - match a { - &HDA::MutableAccess(_) => true, - &HDA::NonMutableAccess(_) => true, + match *a { + HDA::MutableAccess(_) | + HDA::NonMutableAccess(_) => true, _ => false, } } @@ -108,7 +108,7 @@ impl NonMutableHookDataAccessor for Aspect { use crossbeam; let accessors : Vec = self.hooks.iter().map(|h| h.accessor()).collect(); - if !accessors.iter().all(|a| match a { &HDA::NonMutableAccess(_) => true, _ => false }) { + if !accessors.iter().all(|a| match *a { HDA::NonMutableAccess(_) => true, _ => false }) { return Err(HE::new(HEK::AccessTypeViolation, None)); } @@ -117,8 +117,8 @@ impl NonMutableHookDataAccessor for Aspect { .map(|accessor| { crossbeam::scope(|scope| { scope.spawn(|| { - match accessor { - &HDA::NonMutableAccess(accessor) => accessor.access(fle), + match *accessor { + HDA::NonMutableAccess(accessor) => accessor.access(fle), _ => unreachable!(), } .map_err(|_| ()) // TODO: We're losing the error cause here diff --git a/libimagstore/src/hook/error.rs b/libimagstore/src/hook/error.rs index a4769af3..b9abd4fe 100644 --- a/libimagstore/src/hook/error.rs +++ b/libimagstore/src/hook/error.rs @@ -1,6 +1,5 @@ use std::error::Error; use std::fmt::Error as FmtError; -use std::clone::Clone; use std::fmt::{Display, Formatter}; use std::convert::Into; @@ -35,9 +34,9 @@ impl Into for (HookErrorKind, Box) { } fn hook_error_type_as_str(e: &HookErrorKind) -> &'static str { - match e { - &HookErrorKind::HookExecutionError => "Hook exec error", - &HookErrorKind::AccessTypeViolation => "Hook access type violation", + match *e { + HookErrorKind::HookExecutionError => "Hook exec error", + HookErrorKind::AccessTypeViolation => "Hook access type violation", } } @@ -77,7 +76,7 @@ impl HookError { * Get the error type of this HookError */ pub fn err_type(&self) -> HookErrorKind { - self.err_type.clone() + self.err_type } } @@ -85,7 +84,7 @@ impl HookError { impl Display for HookError { fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> { - try!(write!(fmt, "[{}]", hook_error_type_as_str(&self.err_type.clone()))); + try!(write!(fmt, "[{}]", hook_error_type_as_str(&self.err_type))); Ok(()) } @@ -94,7 +93,7 @@ impl Display for HookError { impl Error for HookError { fn description(&self) -> &str { - hook_error_type_as_str(&self.err_type.clone()) + hook_error_type_as_str(&self.err_type) } fn cause(&self) -> Option<&Error> { diff --git a/libimagstore/src/lazyfile.rs b/libimagstore/src/lazyfile.rs index 0b4fa031..ec3e8f45 100644 --- a/libimagstore/src/lazyfile.rs +++ b/libimagstore/src/lazyfile.rs @@ -4,11 +4,9 @@ use std::io::{Seek, SeekFrom}; use std::path::{Path, PathBuf}; use std::fs::{File, OpenOptions, create_dir_all}; -/** - * LazyFile type - * - * A lazy file is either absent, but a path to it is available, or it is present. - */ +/// `LazyFile` type +/// +/// A lazy file is either absent, but a path to it is available, or it is present. #[derive(Debug)] pub enum LazyFile { Absent(PathBuf), diff --git a/libimagstore/src/store.rs b/libimagstore/src/store.rs index a3f6955e..b93696eb 100644 --- a/libimagstore/src/store.rs +++ b/libimagstore/src/store.rs @@ -140,7 +140,7 @@ impl StoreEntry { entry } } else { - return Err(StoreError::new(StoreErrorKind::EntryAlreadyBorrowed, None)) + Err(StoreError::new(StoreErrorKind::EntryAlreadyBorrowed, None)) } } @@ -213,11 +213,9 @@ impl Store { return Err(StoreError::new(StoreErrorKind::StorePathCreate, Some(Box::new(c.unwrap_err())))); } - } else { - if location.is_file() { - debug!("Store path exists as file"); - return Err(StoreError::new(StoreErrorKind::StorePathExists, None)); - } + } else if location.is_file() { + debug!("Store path exists as file"); + return Err(StoreError::new(StoreErrorKind::StorePathExists, None)); } let pre_create_aspects = get_pre_create_aspect_names(&store_config) @@ -468,7 +466,7 @@ impl Store { pub fn register_hook(&mut self, position: HookPosition, - aspect_name: &String, + aspect_name: &str, mut h: Box) -> Result<()> { @@ -506,16 +504,16 @@ impl Store { } let annfe = StoreError::new(StoreErrorKind::AspectNameNotFoundError, None); - return Err(StoreError::new(StoreErrorKind::HookRegisterError, Some(Box::new(annfe)))); + Err(StoreError::new(StoreErrorKind::HookRegisterError, Some(Box::new(annfe)))) } fn get_config_for_hook(&self, name: &str) -> Option<&Value> { - match &self.configuration { - &Some(Value::Table(ref tabl)) => { + match self.configuration { + Some(Value::Table(ref tabl)) => { tabl.get("hooks") .map(|hook_section| { - match hook_section { - &Value::Table(ref tabl) => tabl.get(name), + match *hook_section { + Value::Table(ref tabl) => tabl.get(name), _ => None } }) @@ -635,17 +633,13 @@ impl<'a> Drop for FileLockEntry<'a> { } } -/** - * EntryContent type - */ +/// `EntryContent` type pub type EntryContent = String; -/** - * EntryHeader - * - * This is basically a wrapper around toml::Table which provides convenience to the user of the - * librray. - */ +/// `EntryHeader` +/// +/// This is basically a wrapper around `toml::Table` which provides convenience to the user of the +/// library. #[derive(Debug, Clone)] pub struct EntryHeader { header: Value, @@ -691,8 +685,8 @@ impl EntryHeader { } pub fn verify(&self) -> Result<()> { - match &self.header { - &Value::Table(ref t) => verify_header(&t), + match self.header { + Value::Table(ref t) => verify_header(&t), _ => Err(StoreError::new(StoreErrorKind::HeaderTypeFailure, None)), } } @@ -751,13 +745,13 @@ impl EntryHeader { return Ok(false); } - match destination { - &Token::Key(ref s) => { // if the destination shall be an map key - match value { + match *destination { + Token::Key(ref s) => { // if the destination shall be an map key + match *value { /* * Put it in there if we have a map */ - &mut Value::Table(ref mut t) => { + Value::Table(ref mut t) => { t.insert(s.clone(), v); } @@ -768,13 +762,13 @@ impl EntryHeader { } }, - &Token::Index(i) => { // if the destination shall be an array - match value { + Token::Index(i) => { // if the destination shall be an array + match *value { /* * Put it in there if we have an array */ - &mut Value::Array(ref mut a) => { + Value::Array(ref mut a) => { a.push(v); // push to the end of the array // if the index is inside the array, we swap-remove the element at this @@ -845,13 +839,13 @@ impl EntryHeader { let mut value = value.unwrap(); debug!("walked value = {:?}", value); - match destination { - &Token::Key(ref s) => { // if the destination shall be an map key->value - match value { + match *destination { + Token::Key(ref s) => { // if the destination shall be an map key->value + match *value { /* * Put it in there if we have a map */ - &mut Value::Table(ref mut t) => { + Value::Table(ref mut t) => { debug!("Matched Key->Table"); return Ok(t.insert(s.clone(), v)); } @@ -866,13 +860,13 @@ impl EntryHeader { } }, - &Token::Index(i) => { // if the destination shall be an array - match value { + Token::Index(i) => { // if the destination shall be an array + match *value { /* * Put it in there if we have an array */ - &mut Value::Array(ref mut a) => { + Value::Array(ref mut a) => { debug!("Matched Index->Array"); a.push(v); // push to the end of the array @@ -971,10 +965,10 @@ impl EntryHeader { let mut value = value.unwrap(); debug!("walked value = {:?}", value); - match destination { - &Token::Key(ref s) => { // if the destination shall be an map key->value - match value { - &mut Value::Table(ref mut t) => { + match *destination { + Token::Key(ref s) => { // if the destination shall be an map key->value + match *value { + Value::Table(ref mut t) => { debug!("Matched Key->Table, removing {:?}", s); return Ok(t.remove(s)); }, @@ -985,9 +979,9 @@ impl EntryHeader { } }, - &Token::Index(i) => { // if the destination shall be an array - match value { - &mut Value::Array(ref mut a) => { + Token::Index(i) => { // if the destination shall be an array + match *value { + Value::Array(ref mut a) => { // if the index is inside the array, we swap-remove the element at this // index if a.len() > i { @@ -1037,9 +1031,9 @@ impl EntryHeader { walk_iter(Ok(v), &mut tokens.into_iter()) } - fn extract_from_table<'a>(v: &'a mut Value, s: &String) -> Result<&'a mut Value> { - match v { - &mut Value::Table(ref mut t) => { + fn extract_from_table<'a>(v: &'a mut Value, s: &str) -> Result<&'a mut Value> { + match *v { + Value::Table(ref mut t) => { t.get_mut(&s[..]) .ok_or(StoreError::new(StoreErrorKind::HeaderKeyNotFound, None)) }, @@ -1048,8 +1042,8 @@ impl EntryHeader { } fn extract_from_array(v: &mut Value, i: usize) -> Result<&mut Value> { - match v { - &mut Value::Array(ref mut a) => { + match *v { + Value::Array(ref mut a) => { if a.len() < i { Err(StoreError::new(StoreErrorKind::HeaderKeyNotFound, None)) } else { @@ -1061,9 +1055,9 @@ impl EntryHeader { } fn extract<'a>(v: &'a mut Value, token: &Token) -> Result<&'a mut Value> { - match token { - &Token::Key(ref s) => EntryHeader::extract_from_table(v, s), - &Token::Index(i) => EntryHeader::extract_from_array(v, i), + match *token { + Token::Key(ref s) => EntryHeader::extract_from_table(v, s), + Token::Index(i) => EntryHeader::extract_from_array(v, i), } } @@ -1125,7 +1119,7 @@ fn verify_header_consistency(t: Table) -> EntryResult { fn has_only_tables(t: &Table) -> bool { debug!("Verifying that table has only tables"); - t.iter().all(|(_, x)| if let &Value::Table(_) = x { true } else { false }) + t.iter().all(|(_, x)| if let Value::Table(_) = *x { true } else { false }) } fn has_main_section(t: &Table) -> bool { @@ -1140,20 +1134,20 @@ fn has_main_section(t: &Table) -> bool { fn has_imag_version_in_main_section(t: &Table) -> bool { use semver::Version; - match t.get("imag").unwrap() { - &Value::Table(ref sec) => { + match *t.get("imag").unwrap() { + Value::Table(ref sec) => { sec.get("version") .and_then(|v| { - match v { - &Value::String(ref s) => { + match *v { + Value::String(ref s) => { Some(Version::parse(&s[..]).is_ok()) }, - _ => Some(false), + _ => Some(false), } }) .unwrap_or(false) } - _ => false, + _ => false, } } diff --git a/libimagstore/src/storeid.rs b/libimagstore/src/storeid.rs index 7481b6f8..d6631333 100644 --- a/libimagstore/src/storeid.rs +++ b/libimagstore/src/storeid.rs @@ -85,7 +85,7 @@ impl IntoStoreId for StoreId { pub fn build_entry_path(store: &Store, path_elem: &str) -> Result { debug!("Checking path element for version"); - if path_elem.split("~").last().map(|v| Version::parse(v).is_err()).unwrap_or(false) { + if path_elem.split('~').last().map_or(false, |v| Version::parse(v).is_err()) { debug!("Version cannot be parsed from {:?}", path_elem); debug!("Path does not contain version!"); return Err(StoreError::new(StoreErrorKind::StorePathLacksVersion, None)); @@ -95,8 +95,8 @@ pub fn build_entry_path(store: &Store, path_elem: &str) -> Result { debug!("Building path from {:?}", path_elem); let mut path = store.path().clone(); - if path_elem.chars().next() == Some('/') { - path.push(&path_elem[1..path_elem.len()]); + if path_elem.starts_with('/') { + path.push(&path_elem[1..]); } else { path.push(path_elem); } diff --git a/libimagstorestdhook/src/debug.rs b/libimagstorestdhook/src/debug.rs index 2a68529e..830c8e3d 100644 --- a/libimagstorestdhook/src/debug.rs +++ b/libimagstorestdhook/src/debug.rs @@ -43,14 +43,14 @@ impl HookDataAccessorProvider for DebugHook { use libimagstore::hook::accessor::HookDataAccessor as HDA; match self.position { - HP::PreCreate => HDA::StoreIdAccess(&self.accessor), - HP::PostCreate => HDA::MutableAccess(&self.accessor), - HP::PreRetrieve => HDA::StoreIdAccess(&self.accessor), - HP::PostRetrieve => HDA::MutableAccess(&self.accessor), - HP::PreUpdate => HDA::MutableAccess(&self.accessor), - HP::PostUpdate => HDA::MutableAccess(&self.accessor), - HP::PreDelete => HDA::StoreIdAccess(&self.accessor), + HP::PreCreate | + HP::PreRetrieve | + HP::PreDelete | HP::PostDelete => HDA::StoreIdAccess(&self.accessor), + HP::PostCreate | + HP::PostRetrieve | + HP::PreUpdate | + HP::PostUpdate => HDA::MutableAccess(&self.accessor), } } diff --git a/libimagstorestdhook/src/flock.rs b/libimagstorestdhook/src/flock.rs index 9ba0fe41..2386180a 100644 --- a/libimagstorestdhook/src/flock.rs +++ b/libimagstorestdhook/src/flock.rs @@ -51,9 +51,9 @@ pub enum Action { } fn action_to_str(a: &Action) -> &'static str { - match a { - &Action::Lock => "lock", - &Action::Unlock => "unlock", + match *a { + Action::Lock => "lock", + Action::Unlock => "unlock", } } diff --git a/libimagstorestdhook/src/linkverify.rs b/libimagstorestdhook/src/linkverify.rs index be2501c0..295a9de4 100644 --- a/libimagstorestdhook/src/linkverify.rs +++ b/libimagstorestdhook/src/linkverify.rs @@ -57,10 +57,8 @@ impl NonMutableHookDataAccessor for LinkedEntriesExistHook { path.push(link); if !path.exists() { warn!("File link does not exist: {:?} -> {:?}", fle.get_location(), path); - } else { - if !path.is_file() { - warn!("File link is not a file: {:?} -> {:?}", fle.get_location(), path); - } + } else if !path.is_file() { + warn!("File link is not a file: {:?} -> {:?}", fle.get_location(), path); } } }) diff --git a/libimagutil/src/trace.rs b/libimagutil/src/trace.rs index 5b22c84c..3a66bcb8 100644 --- a/libimagutil/src/trace.rs +++ b/libimagutil/src/trace.rs @@ -59,7 +59,7 @@ fn print_trace_maxdepth(idx: u64, e: &Error, max: u64) -> Option<&Error> { e.cause() } -/// Count errors in Error::cause() recursively +/// Count errors in `Error::cause()` recursively fn count_error_causes(e: &Error) -> u64 { 1 + if e.cause().is_some() { count_error_causes(e.cause().unwrap()) } else { 0 } } From 12472ab397801119fb679cac53f2ad671301e25a Mon Sep 17 00:00:00 2001 From: Andre Bogus Date: Tue, 3 May 2016 23:26:45 +0200 Subject: [PATCH 044/288] fixed type inference on FromIterator call --- imag-tag/src/main.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/imag-tag/src/main.rs b/imag-tag/src/main.rs index 9ed409a3..977098c0 100644 --- a/imag-tag/src/main.rs +++ b/imag-tag/src/main.rs @@ -96,8 +96,8 @@ fn alter(rt: &Runtime, id: &str, add: Option<&str>, rem: Option<&str>, set: Opti set.map(|tags| { info!("Setting tags '{}'", tags); - let tags = tags.split(',').map(String::from).collect(); - if let Err(e) = e.set_tags(tags) { + let tags : Vec<_> = tags.split(',').map(String::from).collect(); + if let Err(e) = e.set_tags(&tags) { trace_error(&e); } }); From e66d837642691de7be729b9128d73f7d73ddf3c4 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sat, 14 May 2016 19:51:24 +0200 Subject: [PATCH 045/288] Remove unneeded scopes --- libimagutil/src/key_value_split.rs | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/libimagutil/src/key_value_split.rs b/libimagutil/src/key_value_split.rs index b5e2790e..f1a7a7c7 100644 --- a/libimagutil/src/key_value_split.rs +++ b/libimagutil/src/key_value_split.rs @@ -56,18 +56,10 @@ impl IntoKeyValue for String { .unwrap(); } R.captures(&self[..]) - .map(|caps| { - caps.name("VALUE") - .or(caps.name("QVALUE")) - .unwrap_or("") - }) + .map(|caps| caps.name("VALUE").or(caps.name("QVALUE")).unwrap_or("")) }; - key.and_then(|k| { - value.and_then(|v| { - Some(KeyValue::new(String::from(k), String::from(v))) - }) - }) + key.and_then(|k| value.and_then(|v| Some(KeyValue::new(String::from(k), String::from(v))))) } } From cd224eaeff9328568cdc4d0ef2a9cf153f760ec8 Mon Sep 17 00:00:00 2001 From: Andre Bogus Date: Sat, 14 May 2016 20:12:19 +0200 Subject: [PATCH 046/288] roll back closure, remove unneeded slice & imports --- imag-store/src/create.rs | 4 ++-- libimagentrytag/src/util.rs | 2 +- libimagstore/src/store.rs | 2 -- 3 files changed, 3 insertions(+), 5 deletions(-) diff --git a/imag-store/src/create.rs b/imag-store/src/create.rs index 52c105b0..fc33c9ee 100644 --- a/imag-store/src/create.rs +++ b/imag-store/src/create.rs @@ -85,8 +85,8 @@ fn create_from_cli_spec(rt: &Runtime, matches: &ArgMatches, path: &PathBuf) -> R fn create_from_source(rt: &Runtime, matches: &ArgMatches, path: &PathBuf) -> Result<()> { let content = matches .value_of("from-raw") - .ok_or_else(|| StoreError::new(StoreErrorKind::NoCommandlineCall, None)) - .map(|raw_src| string_from_raw_src(raw_src)); + .ok_or(StoreError::new(StoreErrorKind::NoCommandlineCall, None)) + .map(string_from_raw_src); if content.is_err() { return content.map(|_| ()); diff --git a/libimagentrytag/src/util.rs b/libimagentrytag/src/util.rs index 42765193..16b76a1d 100644 --- a/libimagentrytag/src/util.rs +++ b/libimagentrytag/src/util.rs @@ -1,5 +1,5 @@ use regex::Regex; pub fn is_tag(s: &str) -> bool { - Regex::new("^[a-zA-Z]([a-zA-Z0-9_-]*)$").unwrap().captures(&s[..]).is_some() + Regex::new("^[a-zA-Z]([a-zA-Z0-9_-]*)$").unwrap().captures(s).is_some() } diff --git a/libimagstore/src/store.rs b/libimagstore/src/store.rs index b93696eb..ed945a7f 100644 --- a/libimagstore/src/store.rs +++ b/libimagstore/src/store.rs @@ -7,7 +7,6 @@ use std::sync::Arc; use std::sync::RwLock; use std::collections::BTreeMap; use std::io::{Seek, SeekFrom}; -use std::io::Write; use std::convert::From; use std::convert::Into; use std::sync::Mutex; @@ -30,7 +29,6 @@ use lazyfile::LazyFile; use hook::aspect::Aspect; use hook::accessor::{ MutableHookDataAccessor, - NonMutableHookDataAccessor, StoreIdAccessor}; use hook::position::HookPosition; use hook::Hook; From 7b855f82f34a257791ebe8f29d205f2dd6c0fff6 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sat, 14 May 2016 19:47:34 +0200 Subject: [PATCH 047/288] Remove unwrap() calling by matching --- libimagrt/src/runtime.rs | 20 ++++++++------------ 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/libimagrt/src/runtime.rs b/libimagrt/src/runtime.rs index c67422cc..cae46bda 100644 --- a/libimagrt/src/runtime.rs +++ b/libimagrt/src/runtime.rs @@ -70,25 +70,21 @@ impl<'a> Runtime<'a> { spath }, PathBuf::from); - let cfg = Configuration::new(&rtp); - let cfg = if cfg.is_err() { - let e = cfg.unwrap_err(); - if e.err_type() != ConfigErrorKind::NoConfigFileFound { + let cfg = match Configuration::new(&rtp) { + Err(e) => if e.err_type() != ConfigErrorKind::NoConfigFileFound { let cause : Option> = Some(Box::new(e)); return Err(RuntimeError::new(RuntimeErrorKind::Instantiate, cause)); } else { trace_error(&e); None - } - } else { - Some(cfg.unwrap()) + }, + + Ok(cfg) => Some(cfg), }; - let store_config = { - match cfg { - Some(ref c) => c.store_config().cloned(), - None => None, - } + let store_config = match cfg { + Some(ref c) => c.store_config().cloned(), + None => None, }; if is_debugging { From ac8bcde2395e0f954c5cb405064bd21ab76bbe3e Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sat, 14 May 2016 18:59:15 +0200 Subject: [PATCH 048/288] Remove unwrap() hell by matching --- libimagstore/src/store.rs | 21 +++++++++------------ 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/libimagstore/src/store.rs b/libimagstore/src/store.rs index ed945a7f..0224eb77 100644 --- a/libimagstore/src/store.rs +++ b/libimagstore/src/store.rs @@ -1192,25 +1192,22 @@ impl Entry { ").unwrap(); } - let matches = RE.captures(s); + let matches = match RE.captures(s) { + None => return Err(StoreError::new(StoreErrorKind::MalformedEntry, None)), + Some(s) => s, + }; - if matches.is_none() { - return Err(StoreError::new(StoreErrorKind::MalformedEntry, None)); - } + let header = match matches.name("header") { + None => return Err(StoreError::new(StoreErrorKind::MalformedEntry, None)), + Some(s) => s + }; - 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)); - } - debug!("Header and content found. Yay! Building Entry object now"); Ok(Entry { location: loc.into_storeid(), - header: try!(EntryHeader::parse(header.unwrap())), + header: try!(EntryHeader::parse(header)), content: content.into(), }) } From 3fb6d507e509813f57750db419d19f74c68d1e1f Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sat, 14 May 2016 19:05:11 +0200 Subject: [PATCH 049/288] Remove unwrap() by matching --- libimagstore/src/store.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/libimagstore/src/store.rs b/libimagstore/src/store.rs index 0224eb77..0ba28816 100644 --- a/libimagstore/src/store.rs +++ b/libimagstore/src/store.rs @@ -302,11 +302,11 @@ impl Store { return Err(e); } - let hsmap = self.entries.write(); - if hsmap.is_err() { - return Err(StoreError::new(StoreErrorKind::LockPoisoned, None)) - } - let mut hsmap = hsmap.unwrap(); + let mut hsmap = match self.entries.write() { + Err(_) => return Err(StoreError::new(StoreErrorKind::LockPoisoned, None)), + Ok(s) => s, + }; + if hsmap.contains_key(&id) { return Err(StoreError::new(StoreErrorKind::EntryAlreadyExists, None)) } From a852da54ddb162bccad53253d8bb36a8dba8bc89 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sat, 14 May 2016 19:05:32 +0200 Subject: [PATCH 050/288] Remove iflet by using Option::{map_err, and}() --- libimagstore/src/store.rs | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/libimagstore/src/store.rs b/libimagstore/src/store.rs index 0ba28816..63cd22e2 100644 --- a/libimagstore/src/store.rs +++ b/libimagstore/src/store.rs @@ -341,12 +341,9 @@ impl Store { }) .map(|e| FileLockEntry::new(self, e, id)) .and_then(|mut fle| { - if let Err(e) = self.execute_hooks_for_mut_file(self.post_retrieve_aspects.clone(), &mut fle) { - Err(StoreError::new(StoreErrorKind::HookExecutionError, Some(Box::new(e)))) - } else { - Ok(fle) - } - + self.execute_hooks_for_mut_file(self.pre_retrieve_aspects.clone(), &mut fle) + .map_err(|e| StoreError::new(StoreErrorKind::HookExecutionError, Some(Box::new(e)))) + .and(Ok(fle)) }) } From f9f5fa57173a338695b50f92bc6b6783e773bb92 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sat, 14 May 2016 19:05:54 +0200 Subject: [PATCH 051/288] Shorten code by using StoreError as SE and StoreErrorKind as SEK --- libimagstore/src/store.rs | 102 +++++++++++++++++++------------------- 1 file changed, 51 insertions(+), 51 deletions(-) diff --git a/libimagstore/src/store.rs b/libimagstore/src/store.rs index 63cd22e2..1e5c1c3b 100644 --- a/libimagstore/src/store.rs +++ b/libimagstore/src/store.rs @@ -23,7 +23,7 @@ use walkdir::WalkDir; use walkdir::Iter as WalkDirIter; use error::{ParserErrorKind, ParserError}; -use error::{StoreError, StoreErrorKind}; +use error::{StoreError as SE, StoreErrorKind as SEK}; use storeid::{IntoStoreId, StoreId, StoreIdIterator}; use lazyfile::LazyFile; @@ -36,7 +36,7 @@ use hook::Hook; use self::glob_store_iter::*; /// The Result Type returned by any interaction with the store that could fail -pub type Result = RResult; +pub type Result = RResult; #[derive(Debug, PartialEq)] @@ -125,7 +125,7 @@ impl StoreEntry { if !self.is_borrowed() { let file = self.file.get_file_mut(); if let Err(err) = file { - if err.err_type() == StoreErrorKind::FileNotFound { + if err.err_type() == SEK::FileNotFound { Ok(Entry::new(self.id.clone())) } else { Err(err) @@ -138,7 +138,7 @@ impl StoreEntry { entry } } else { - Err(StoreError::new(StoreErrorKind::EntryAlreadyBorrowed, None)) + Err(SE::new(SEK::EntryAlreadyBorrowed, None)) } } @@ -149,9 +149,9 @@ impl StoreEntry { assert_eq!(self.id, entry.location); try!(file.set_len(0) - .map_err(|e| StoreError::new(StoreErrorKind::FileError, Some(Box::new(e))))); + .map_err(|e| SE::new(SEK::FileError, Some(Box::new(e))))); file.write_all(entry.to_str().as_bytes()) - .map_err(|e| StoreError::new(StoreErrorKind::FileError, Some(Box::new(e)))) + .map_err(|e| SE::new(SEK::FileError, Some(Box::new(e)))) } else { Ok(()) } @@ -199,7 +199,7 @@ impl Store { debug!("Validating Store configuration"); if !config_is_valid(&store_config) { - return Err(StoreError::new(StoreErrorKind::ConfigurationError, None)); + return Err(SE::new(SEK::ConfigurationError, None)); } debug!("Building new Store object"); @@ -208,12 +208,12 @@ impl Store { let c = create_dir_all(location.clone()); if c.is_err() { debug!("Failed"); - return Err(StoreError::new(StoreErrorKind::StorePathCreate, + return Err(SE::new(SEK::StorePathCreate, Some(Box::new(c.unwrap_err())))); } } else if location.is_file() { debug!("Store path exists as file"); - return Err(StoreError::new(StoreErrorKind::StorePathExists, None)); + return Err(SE::new(SEK::StorePathExists, None)); } let pre_create_aspects = get_pre_create_aspect_names(&store_config) @@ -303,12 +303,12 @@ impl Store { } let mut hsmap = match self.entries.write() { - Err(_) => return Err(StoreError::new(StoreErrorKind::LockPoisoned, None)), + Err(_) => return Err(SE::new(SEK::LockPoisoned, None)), Ok(s) => s, }; if hsmap.contains_key(&id) { - return Err(StoreError::new(StoreErrorKind::EntryAlreadyExists, None)) + return Err(SE::new(SEK::EntryAlreadyExists, None)) } hsmap.insert(id.clone(), { let mut se = StoreEntry::new(id.clone()); @@ -318,7 +318,7 @@ impl Store { let mut fle = FileLockEntry::new(self, Entry::new(id.clone()), id); self.execute_hooks_for_mut_file(self.post_create_aspects.clone(), &mut fle) - .map_err(|e| StoreError::new(StoreErrorKind::PostHookExecuteError, Some(Box::new(e)))) + .map_err(|e| SE::new(SEK::PostHookExecuteError, Some(Box::new(e)))) .map(|_| fle) } @@ -332,7 +332,7 @@ impl Store { self.entries .write() - .map_err(|_| StoreError::new(StoreErrorKind::LockPoisoned, None)) + .map_err(|_| SE::new(SEK::LockPoisoned, None)) .and_then(|mut es| { let mut se = es.entry(id.clone()).or_insert_with(|| StoreEntry::new(id.clone())); let entry = se.get_entry(); @@ -342,7 +342,7 @@ impl Store { .map(|e| FileLockEntry::new(self, e, id)) .and_then(|mut fle| { self.execute_hooks_for_mut_file(self.pre_retrieve_aspects.clone(), &mut fle) - .map_err(|e| StoreError::new(StoreErrorKind::HookExecutionError, Some(Box::new(e)))) + .map_err(|e| SE::new(SEK::HookExecutionError, Some(Box::new(e)))) .and(Ok(fle)) }) } @@ -357,9 +357,9 @@ impl Store { debug!("glob()ing with '{}'", path); glob(&path[..]) .map(|paths| StoreIdIterator::new(Box::new(GlobStoreIdIterator::new(paths)))) - .map_err(|e| StoreError::new(StoreErrorKind::GlobError, Some(Box::new(e)))) + .map_err(|e| SE::new(SEK::GlobError, Some(Box::new(e)))) } else { - Err(StoreError::new(StoreErrorKind::EncodingError, None)) + Err(SE::new(SEK::EncodingError, None)) } } @@ -389,11 +389,11 @@ impl Store { fn _update<'a>(&'a self, entry: &FileLockEntry<'a>) -> Result<()> { let hsmap = self.entries.write(); if hsmap.is_err() { - return Err(StoreError::new(StoreErrorKind::LockPoisoned, None)) + return Err(SE::new(SEK::LockPoisoned, None)) } let mut hsmap = hsmap.unwrap(); let mut se = try!(hsmap.get_mut(&entry.key) - .ok_or(StoreError::new(StoreErrorKind::IdNotFound, None))); + .ok_or(SE::new(SEK::IdNotFound, None))); assert!(se.is_borrowed(), "Tried to update a non borrowed entry."); @@ -413,14 +413,14 @@ impl Store { let id = self.storify_id(id.into_storeid()); let entries_lock = self.entries.write(); if entries_lock.is_err() { - return Err(StoreError::new(StoreErrorKind::LockPoisoned, None)) + return Err(SE::new(SEK::LockPoisoned, None)) } let entries = entries_lock.unwrap(); // if the entry is currently modified by the user, we cannot drop it if entries.get(&id).map(|e| e.is_borrowed()).unwrap_or(false) { - return Err(StoreError::new(StoreErrorKind::IdLocked, None)); + return Err(SE::new(SEK::IdLocked, None)); } StoreEntry::new(id).get_entry() @@ -435,20 +435,20 @@ impl Store { let entries_lock = self.entries.write(); if entries_lock.is_err() { - return Err(StoreError::new(StoreErrorKind::LockPoisoned, None)) + return Err(SE::new(SEK::LockPoisoned, None)) } let mut entries = entries_lock.unwrap(); // if the entry is currently modified by the user, we cannot drop it if entries.get(&id).map(|e| e.is_borrowed()).unwrap_or(false) { - return Err(StoreError::new(StoreErrorKind::IdLocked, None)); + return Err(SE::new(SEK::IdLocked, None)); } // remove the entry first, then the file entries.remove(&id); if let Err(e) = remove_file(&id) { - return Err(StoreError::new(StoreErrorKind::FileError, Some(Box::new(e)))); + return Err(SE::new(SEK::FileError, Some(Box::new(e)))); } self.execute_hooks_for_id(self.post_delete_aspects.clone(), &id) @@ -483,10 +483,10 @@ impl Store { let guard = guard .deref() .lock() - .map_err(|_| StoreError::new(StoreErrorKind::LockError, None)); + .map_err(|_| SE::new(SEK::LockError, None)); if guard.is_err() { - return Err(StoreError::new(StoreErrorKind::HookRegisterError, + return Err(SE::new(SEK::HookRegisterError, Some(Box::new(guard.err().unwrap())))); } let mut guard = guard.unwrap(); @@ -498,8 +498,8 @@ impl Store { } } - let annfe = StoreError::new(StoreErrorKind::AspectNameNotFoundError, None); - Err(StoreError::new(StoreErrorKind::HookRegisterError, Some(Box::new(annfe)))) + let annfe = SE::new(SEK::AspectNameNotFoundError, None); + Err(SE::new(SEK::HookRegisterError, Some(Box::new(annfe)))) } fn get_config_for_hook(&self, name: &str) -> Option<&Value> { @@ -524,14 +524,14 @@ impl Store { -> Result<()> { let guard = aspects.deref().lock(); - if guard.is_err() { return Err(StoreError::new(StoreErrorKind::PreHookExecuteError, None)) } + if guard.is_err() { return Err(SE::new(SEK::PreHookExecuteError, None)) } guard.unwrap().deref().iter() .fold(Ok(()), |acc, aspect| { debug!("[Aspect][exec]: {:?}", aspect); acc.and_then(|_| (aspect as &StoreIdAccessor).access(id)) }) - .map_err(|e| StoreError::new(StoreErrorKind::PreHookExecuteError, Some(Box::new(e)))) + .map_err(|e| SE::new(SEK::PreHookExecuteError, Some(Box::new(e)))) } fn execute_hooks_for_mut_file(&self, @@ -540,14 +540,14 @@ impl Store { -> Result<()> { let guard = aspects.deref().lock(); - if guard.is_err() { return Err(StoreError::new(StoreErrorKind::PreHookExecuteError, None)) } + if guard.is_err() { return Err(SE::new(SEK::PreHookExecuteError, None)) } guard.unwrap().deref().iter() .fold(Ok(()), |acc, aspect| { debug!("[Aspect][exec]: {:?}", aspect); acc.and_then(|_| aspect.access_mut(fle)) }) - .map_err(|e| StoreError::new(StoreErrorKind::PreHookExecuteError, Some(Box::new(e)))) + .map_err(|e| SE::new(SEK::PreHookExecuteError, Some(Box::new(e)))) } } @@ -682,7 +682,7 @@ impl EntryHeader { pub fn verify(&self) -> Result<()> { match self.header { Value::Table(ref t) => verify_header(&t), - _ => Err(StoreError::new(StoreErrorKind::HeaderTypeFailure, None)), + _ => Err(SE::new(SEK::HeaderTypeFailure, None)), } } @@ -724,7 +724,7 @@ impl EntryHeader { let destination = tokens.iter().last(); if destination.is_none() { - return Err(StoreError::new(StoreErrorKind::HeaderPathSyntaxError, None)); + return Err(SE::new(SEK::HeaderPathSyntaxError, None)); } let destination = destination.unwrap(); @@ -753,7 +753,7 @@ impl EntryHeader { /* * Fail if there is no map here */ - _ => return Err(StoreError::new(StoreErrorKind::HeaderPathTypeFailure, None)), + _ => return Err(SE::new(SEK::HeaderPathTypeFailure, None)), } }, @@ -776,7 +776,7 @@ impl EntryHeader { /* * Fail if there is no array here */ - _ => return Err(StoreError::new(StoreErrorKind::HeaderPathTypeFailure, None)), + _ => return Err(SE::new(SEK::HeaderPathTypeFailure, None)), } }, } @@ -821,7 +821,7 @@ impl EntryHeader { let destination = tokens.iter().last(); if destination.is_none() { - return Err(StoreError::new(StoreErrorKind::HeaderPathSyntaxError, None)); + return Err(SE::new(SEK::HeaderPathSyntaxError, None)); } let destination = destination.unwrap(); debug!("destination = {:?}", destination); @@ -850,7 +850,7 @@ impl EntryHeader { */ _ => { debug!("Matched Key->NON-Table"); - return Err(StoreError::new(StoreErrorKind::HeaderPathTypeFailure, None)); + return Err(SE::new(SEK::HeaderPathTypeFailure, None)); } } }, @@ -881,7 +881,7 @@ impl EntryHeader { */ _ => { debug!("Matched Index->NON-Array"); - return Err(StoreError::new(StoreErrorKind::HeaderPathTypeFailure, None)); + return Err(SE::new(SEK::HeaderPathTypeFailure, None)); }, } }, @@ -931,7 +931,7 @@ impl EntryHeader { let e = value.unwrap_err(); return match e.err_type() { // We cannot find the header key, as there is no path to it - StoreErrorKind::HeaderKeyNotFound => Ok(None), + SEK::HeaderKeyNotFound => Ok(None), _ => Err(e), }; } @@ -947,7 +947,7 @@ impl EntryHeader { let destination = tokens.iter().last(); if destination.is_none() { - return Err(StoreError::new(StoreErrorKind::HeaderPathSyntaxError, None)); + return Err(SE::new(SEK::HeaderPathSyntaxError, None)); } let destination = destination.unwrap(); debug!("destination = {:?}", destination); @@ -969,7 +969,7 @@ impl EntryHeader { }, _ => { debug!("Matched Key->NON-Table"); - return Err(StoreError::new(StoreErrorKind::HeaderPathTypeFailure, None)); + return Err(SE::new(SEK::HeaderPathTypeFailure, None)); } } }, @@ -988,7 +988,7 @@ impl EntryHeader { }, _ => { debug!("Matched Index->NON-Array"); - return Err(StoreError::new(StoreErrorKind::HeaderPathTypeFailure, None)); + return Err(SE::new(SEK::HeaderPathTypeFailure, None)); }, } }, @@ -1030,9 +1030,9 @@ impl EntryHeader { match *v { Value::Table(ref mut t) => { t.get_mut(&s[..]) - .ok_or(StoreError::new(StoreErrorKind::HeaderKeyNotFound, None)) + .ok_or(SE::new(SEK::HeaderKeyNotFound, None)) }, - _ => Err(StoreError::new(StoreErrorKind::HeaderPathTypeFailure, None)), + _ => Err(SE::new(SEK::HeaderPathTypeFailure, None)), } } @@ -1040,12 +1040,12 @@ impl EntryHeader { match *v { Value::Array(ref mut a) => { if a.len() < i { - Err(StoreError::new(StoreErrorKind::HeaderKeyNotFound, None)) + Err(SE::new(SEK::HeaderKeyNotFound, None)) } else { Ok(&mut a[i]) } }, - _ => Err(StoreError::new(StoreErrorKind::HeaderPathTypeFailure, None)), + _ => Err(SE::new(SEK::HeaderPathTypeFailure, None)), } } @@ -1093,12 +1093,12 @@ fn build_default_header() -> Value { // BTreeMap } fn verify_header(t: &Table) -> Result<()> { if !has_main_section(t) { - Err(StoreError::from(ParserError::new(ParserErrorKind::MissingMainSection, None))) + Err(SE::from(ParserError::new(ParserErrorKind::MissingMainSection, None))) } else if !has_imag_version_in_main_section(t) { - Err(StoreError::from(ParserError::new(ParserErrorKind::MissingVersionInfo, None))) + Err(SE::from(ParserError::new(ParserErrorKind::MissingVersionInfo, None))) } else if !has_only_tables(t) { debug!("Could not verify that it only has tables in its base table"); - Err(StoreError::from(ParserError::new(ParserErrorKind::NonTableInBaseTable, None))) + Err(SE::from(ParserError::new(ParserErrorKind::NonTableInBaseTable, None))) } else { Ok(()) } @@ -1190,12 +1190,12 @@ impl Entry { } let matches = match RE.captures(s) { - None => return Err(StoreError::new(StoreErrorKind::MalformedEntry, None)), + None => return Err(SE::new(SEK::MalformedEntry, None)), Some(s) => s, }; let header = match matches.name("header") { - None => return Err(StoreError::new(StoreErrorKind::MalformedEntry, None)), + None => return Err(SE::new(SEK::MalformedEntry, None)), Some(s) => s }; From 7b612ce8fb88fe44b913cbd05d1e1abcf4c00b79 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sat, 14 May 2016 19:10:25 +0200 Subject: [PATCH 052/288] Remove iflet by mapping over Option/Result types --- libimagstore/src/store.rs | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/libimagstore/src/store.rs b/libimagstore/src/store.rs index 1e5c1c3b..b9c727fc 100644 --- a/libimagstore/src/store.rs +++ b/libimagstore/src/store.rs @@ -352,15 +352,14 @@ impl Store { let mut path = self.path().clone(); path.push(mod_name); - if let Some(path) = path.to_str() { - let path = [ path, "/*" ].join(""); - debug!("glob()ing with '{}'", path); - glob(&path[..]) - .map(|paths| StoreIdIterator::new(Box::new(GlobStoreIdIterator::new(paths)))) - .map_err(|e| SE::new(SEK::GlobError, Some(Box::new(e)))) - } else { - Err(SE::new(SEK::EncodingError, None)) - } + path.to_str() + .ok_or(SE::new(SEK::EncodingError, None)) + .and_then(|path| { + let path = [ path, "/*" ].join(""); + debug!("glob()ing with '{}'", path); + glob(&path[..]).map_err(|e| SE::new(SEK::GlobError, Some(Box::new(e)))) + }) + .map(|paths| StoreIdIterator::new(Box::new(GlobStoreIdIterator::new(paths)))) } // Walk the store tree for the module From 1f66f67791762e3d2bde0f823b3db94f69c0b8cf Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sat, 14 May 2016 19:12:13 +0200 Subject: [PATCH 053/288] Replaced unwrap() by matching --- libimagstore/src/store.rs | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/libimagstore/src/store.rs b/libimagstore/src/store.rs index b9c727fc..4b30a025 100644 --- a/libimagstore/src/store.rs +++ b/libimagstore/src/store.rs @@ -386,13 +386,12 @@ impl Store { /// This method assumes that entry is dropped _right after_ the call, hence /// it is not public. fn _update<'a>(&'a self, entry: &FileLockEntry<'a>) -> Result<()> { - let hsmap = self.entries.write(); - if hsmap.is_err() { - return Err(SE::new(SEK::LockPoisoned, None)) - } - let mut hsmap = hsmap.unwrap(); - let mut se = try!(hsmap.get_mut(&entry.key) - .ok_or(SE::new(SEK::IdNotFound, None))); + let mut hsmap = match self.entries.write() { + Err(_) => return Err(SE::new(SEK::LockPoisoned, None)), + Ok(e) => e, + }; + + let mut se = try!(hsmap.get_mut(&entry.key).ok_or(SE::new(SEK::IdNotFound, None))); assert!(se.is_borrowed(), "Tried to update a non borrowed entry."); From 70b3d3906ec1dd624a59343e9325efc48b33728c Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sat, 14 May 2016 19:14:11 +0200 Subject: [PATCH 054/288] Replace unwrap() by matching --- libimagstore/src/store.rs | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/libimagstore/src/store.rs b/libimagstore/src/store.rs index 4b30a025..ec6353c4 100644 --- a/libimagstore/src/store.rs +++ b/libimagstore/src/store.rs @@ -409,12 +409,10 @@ impl Store { /// the one on disk pub fn retrieve_copy(&self, id: S) -> Result { let id = self.storify_id(id.into_storeid()); - let entries_lock = self.entries.write(); - if entries_lock.is_err() { - return Err(SE::new(SEK::LockPoisoned, None)) - } - - let entries = entries_lock.unwrap(); + let entries = match self.entries.write() { + Err(_) => return Err(SE::new(SEK::LockPoisoned, None)), + Ok(e) => e, + }; // if the entry is currently modified by the user, we cannot drop it if entries.get(&id).map(|e| e.is_borrowed()).unwrap_or(false) { From 1e1cbec98b3a6a20bffbef75d3219878cbb8f759 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sat, 14 May 2016 19:14:19 +0200 Subject: [PATCH 055/288] Replace unwrap() by matching --- libimagstore/src/store.rs | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/libimagstore/src/store.rs b/libimagstore/src/store.rs index ec6353c4..964730be 100644 --- a/libimagstore/src/store.rs +++ b/libimagstore/src/store.rs @@ -429,12 +429,10 @@ impl Store { return Err(e); } - let entries_lock = self.entries.write(); - if entries_lock.is_err() { - return Err(SE::new(SEK::LockPoisoned, None)) - } - - let mut entries = entries_lock.unwrap(); + let mut entries = match self.entries.write() { + Err(_) => return Err(SE::new(SEK::LockPoisoned, None)), + Ok(e) => e, + }; // if the entry is currently modified by the user, we cannot drop it if entries.get(&id).map(|e| e.is_borrowed()).unwrap_or(false) { From a481200c9ae4f14d1816ed6cd685acddde15219b Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sat, 14 May 2016 19:15:51 +0200 Subject: [PATCH 056/288] Replace unwrap() by matching --- libimagstore/src/store.rs | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/libimagstore/src/store.rs b/libimagstore/src/store.rs index 964730be..c346fea7 100644 --- a/libimagstore/src/store.rs +++ b/libimagstore/src/store.rs @@ -474,16 +474,11 @@ impl Store { HookPosition::PostDelete => self.post_delete_aspects.clone(), }; - let guard = guard - .deref() - .lock() - .map_err(|_| SE::new(SEK::LockError, None)); + let mut guard = match guard.deref().lock().map_err(|_| SE::new(SEK::LockError, None)) { + Err(e) => return Err(SE::new(SEK::HookRegisterError, Some(Box::new(e)))), + Ok(g) => g, + }; - if guard.is_err() { - return Err(SE::new(SEK::HookRegisterError, - Some(Box::new(guard.err().unwrap())))); - } - let mut guard = guard.unwrap(); for mut aspect in guard.deref_mut() { if aspect.name().clone() == aspect_name.clone() { self.get_config_for_hook(h.name()).map(|config| h.set_config(config)); From 8d9bd5154dc4373187f3dedd2abc7c613d847d3b Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sat, 14 May 2016 19:17:44 +0200 Subject: [PATCH 057/288] Remove unwrap() by matching, remove unneeded deref() --- libimagstore/src/store.rs | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/libimagstore/src/store.rs b/libimagstore/src/store.rs index c346fea7..b853b594 100644 --- a/libimagstore/src/store.rs +++ b/libimagstore/src/store.rs @@ -512,15 +512,13 @@ impl Store { id: &StoreId) -> Result<()> { - let guard = aspects.deref().lock(); - if guard.is_err() { return Err(SE::new(SEK::PreHookExecuteError, None)) } - - guard.unwrap().deref().iter() - .fold(Ok(()), |acc, aspect| { - debug!("[Aspect][exec]: {:?}", aspect); - acc.and_then(|_| (aspect as &StoreIdAccessor).access(id)) - }) - .map_err(|e| SE::new(SEK::PreHookExecuteError, Some(Box::new(e)))) + match aspects.lock() { + Err(_) => return Err(SE::new(SEK::PreHookExecuteError, None)), + Ok(g) => g + }.iter().fold(Ok(()), |acc, aspect| { + debug!("[Aspect][exec]: {:?}", aspect); + acc.and_then(|_| (aspect as &StoreIdAccessor).access(id)) + }).map_err(|e| SE::new(SEK::PreHookExecuteError, Some(Box::new(e)))) } fn execute_hooks_for_mut_file(&self, From 2a6e4c62feb362ac34bebe701dbb746c1b7fabda Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sat, 14 May 2016 19:17:47 +0200 Subject: [PATCH 058/288] Remove unwrap() by matching, remove unneeded deref() --- libimagstore/src/store.rs | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/libimagstore/src/store.rs b/libimagstore/src/store.rs index b853b594..c124c41e 100644 --- a/libimagstore/src/store.rs +++ b/libimagstore/src/store.rs @@ -526,15 +526,13 @@ impl Store { fle: &mut FileLockEntry) -> Result<()> { - let guard = aspects.deref().lock(); - if guard.is_err() { return Err(SE::new(SEK::PreHookExecuteError, None)) } - - guard.unwrap().deref().iter() - .fold(Ok(()), |acc, aspect| { - debug!("[Aspect][exec]: {:?}", aspect); - acc.and_then(|_| aspect.access_mut(fle)) - }) - .map_err(|e| SE::new(SEK::PreHookExecuteError, Some(Box::new(e)))) + match aspects.lock() { + Err(_) => return Err(SE::new(SEK::PreHookExecuteError, None)), + Ok(g) => g + }.iter().fold(Ok(()), |acc, aspect| { + debug!("[Aspect][exec]: {:?}", aspect); + acc.and_then(|_| aspect.access_mut(fle)) + }).map_err(|e| SE::new(SEK::PreHookExecuteError, Some(Box::new(e)))) } } From 604e59ae3cc089b116b6c9a07a56f1895637ce51 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sat, 14 May 2016 19:24:01 +0200 Subject: [PATCH 059/288] Remove unwrap() calls by matching --- libimagstore/src/store.rs | 29 ++++++++++++++--------------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/libimagstore/src/store.rs b/libimagstore/src/store.rs index c124c41e..90a3b54b 100644 --- a/libimagstore/src/store.rs +++ b/libimagstore/src/store.rs @@ -701,24 +701,23 @@ impl EntryHeader { } pub fn insert_with_sep(&mut self, spec: &str, sep: char, v: Value) -> Result { - let tokens = EntryHeader::tokenize(spec, sep); - if tokens.is_err() { // return parser error if any - return tokens.map(|_| false); - } - let tokens = tokens.unwrap(); + let tokens = match EntryHeader::tokenize(spec, sep) { + Err(e) => return Err(e), + Ok(t) => t + }; - let destination = tokens.iter().last(); - if destination.is_none() { - return Err(SE::new(SEK::HeaderPathSyntaxError, None)); - } - let destination = destination.unwrap(); + let destination = match tokens.iter().last() { + None => return Err(SE::new(SEK::HeaderPathSyntaxError, None)), + Some(d) => d, + }; let path_to_dest = tokens[..(tokens.len() - 1)].into(); // N - 1 tokens - let value = EntryHeader::walk_header(&mut self.header, path_to_dest); // walk N-1 tokens - if value.is_err() { - return value.map(|_| false); - } - let mut value = value.unwrap(); + + // walk N-1 tokens + let value = match EntryHeader::walk_header(&mut self.header, path_to_dest) { + Err(e) => return Err(e), + Ok(v) => v + }; // There is already an value at this place if EntryHeader::extract(value, destination).is_ok() { From 81810dbcc8778fb22db6b375000f378ddf699e8d Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sat, 14 May 2016 19:26:54 +0200 Subject: [PATCH 060/288] Remove unwrap() calls by matching --- libimagstore/src/store.rs | 28 +++++++++++++--------------- 1 file changed, 13 insertions(+), 15 deletions(-) diff --git a/libimagstore/src/store.rs b/libimagstore/src/store.rs index 90a3b54b..7b9e8104 100644 --- a/libimagstore/src/store.rs +++ b/libimagstore/src/store.rs @@ -796,26 +796,24 @@ impl EntryHeader { } pub fn set_with_sep(&mut self, spec: &str, sep: char, v: Value) -> Result> { - let tokens = EntryHeader::tokenize(spec, sep); - if tokens.is_err() { // return parser error if any - return Err(tokens.unwrap_err()); - } - let tokens = tokens.unwrap(); + let tokens = match EntryHeader::tokenize(spec, sep) { + Err(e) => return Err(e), + Ok(t) => t, + }; debug!("tokens = {:?}", tokens); - let destination = tokens.iter().last(); - if destination.is_none() { - return Err(SE::new(SEK::HeaderPathSyntaxError, None)); - } - let destination = destination.unwrap(); + let destination = match tokens.iter().last() { + None => return Err(SE::new(SEK::HeaderPathSyntaxError, None)), + Some(d) => d + }; debug!("destination = {:?}", destination); let path_to_dest = tokens[..(tokens.len() - 1)].into(); // N - 1 tokens - let value = EntryHeader::walk_header(&mut self.header, path_to_dest); // walk N-1 tokens - if value.is_err() { - return Err(value.unwrap_err()); - } - let mut value = value.unwrap(); + // walk N-1 tokens + let value = match EntryHeader::walk_header(&mut self.header, path_to_dest) { + Err(e) => return Err(e), + Ok(v) => v + }; debug!("walked value = {:?}", value); match *destination { From 0b7f81510419190cfe2aa1e386161590c94617a2 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sat, 14 May 2016 19:29:14 +0200 Subject: [PATCH 061/288] Remove unwrap() calls by matching --- libimagstore/src/store.rs | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/libimagstore/src/store.rs b/libimagstore/src/store.rs index 7b9e8104..73da21ba 100644 --- a/libimagstore/src/store.rs +++ b/libimagstore/src/store.rs @@ -901,23 +901,21 @@ impl EntryHeader { } pub fn read_with_sep(&self, spec: &str, splitchr: char) -> Result> { - let tokens = EntryHeader::tokenize(spec, splitchr); - if tokens.is_err() { // return parser error if any - return Err(tokens.unwrap_err()); - } - let tokens = tokens.unwrap(); + let tokens = match EntryHeader::tokenize(spec, splitchr) { + Err(e) => return Err(e), + Ok(t) => t, + }; let mut header_clone = self.header.clone(); // we clone as READing is simpler this way - let value = EntryHeader::walk_header(&mut header_clone, tokens); // walk N-1 tokens - if value.is_err() { - let e = value.unwrap_err(); - return match e.err_type() { + // walk N-1 tokens + match EntryHeader::walk_header(&mut header_clone, tokens) { + Err(e) => match e.err_type() { // We cannot find the header key, as there is no path to it SEK::HeaderKeyNotFound => Ok(None), _ => Err(e), - }; + }, + Ok(v) => Ok(Some(v.clone())), } - Ok(Some(value.unwrap().clone())) } pub fn delete(&mut self, spec: &str) -> Result> { From 944a9bf876f8a9dcdae112c59b0db0f67e61a849 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sat, 14 May 2016 19:33:41 +0200 Subject: [PATCH 062/288] Remove unwrap() calls by matching --- libimagstore/src/store.rs | 28 +++++++++++++--------------- 1 file changed, 13 insertions(+), 15 deletions(-) diff --git a/libimagstore/src/store.rs b/libimagstore/src/store.rs index 73da21ba..573efb82 100644 --- a/libimagstore/src/store.rs +++ b/libimagstore/src/store.rs @@ -919,25 +919,23 @@ impl EntryHeader { } pub fn delete(&mut self, spec: &str) -> Result> { - let tokens = EntryHeader::tokenize(spec, '.'); - if tokens.is_err() { // return parser error if any - return Err(tokens.unwrap_err()); - } - let tokens = tokens.unwrap(); + let tokens = match EntryHeader::tokenize(spec, '.') { + Err(e) => return Err(e), + Ok(t) => t + }; - let destination = tokens.iter().last(); - if destination.is_none() { - return Err(SE::new(SEK::HeaderPathSyntaxError, None)); - } - let destination = destination.unwrap(); + let destination = match tokens.iter().last() { + None => return Err(SE::new(SEK::HeaderPathSyntaxError, None)), + Some(d) => d + }; debug!("destination = {:?}", destination); let path_to_dest = tokens[..(tokens.len() - 1)].into(); // N - 1 tokens - let value = EntryHeader::walk_header(&mut self.header, path_to_dest); // walk N-1 tokens - if value.is_err() { - return Err(value.unwrap_err()); - } - let mut value = value.unwrap(); + // walk N-1 tokens + let mut value = match EntryHeader::walk_header(&mut self.header, path_to_dest) { + Err(e) => return Err(e), + Ok(v) => v + }; debug!("walked value = {:?}", value); match *destination { From a26a0645bd6e8433eb434cb7ffdcf0524e0ec454 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sat, 14 May 2016 19:37:46 +0200 Subject: [PATCH 063/288] Remove iflet by mapping --- libimagstore/src/store.rs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/libimagstore/src/store.rs b/libimagstore/src/store.rs index 573efb82..3bbdc8a6 100644 --- a/libimagstore/src/store.rs +++ b/libimagstore/src/store.rs @@ -1083,11 +1083,9 @@ fn verify_header(t: &Table) -> Result<()> { } fn verify_header_consistency(t: Table) -> EntryResult
{ - if let Err(e) = verify_header(&t) { - Err(ParserError::new(ParserErrorKind::HeaderInconsistency, Some(Box::new(e)))) - } else { - Ok(t) - } + verify_header(&t) + .map_err(|e| ParserError::new(ParserErrorKind::HeaderInconsistency, Some(Box::new(e)))) + .map(|_| t) } fn has_only_tables(t: &Table) -> bool { From a56f000e3e08f5459671b7c849d43282700b70c9 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sat, 14 May 2016 19:38:22 +0200 Subject: [PATCH 064/288] Remove unneeded scope --- libimagstore/src/store.rs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/libimagstore/src/store.rs b/libimagstore/src/store.rs index 3bbdc8a6..53cd60ca 100644 --- a/libimagstore/src/store.rs +++ b/libimagstore/src/store.rs @@ -1110,10 +1110,8 @@ fn has_imag_version_in_main_section(t: &Table) -> bool { sec.get("version") .and_then(|v| { match *v { - Value::String(ref s) => { - Some(Version::parse(&s[..]).is_ok()) - }, - _ => Some(false), + Value::String(ref s) => Some(Version::parse(&s[..]).is_ok()), + _ => Some(false), } }) .unwrap_or(false) From 072564f6b833df13f21479013c0484fff81ccc1e Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sun, 15 May 2016 00:03:51 +0200 Subject: [PATCH 065/288] Remove feature: setting tags --- imag-tag/src/main.rs | 13 ++----------- imag-tag/src/ui.rs | 8 -------- 2 files changed, 2 insertions(+), 19 deletions(-) diff --git a/imag-tag/src/main.rs b/imag-tag/src/main.rs index 977098c0..278f3978 100644 --- a/imag-tag/src/main.rs +++ b/imag-tag/src/main.rs @@ -44,9 +44,8 @@ fn main() { || { let add = rt.cli().value_of("add"); let rem = rt.cli().value_of("remove"); - let set = rt.cli().value_of("set"); - alter(&rt, id, add, rem, set); + alter(&rt, id, add, rem); }, |name| { debug!("Call: {}", name); @@ -60,7 +59,7 @@ fn main() { }); } -fn alter(rt: &Runtime, id: &str, add: Option<&str>, rem: Option<&str>, set: Option<&str>) { +fn alter(rt: &Runtime, id: &str, add: Option<&str>, rem: Option<&str>) { let path = { match build_entry_path(rt.store(), id) { Err(e) => { @@ -93,14 +92,6 @@ fn alter(rt: &Runtime, id: &str, add: Option<&str>, rem: Option<&str>, set: Opti } } }); - - set.map(|tags| { - info!("Setting tags '{}'", tags); - let tags : Vec<_> = tags.split(',').map(String::from).collect(); - if let Err(e) = e.set_tags(&tags) { - trace_error(&e); - } - }); }) .map_err(|e| { info!("No entry."); diff --git a/imag-tag/src/ui.rs b/imag-tag/src/ui.rs index 4f78bf1f..74916879 100644 --- a/imag-tag/src/ui.rs +++ b/imag-tag/src/ui.rs @@ -24,14 +24,6 @@ pub fn build_ui<'a>(app: App<'a, 'a>) -> App<'a, 'a> { .multiple(true) .help("Remove this tag")) - .arg(Arg::with_name("set") - .long("set") - .short("s") - .takes_value(true) - .required(false) - .multiple(true) - .help("Set these tags")) - .subcommand(SubCommand::with_name("list") .about("List tags (default)") .version("0.1") From 332dba028cbbe76fb06751890bab30cc2ff868dc Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sun, 15 May 2016 00:04:13 +0200 Subject: [PATCH 066/288] Rewrite adding/removing to allow adding and removing multiple tags --- imag-tag/src/main.rs | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/imag-tag/src/main.rs b/imag-tag/src/main.rs index 278f3978..f070dbd1 100644 --- a/imag-tag/src/main.rs +++ b/imag-tag/src/main.rs @@ -42,8 +42,8 @@ fn main() { .subcommand_name() .map_or_else( || { - let add = rt.cli().value_of("add"); - let rem = rt.cli().value_of("remove"); + let add = rt.cli().values_of("add").map(|o| o.map(String::from)); + let rem = rt.cli().values_of("remove").map(|o| o.map(String::from)); alter(&rt, id, add, rem); }, @@ -59,7 +59,7 @@ fn main() { }); } -fn alter(rt: &Runtime, id: &str, add: Option<&str>, rem: Option<&str>) { +fn alter>(rt: &Runtime, id: &str, add: Option, rem: Option) { let path = { match build_entry_path(rt.store(), id) { Err(e) => { @@ -76,22 +76,22 @@ fn alter(rt: &Runtime, id: &str, add: Option<&str>, rem: Option<&str>) { .retrieve(path) .map(|mut e| { add.map(|tags| { - for tag in tags.split(',') { - info!("Adding tag '{}'", tag); - if let Err(e) = e.add_tag(String::from(tag)) { + for tag in tags { + debug!("Adding tag '{:?}'", tag); + if let Err(e) = e.add_tag(tag) { trace_error(&e); } } - }); + }); // it is okay to ignore a None here rem.map(|tags| { - for tag in tags.split(',') { - info!("Removing tag '{}'", tag); - if let Err(e) = e.remove_tag(String::from(tag)) { + for tag in tags { + debug!("Removing tag '{:?}'", tag); + if let Err(e) = e.remove_tag(tag) { trace_error(&e); } } - }); + }); // it is okay to ignore a None here }) .map_err(|e| { info!("No entry."); From 3196a8c5dfae0a7dc5645f2a570b20137ac3e41a Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sun, 15 May 2016 16:23:43 +0200 Subject: [PATCH 067/288] Contributing: Add label explanation --- CONTRIBUTING.md | 119 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 119 insertions(+) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0fd002ee..ea3e73ef 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -95,7 +95,126 @@ ask questions as well! Feel free to reach out via mail. +## More information about the structure of this project + +Here goes some notes on how this project is structured. + +### Issue- and PR-Labels + +Our labels are color coded as well as "namespaced". The color groups labels +exactly as the prefix does. The prefix is the first component which is seperated +from the others by `"/`". See below: + +| Label | Description | search | +| --- | --- | --- | +| complexity/easy | Easy to do | [search][search-complexity/easy] | +| complexity/high | Not so easy to do | [search][search-complexity/high] | +| complexity/medium | Relatively easy | [search][search-complexity/medium] | +| kind/bug | Bug | [search][search-kind/bug] | +| kind/doc | Documentation related | [search][search-kind/doc] | +| kind/enhancement | Enhancement | [search][search-kind/enhancement] | +| kind/feature | Feature | [search][search-kind/feature] | +| kind/hotfix | Hotfix | [search][search-kind/hotfix] | +| kind/infrastructure | Infrastructure code | [search][search-kind/infrastructure] | +| kind/invalid | Not valid Issue/PR | [search][search-kind/invalid] | +| kind/nicetohave | Would be a nice thing | [search][search-kind/nicetohave] | +| kind/refactor | Refactor codebase | [search][search-kind/refactor] | +| meta/assigned | Is assigned | [search][search-meta/assigned] | +| meta/blocked | Blocked by other Issue/PR | [search][search-meta/blocked] | +| meta/blocker | Blocks other Issue/PR | [search][search-meta/blocker] | +| meta/decision-pending | Not clear what to do | [search][search-meta/decision-pending] | +| meta/dependencies | Dependency-related | [search][search-meta/dependencies] | +| meta/doc | Documentation related | [search][search-meta/doc] | +| meta/importance/high | Very Important | [search][search-meta/importance/high] | +| meta/importance/low | Not so important | [search][search-meta/importance/low] | +| meta/importance/medium | Rather important | [search][search-meta/importance/medium] | +| meta/on-hold | Do not work on this! | [search][search-meta/on-hold] | +| meta/ready | Ready for review/merge | [search][search-meta/ready] | +| meta/reopen-later | Reopen closed issue/pr later | [search][search-meta/reopen-later] | +| meta/WIP | Work in Progress | [search][search-meta/WIP] | +| nochange/duplicate | Duplicated | [search][search-nochange/duplicate] | +| nochange/question | Question | [search][search-nochange/question] | +| nochange/rfc | Request for comments | [search][search-nochange/rfc] | +| nochange/wontfix | Won't fix this issue | [search][search-nochange/wontfix] | +| part/bin/imag-counter | Targets binary: imag-counter | [search][search-part/bin/imag-counter] | +| part/bin/imag-link | Targets binary: imag-link | [search][search-part/bin/imag-link] | +| part/bin/imag-store | Targets binary: imag-store | [search][search-part/bin/imag-store] | +| part/bin/imag-tag | Targets binary: imag-tag | [search][search-part/bin/imag-tag] | +| part/bin/imag-view | Targets binary: imag-view | [search][search-part/bin/imag-view] | +| part/interface | Changes the interface | [search][search-part/interface] | +| part/lib/imagcounter | Targets library: imagcounter | [search][search-part/lib/imagcounter] | +| part/lib/imagentryfilter | Targets library: imagentryfilter | [search][search-part/lib/imagentryfilter] | +| part/lib/imagentrylink | Targets library: imagentrylink | [search][search-part/lib/imagentrylink] | +| part/lib/imagentrylist | Targets library: imagentrylist | [search][search-part/lib/imagentrylist] | +| part/lib/imagentrymarkup | Targets library: imagentrymarkup | [search][search-part/lib/imagentrymarkup] | +| part/lib/imagentryprinter | Targets library: imagentryprinter | [search][search-part/lib/imagentryprinter] | +| part/lib/imagentrytag | Targets library: imagentrytag | [search][search-part/lib/imagentrytag] | +| part/lib/imagentryview | Targets library: imagentryview | [search][search-part/lib/imagentryview] | +| part/lib/imagnotes | Targets library: imagnotes | [search][search-part/lib/imagnotes] | +| part/lib/imagrt | Targets library: imagrt | [search][search-part/lib/imagrt] | +| part/lib/imagstore | Targets library: imagstore | [search][search-part/lib/imagstore] | +| part/lib/imagstorestdhook | Targets library: imagstorestdhook | [search][search-part/lib/imagstorestdhook] | +| part/lib/imagutil | Targets library: | [search][search-part/lib/imagutil] | +| part/_new_binary | Introduces new binary | [search][search-part/_new_binary] | +| part/_new_library | Introduces new library | [search][search-part/_new_library] | +| test/change | Changes a test | [search][search-test/change] | +| test/missing | Test missing | [search][search-test/missing] | +| test/new | New test | [search][search-test/new] | + ## FAQ _to be written_ +[search-complexity/easy]: https://github.com/matthiasbeyer/imag/labels/ +[search-complexity/high]: https://github.com/matthiasbeyer/imag/labels/complexity%2Fhigh +[search-complexity/medium]: https://github.com/matthiasbeyer/imag/labels/complexity%2Fmedium +[search-kind/bug]: https://github.com/matthiasbeyer/imag/labels/kind%2Fbug +[search-kind/doc]: https://github.com/matthiasbeyer/imag/labels/kind%2Fdoc +[search-kind/enhancement]: https://github.com/matthiasbeyer/imag/labels/kind%2Fenhancement +[search-kind/feature]: https://github.com/matthiasbeyer/imag/labels/kind%2Ffeature +[search-kind/hotfix]: https://github.com/matthiasbeyer/imag/labels/kind%2Fhotfix +[search-kind/infrastructure]: https://github.com/matthiasbeyer/imag/labels/kind%2Finfrastructure +[search-kind/invalid]: https://github.com/matthiasbeyer/imag/labels/kind%2Finvalid +[search-kind/nicetohave]: https://github.com/matthiasbeyer/imag/labels/kind%2Fnicetohave +[search-kind/refactor]: https://github.com/matthiasbeyer/imag/labels/kind%2Frefactor +[search-meta/assigned]: https://github.com/matthiasbeyer/imag/labels/meta%2Fassigned +[search-meta/blocked]: https://github.com/matthiasbeyer/imag/labels/meta%2Fblocked +[search-meta/blocker]: https://github.com/matthiasbeyer/imag/labels/meta%2Fblocker +[search-meta/decision-pending]: https://github.com/matthiasbeyer/imag/labels/meta%2Fdecision-pending +[search-meta/dependencies]: https://github.com/matthiasbeyer/imag/labels/meta%2Fdependencies +[search-meta/doc]: https://github.com/matthiasbeyer/imag/labels/meta%2Fdoc +[search-meta/importance/high]: https://github.com/matthiasbeyer/imag/labels/meta%2Fimportance%2Fhigh +[search-meta/importance/low]: https://github.com/matthiasbeyer/imag/labels/meta%2Fimportance%2Flow +[search-meta/importance/medium]: https://github.com/matthiasbeyer/imag/labels/meta%2Fimportance%2Fmedium +[search-meta/on-hold]: https://github.com/matthiasbeyer/imag/labels/meta%2Fon-hold +[search-meta/ready]: https://github.com/matthiasbeyer/imag/labels/meta%2Fready +[search-meta/reopen-later]: https://github.com/matthiasbeyer/imag/labels/meta%2Freopen-later +[search-meta/WIP]: https://github.com/matthiasbeyer/imag/labels/meta%2FWIP +[search-nochange/duplicate]: https://github.com/matthiasbeyer/imag/labels/nochange%2Fduplicate +[search-nochange/question]: https://github.com/matthiasbeyer/imag/labels/nochange%2Fquestion +[search-nochange/rfc]: https://github.com/matthiasbeyer/imag/labels/nochange%2Frfc +[search-nochange/wontfix]: https://github.com/matthiasbeyer/imag/labels/nochange%2Fwontfix +[search-part/bin/imag-counter]: https://github.com/matthiasbeyer/imag/labels/part%2Fbin%2Fimag-counter +[search-part/bin/imag-link]: https://github.com/matthiasbeyer/imag/labels/part%2Fbin%2Fimag-link +[search-part/bin/imag-store]: https://github.com/matthiasbeyer/imag/labels/part%2Fbin%2Fimag-store +[search-part/bin/imag-tag]: https://github.com/matthiasbeyer/imag/labels/part%2Fbin%2Fimag-tag +[search-part/bin/imag-view]: https://github.com/matthiasbeyer/imag/labels/part%2Fbin%2Fimag-view +[search-part/interface]: https://github.com/matthiasbeyer/imag/labels/part%2F_interface +[search-part/lib/imagcounter]: https://github.com/matthiasbeyer/imag/labels/part%2Flib%2Fimagcounter +[search-part/lib/imagentryfilter]: https://github.com/matthiasbeyer/imag/labels/part%2Flib%2Fimagentryfilter +[search-part/lib/imagentrylink]: https://github.com/matthiasbeyer/imag/labels/part%2Flib%2Fimagentrylink +[search-part/lib/imagentrylist]: https://github.com/matthiasbeyer/imag/labels/part%2Flib%2Fimagentrylist +[search-part/lib/imagentrymarkup]: https://github.com/matthiasbeyer/imag/labels/part%2Flib%2Fimagentrymarkup +[search-part/lib/imagentryprinter]: https://github.com/matthiasbeyer/imag/labels/part%2Flib%2Fimagentryprinter +[search-part/lib/imagentrytag]: https://github.com/matthiasbeyer/imag/labels/part%2Flib%2Fimagentrytag +[search-part/lib/imagentryview]: https://github.com/matthiasbeyer/imag/labels/part%2Flib%2Fimagentryview +[search-part/lib/imagnotes]: https://github.com/matthiasbeyer/imag/labels/part%2Flib%2Fimagnotes +[search-part/lib/imagrt]: https://github.com/matthiasbeyer/imag/labels/part%2Flib%2Fimagrt +[search-part/lib/imagstore]: https://github.com/matthiasbeyer/imag/labels/part%2Flib%2Fimagstore +[search-part/lib/imagstorestdhook]: https://github.com/matthiasbeyer/imag/labels/part%2Flib%2Fimagstorestdhook +[search-part/lib/imagutil]: https://github.com/matthiasbeyer/imag/labels/part%2Flib%2Fimagutil +[search-part/_new_binary]: https://github.com/matthiasbeyer/imag/labels/part%2F_new_binary +[search-part/_new_library]: https://github.com/matthiasbeyer/imag/labels/part%2F_new_library +[search-test/change]: https://github.com/matthiasbeyer/imag/labels/test%2Fchange +[search-test/missing]: https://github.com/matthiasbeyer/imag/labels/test%2Fmissing +[search-test/new]: https://github.com/matthiasbeyer/imag/labels/test%2Fnew From 344296487df6361eba2d8be079c6597aa81b5a4b Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sun, 15 May 2016 17:37:56 +0200 Subject: [PATCH 068/288] Add dependency: ansi_term = 0.7 --- libimagrt/Cargo.toml | 1 + libimagrt/src/lib.rs | 1 + 2 files changed, 2 insertions(+) diff --git a/libimagrt/Cargo.toml b/libimagrt/Cargo.toml index 6989ef69..485994b5 100644 --- a/libimagrt/Cargo.toml +++ b/libimagrt/Cargo.toml @@ -10,6 +10,7 @@ log = "0.3" xdg-basedir = "0.2.2" itertools = "0.4" tempfile = "2.1.1" +ansi_term = "0.7" [dependencies.libimagstore] path = "../libimagstore" diff --git a/libimagrt/src/lib.rs b/libimagrt/src/lib.rs index 2e3d307c..7c9e3f59 100644 --- a/libimagrt/src/lib.rs +++ b/libimagrt/src/lib.rs @@ -18,6 +18,7 @@ #[macro_use] extern crate itertools; #[cfg(unix)] extern crate xdg_basedir; extern crate tempfile; +extern crate ansi_term; extern crate clap; extern crate toml; From 376a23b8cee18be60c320a433ca7a7500e4317a8 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sun, 15 May 2016 17:38:02 +0200 Subject: [PATCH 069/288] Color log output Color as follows: * Debug output -> Cyan * Warning, errors -> Red, with the type (WARN; ERROR) red blinking * All other output yellow. --- libimagrt/src/logger.rs | 35 +++++++++++++++++++++++++++++------ 1 file changed, 29 insertions(+), 6 deletions(-) diff --git a/libimagrt/src/logger.rs b/libimagrt/src/logger.rs index 302d790a..e637163d 100644 --- a/libimagrt/src/logger.rs +++ b/libimagrt/src/logger.rs @@ -24,14 +24,37 @@ impl Log for ImagLogger { } fn log(&self, record: &LogRecord) { + use ansi_term::Colour::Red; + use ansi_term::Colour::Yellow; + use ansi_term::Colour::Cyan; + if self.enabled(record.metadata()) { // TODO: This is just simple logging. Maybe we can enhance this lateron - if record.metadata().level() == LogLevel::Debug { - let loc = record.location(); - writeln!(stderr(), "[imag][{: <5}][{}][{: >5}]: {}", - record.level(), loc.file(), loc.line(), record.args()).ok(); - } else { - writeln!(stderr(), "[imag][{: <5}]: {}", record.level(), record.args()).ok(); + let loc = record.location(); + match record.metadata().level() { + LogLevel::Debug => { + let lvl = Cyan.paint(format!("{}", record.level())); + let file = Cyan.paint(format!("{}", loc.file())); + let ln = Cyan.paint(format!("{}", loc.line())); + let args = Cyan.paint(format!("{}", record.args())); + + writeln!(stderr(), "[imag][{: <5}][{}][{: >5}]: {}", lvl, file, ln, args).ok(); + }, + LogLevel::Warn | LogLevel::Error => { + let lvl = Red.blink().paint(format!("{}", record.level())); + let args = Red.paint(format!("{}", record.args())); + + writeln!(stderr(), "[imag][{: <5}]: {}", lvl, args).ok(); + }, + LogLevel::Info => { + let lvl = Yellow.paint(format!("{}", record.level())); + let args = Yellow.paint(format!("{}", record.args())); + + writeln!(stderr(), "[imag][{: <5}]: {}", lvl, args).ok(); + }, + _ => { + writeln!(stderr(), "[imag][{: <5}]: {}", record.level(), record.args()).ok(); + }, } } } From 5dd0fa900c1a3495ffd72f0dc017b2dfaaa895b3 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sun, 15 May 2016 17:46:52 +0200 Subject: [PATCH 070/288] Add dependency: ansi_term = 0.7 --- libimagutil/Cargo.toml | 1 + libimagutil/src/lib.rs | 1 + 2 files changed, 2 insertions(+) diff --git a/libimagutil/Cargo.toml b/libimagutil/Cargo.toml index 96638623..efcbff44 100644 --- a/libimagutil/Cargo.toml +++ b/libimagutil/Cargo.toml @@ -7,4 +7,5 @@ authors = ["Matthias Beyer "] lazy_static = "0.1.15" log = "0.3" regex = "0.1" +ansi_term = "0.7" diff --git a/libimagutil/src/lib.rs b/libimagutil/src/lib.rs index e9894c0a..e0d7a3ce 100644 --- a/libimagutil/src/lib.rs +++ b/libimagutil/src/lib.rs @@ -16,6 +16,7 @@ #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; extern crate regex; +extern crate ansi_term; pub mod ismatch; pub mod key_value_split; From f22624302c5ab9abb6d88d75825d04ea0ca7a6b4 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sun, 15 May 2016 17:47:01 +0200 Subject: [PATCH 071/288] Make trace() output red --- libimagutil/src/trace.rs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/libimagutil/src/trace.rs b/libimagutil/src/trace.rs index 3a66bcb8..e04b292f 100644 --- a/libimagutil/src/trace.rs +++ b/libimagutil/src/trace.rs @@ -2,6 +2,8 @@ use std::error::Error; use std::io::Write; use std::io::stderr; +use ansi_term::Colour::Red; + /// Print an Error type and its cause recursively /// /// The error is printed with "Error NNNN :" as prefix, where "NNNN" is a number which increases @@ -29,8 +31,9 @@ pub fn trace_error(e: &Error) { /// Output is the same as for `trace_error()`, though there are only `max` levels printed. pub fn trace_error_maxdepth(e: &Error, max: u64) { let n = count_error_causes(e); - write!(stderr(), - "{}/{} Levels of errors will be printed\n", (if max > n { n } else { max }), n).ok(); + let msg = Red.blink().paint(format!("{}/{} Levels of errors will be printed\n", + (if max > n { n } else { max }), n)); + write!(stderr(), "{}", msg).ok(); print_trace_maxdepth(n, e, max); write!(stderr(), "").ok(); } @@ -55,7 +58,7 @@ fn print_trace_maxdepth(idx: u64, e: &Error, max: u64) -> Option<&Error> { } else { write!(stderr(), "\n").ok(); } - write!(stderr(), "ERROR[{:>4}]: {}", idx, e.description()).ok(); + write!(stderr(), "{}: {}", Red.paint(format!("ERROR[{:>4}]", idx)), e.description()).ok(); e.cause() } @@ -65,7 +68,7 @@ fn count_error_causes(e: &Error) -> u64 { } fn print_trace_dbg(idx: u64, e: &Error) { - debug!("ERROR[{:>4}]: {}", idx, e.description()); + debug!("{}: {}", Red.blink().paint(format!("ERROR[{:>4}]", idx)), e.description()); if e.cause().is_some() { print_trace_dbg(idx + 1, e.cause().unwrap()); } From cb855ae33546aa1ce99a8411645a226856d9c4e0 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sun, 15 May 2016 14:09:29 +0200 Subject: [PATCH 072/288] Initial import --- libimagerror/Cargo.toml | 6 ++++++ libimagerror/src/lib.rs | 6 ++++++ 2 files changed, 12 insertions(+) create mode 100644 libimagerror/Cargo.toml create mode 100644 libimagerror/src/lib.rs diff --git a/libimagerror/Cargo.toml b/libimagerror/Cargo.toml new file mode 100644 index 00000000..bd769698 --- /dev/null +++ b/libimagerror/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "libimagerror" +version = "0.1.0" +authors = ["Matthias Beyer "] + +[dependencies] diff --git a/libimagerror/src/lib.rs b/libimagerror/src/lib.rs new file mode 100644 index 00000000..cdfbe1aa --- /dev/null +++ b/libimagerror/src/lib.rs @@ -0,0 +1,6 @@ +#[cfg(test)] +mod tests { + #[test] + fn it_works() { + } +} From 2f03077abf0e0e048e7d088e0471fd027ae95328 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sun, 15 May 2016 16:00:51 +0200 Subject: [PATCH 073/288] Add error generator macro --- libimagerror/src/error_gen.rs | 113 ++++++++++++++++++++++++++++++++++ libimagerror/src/lib.rs | 7 +-- 2 files changed, 114 insertions(+), 6 deletions(-) create mode 100644 libimagerror/src/error_gen.rs diff --git a/libimagerror/src/error_gen.rs b/libimagerror/src/error_gen.rs new file mode 100644 index 00000000..471c6362 --- /dev/null +++ b/libimagerror/src/error_gen.rs @@ -0,0 +1,113 @@ +#[macro_export] +macro_rules! generate_error_types { + ( + $name: ident, + $kindname: ident, + $($kind:ident => $string:expr),* + ) => { + #[derive(Clone, Copy, Debug, PartialEq)] + pub enum $kindname { + $( $kind ),* + } + + impl Display for $kindname { + + fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> { + let s = match *self { + $( $kindname::$kind => $string ),* + }; + try!(write!(fmt, "{}", s)); + Ok(()) + } + + } + + #[derive(Debug)] + pub struct $name { + err_type: $kindname, + cause: Option>, + } + + impl $name { + + pub fn new(errtype: $kindname, cause: Option>) -> $name { + $name { + err_type: errtype, + cause: cause, + } + } + + pub fn err_type(&self) -> $kindname { + self.err_type + } + + } + + impl Display for $name { + + fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> { + try!(write!(fmt, "[{}]", self.err_type)); + Ok(()) + } + + } + + impl Error for $name { + + fn description(&self) -> &str { + match self.err_type { + $( $kindname::$kind => $string ),* + } + } + + fn cause(&self) -> Option<&Error> { + self.cause.as_ref().map(|e| &**e) + } + + } + + } +} + +#[cfg(test)] +mod test { + use std::error::Error; + use std::fmt::Error as FmtError; + use std::fmt::{Display, Formatter}; + + generate_error_types!(TestError, TestErrorKind, + TestErrorKindA => "testerrorkind a", + TestErrorKindB => "testerrorkind B"); + + #[test] + fn test_a() { + let kind = TestErrorKind::TestErrorKindA; + assert_eq!(String::from("testerrorkind a"), format!("{}", kind)); + + let e = TestError::new(kind, None); + assert_eq!(String::from("[testerrorkind a]"), format!("{}", e)); + } + + #[test] + fn test_b() { + let kind = TestErrorKind::TestErrorKindB; + assert_eq!(String::from("testerrorkind B"), format!("{}", kind)); + + let e = TestError::new(kind, None); + assert_eq!(String::from("[testerrorkind B]"), format!("{}", e)); + + } + + #[test] + fn test_ab() { + let kinda = TestErrorKind::TestErrorKindA; + let kindb = TestErrorKind::TestErrorKindB; + assert_eq!(String::from("testerrorkind a"), format!("{}", kinda)); + assert_eq!(String::from("testerrorkind B"), format!("{}", kindb)); + + let e = TestError::new(kinda, Some(Box::new(TestError::new(kindb, None)))); + assert_eq!(String::from("[testerrorkind a]"), format!("{}", e)); + assert_eq!(TestErrorKind::TestErrorKindA, e.err_type()); + assert_eq!(String::from("[testerrorkind B]"), format!("{}", e.cause().unwrap())); + } +} diff --git a/libimagerror/src/lib.rs b/libimagerror/src/lib.rs index cdfbe1aa..9f79f549 100644 --- a/libimagerror/src/lib.rs +++ b/libimagerror/src/lib.rs @@ -1,6 +1 @@ -#[cfg(test)] -mod tests { - #[test] - fn it_works() { - } -} +pub mod error_gen; From a69fd780589db82aad7756d579c523aabc08fd13 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sun, 15 May 2016 16:39:52 +0200 Subject: [PATCH 074/288] Add dependency: libimagerror --- libimagstore/Cargo.toml | 3 +++ libimagstore/src/lib.rs | 2 ++ 2 files changed, 5 insertions(+) diff --git a/libimagstore/Cargo.toml b/libimagstore/Cargo.toml index 7c0fbf49..72d068d5 100644 --- a/libimagstore/Cargo.toml +++ b/libimagstore/Cargo.toml @@ -15,6 +15,9 @@ version = "2.0.1" crossbeam = "0.2.8" walkdir = "0.1.5" +[dependencies.libimagerror] +path = "../libimagerror" + [dev-dependencies] tempdir = "0.3.4" env_logger = "0.3" diff --git a/libimagstore/src/lib.rs b/libimagstore/src/lib.rs index e7efa3be..89657283 100644 --- a/libimagstore/src/lib.rs +++ b/libimagstore/src/lib.rs @@ -24,6 +24,8 @@ extern crate semver; extern crate crossbeam; extern crate walkdir; +#[macro_use] extern crate libimagerror; + pub mod storeid; pub mod error; pub mod hook; From 627fa7de46701a1848ffe8c464cc7dc4a1618b0c Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sun, 15 May 2016 16:40:06 +0200 Subject: [PATCH 075/288] Replace error code with macro for code generation --- libimagstore/src/error.rs | 228 +++++++------------------------------- 1 file changed, 37 insertions(+), 191 deletions(-) diff --git a/libimagstore/src/error.rs b/libimagstore/src/error.rs index 1976622d..ad36963e 100644 --- a/libimagstore/src/error.rs +++ b/libimagstore/src/error.rs @@ -1,138 +1,45 @@ use std::error::Error; use std::fmt::Error as FmtError; -use std::fmt::{Debug, Display, Formatter}; -use std::fmt; +use std::fmt::{Display, Formatter}; use std::convert::From; -/** - * Kind of store error - */ -#[derive(Clone, Copy, Debug, PartialEq)] -pub enum StoreErrorKind { - ConfigurationError, - FileError, - IdLocked, - IdNotFound, - OutOfMemory, - FileNotFound, - FileNotCreated, - IoError, - StorePathExists, - StorePathCreate, - LockError, - LockPoisoned, - EntryAlreadyBorrowed, - EntryAlreadyExists, - MalformedEntry, - HeaderPathSyntaxError, - HeaderPathTypeFailure, - HeaderKeyNotFound, - HeaderTypeFailure, - HookRegisterError, - AspectNameNotFoundError, - HookExecutionError, - PreHookExecuteError, - PostHookExecuteError, - StorePathLacksVersion, - GlobError, - EncodingError, - // maybe more -} +generate_error_types!(StoreError, StoreErrorKind, + ConfigurationError => "Store Configuration Error", + FileError => "File Error", + IoError => "IO Error", + IdLocked => "ID locked", + IdNotFound => "ID not found", + OutOfMemory => "Out of Memory", + FileNotFound => "File corresponding to ID not found", + FileNotCreated => "File corresponding to ID could not be created", + StorePathExists => "Store path exists", + StorePathCreate => "Store path create", + LockError => "Error locking datastructure", + LockPoisoned => "The internal Store Lock has been poisoned", + EntryAlreadyBorrowed => "Entry is already borrowed", + EntryAlreadyExists => "Entry already exists", + MalformedEntry => "Entry has invalid formatting, missing header", + HeaderPathSyntaxError => "Syntax error in accessor string", + HeaderPathTypeFailure => "Header has wrong type for path", + HeaderKeyNotFound => "Header Key not found", + HeaderTypeFailure => "Header type is wrong", + HookRegisterError => "Hook register error", + AspectNameNotFoundError => "Aspect name not found", + HookExecutionError => "Hook execution error", + PreHookExecuteError => "Pre-Hook execution error", + PostHookExecuteError => "Post-Hook execution error", + StorePathLacksVersion => "The supplied store path has no version part", + GlobError => "glob() error", + EncodingError => "Encoding error" +); -fn store_error_type_as_str(e: &StoreErrorKind) -> &'static str { - match *e { - StoreErrorKind::ConfigurationError => "Store Configuration Error", - StoreErrorKind::FileError | - StoreErrorKind::IoError => "File Error", - StoreErrorKind::IdLocked => "ID locked", - StoreErrorKind::IdNotFound => "ID not found", - StoreErrorKind::OutOfMemory => "Out of Memory", - StoreErrorKind::FileNotFound => "File corresponding to ID not found", - StoreErrorKind::FileNotCreated => "File corresponding to ID could not be created", - StoreErrorKind::StorePathExists | - StoreErrorKind::StorePathCreate => "Store path create", - StoreErrorKind::LockError => "Error locking datastructure", - StoreErrorKind::LockPoisoned - => "The internal Store Lock has been poisoned", - StoreErrorKind::EntryAlreadyBorrowed => "Entry is already borrowed", - StoreErrorKind::EntryAlreadyExists => "Entry already exists", - StoreErrorKind::MalformedEntry => "Entry has invalid formatting, missing header", - StoreErrorKind::HeaderPathSyntaxError => "Syntax error in accessor string", - StoreErrorKind::HeaderPathTypeFailure => "Header has wrong type for path", - StoreErrorKind::HeaderKeyNotFound => "Header Key not found", - StoreErrorKind::HeaderTypeFailure => "Header type is wrong", - StoreErrorKind::HookRegisterError => "Hook register error", - StoreErrorKind::AspectNameNotFoundError => "Aspect name not found", - StoreErrorKind::HookExecutionError => "Hook execution error", - StoreErrorKind::PreHookExecuteError => "Pre-Hook execution error", - StoreErrorKind::PostHookExecuteError => "Post-Hook execution error", - StoreErrorKind::StorePathLacksVersion => "The supplied store path has no version part", - StoreErrorKind::GlobError => "glob() error", - StoreErrorKind::EncodingError => "Encoding error", - } -} - -impl Display for StoreErrorKind { - - fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> { - try!(write!(fmt, "{}", store_error_type_as_str(self))); - Ok(()) - } - -} - -/** - * Store error type - */ -#[derive(Debug)] -pub struct StoreError { - err_type: StoreErrorKind, - cause: Option>, -} - -impl StoreError { - - /** - * Build a new StoreError from an StoreErrorKind, optionally with cause - */ - pub fn new(errtype: StoreErrorKind, cause: Option>) - -> StoreError - { - StoreError { - err_type: errtype, - cause: cause, - } - } - - /** - * Get the error type of this StoreError - */ - pub fn err_type(&self) -> StoreErrorKind { - self.err_type - } - -} - -impl Display for StoreError { - - fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> { - try!(write!(fmt, "[{}]", store_error_type_as_str(&self.err_type))); - Ok(()) - } - -} - -impl Error for StoreError { - - fn description(&self) -> &str { - store_error_type_as_str(&self.err_type) - } - - fn cause(&self) -> Option<&Error> { - self.cause.as_ref().map(|e| &**e) - } - -} +generate_error_types!(ParserError, ParserErrorKind, + TOMLParserErrors => "Several TOML-Parser-Errors", + MissingMainSection => "Missing main section", + MissingVersionInfo => "Missing version information in main section", + NonTableInBaseTable => "A non-table was found in the base table", + HeaderInconsistency => "The header is inconsistent" +); impl From for StoreError { fn from(ps: ParserError) -> StoreError { @@ -152,64 +59,3 @@ impl From<::std::io::Error> for StoreError { } } -#[derive(Clone)] -pub enum ParserErrorKind { - TOMLParserErrors, - MissingMainSection, - MissingVersionInfo, - NonTableInBaseTable, - HeaderInconsistency, -} - -pub struct ParserError { - kind: ParserErrorKind, - cause: Option>, -} - -impl ParserError { - - pub fn new(k: ParserErrorKind, cause: Option>) -> ParserError { - ParserError { - kind: k, - cause: cause, - } - } - -} - -impl Debug for ParserError { - - fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { - try!(write!(f, "{:?}", self.description())); - Ok(()) - } - -} - -impl Display for ParserError { - - fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { - try!(write!(f, "{}", self.description())); - Ok(()) - } - -} - -impl Error for ParserError { - - fn description(&self) -> &str { - match self.kind { - ParserErrorKind::TOMLParserErrors => "Several TOML-Parser-Errors", - ParserErrorKind::MissingMainSection => "Missing main section", - ParserErrorKind::MissingVersionInfo => "Missing version information in main section", - ParserErrorKind::NonTableInBaseTable => "A non-table was found in the base table", - ParserErrorKind::HeaderInconsistency => "The header is inconsistent", - } - } - - fn cause(&self) -> Option<&Error> { - self.cause.as_ref().map(|e| &**e) - } - -} - From 42f7e086a32d805f2965058b08cbdf303a331cb5 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sun, 15 May 2016 16:41:25 +0200 Subject: [PATCH 076/288] Replace error code with macro for code generation --- libimagstore/src/hook/error.rs | 82 ++-------------------------------- 1 file changed, 4 insertions(+), 78 deletions(-) diff --git a/libimagstore/src/hook/error.rs b/libimagstore/src/hook/error.rs index b9abd4fe..ec06dd98 100644 --- a/libimagstore/src/hook/error.rs +++ b/libimagstore/src/hook/error.rs @@ -3,14 +3,10 @@ use std::fmt::Error as FmtError; use std::fmt::{Display, Formatter}; use std::convert::Into; -/** - * Kind of error - */ -#[derive(Clone, Copy, Debug)] -pub enum HookErrorKind { - HookExecutionError, - AccessTypeViolation, -} +generate_error_types!(HookError, HookErrorKind, + HookExecutionError => "Hook exec error", + AccessTypeViolation => "Hook access type violation" +); pub trait IntoHookError { fn into_hookerror(self) -> HookError; @@ -33,73 +29,3 @@ impl Into for (HookErrorKind, Box) { } -fn hook_error_type_as_str(e: &HookErrorKind) -> &'static str { - match *e { - HookErrorKind::HookExecutionError => "Hook exec error", - HookErrorKind::AccessTypeViolation => "Hook access type violation", - } -} - -impl Display for HookErrorKind { - - fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> { - try!(write!(fmt, "{}", hook_error_type_as_str(self))); - Ok(()) - } - -} - -/** - * Error type - */ -#[derive(Debug)] -pub struct HookError { - err_type: HookErrorKind, - cause: Option>, -} - -impl HookError { - - /** - * Build a new HookError from an HookErrorKind, optionally with cause - */ - pub fn new(errtype: HookErrorKind, cause: Option>) - -> HookError - { - HookError { - err_type: errtype, - cause: cause, - } - } - - /** - * Get the error type of this HookError - */ - pub fn err_type(&self) -> HookErrorKind { - self.err_type - } - -} - -impl Display for HookError { - - fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> { - try!(write!(fmt, "[{}]", hook_error_type_as_str(&self.err_type))); - Ok(()) - } - -} - -impl Error for HookError { - - fn description(&self) -> &str { - hook_error_type_as_str(&self.err_type) - } - - fn cause(&self) -> Option<&Error> { - self.cause.as_ref().map(|e| &**e) - } - -} - - From 60bf3c68a7ab943f06b30f75cd380395930d51af Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sun, 15 May 2016 16:53:31 +0200 Subject: [PATCH 077/288] imag-store: Replace error code with code generator macro --- imag-store/Cargo.toml | 3 ++ imag-store/src/error.rs | 74 +++-------------------------------------- imag-store/src/main.rs | 1 + 3 files changed, 8 insertions(+), 70 deletions(-) diff --git a/imag-store/Cargo.toml b/imag-store/Cargo.toml index 0deba5a0..6c244322 100644 --- a/imag-store/Cargo.toml +++ b/imag-store/Cargo.toml @@ -19,3 +19,6 @@ path = "../libimagrt" [dependencies.libimagutil] path = "../libimagutil" +[dependencies.libimagerror] +path = "../libimagerror" + diff --git a/imag-store/src/error.rs b/imag-store/src/error.rs index 30c9c8b5..472070f2 100644 --- a/imag-store/src/error.rs +++ b/imag-store/src/error.rs @@ -1,75 +1,9 @@ use std::error::Error; use std::fmt::Error as FmtError; -use std::clone::Clone; use std::fmt::{Display, Formatter}; -#[derive(Clone, Copy, Debug, PartialEq)] -/// Kind of store error -pub enum StoreErrorKind { - BackendError, - NoCommandlineCall, - // maybe more -} - -fn store_error_type_as_str(e: &StoreErrorKind) -> &'static str { - match *e { - StoreErrorKind::BackendError => "Backend Error", - StoreErrorKind::NoCommandlineCall => "No commandline call", - } -} - -impl Display for StoreErrorKind { - - fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> { - try!(write!(fmt, "{}", store_error_type_as_str(self))); - Ok(()) - } - -} - -#[derive(Debug)] -pub struct StoreError { - err_type: StoreErrorKind, - cause: Option>, -} - -impl StoreError { - - ///Build a new StoreError from an StoreErrorKind, optionally with cause - pub fn new(errtype: StoreErrorKind, cause: Option>) - -> StoreError - { - StoreError { - err_type: errtype, - cause: cause, - } - } - - /// Get the error type of this StoreError - pub fn err_type(&self) -> StoreErrorKind { - self.err_type - } - -} - -impl Display for StoreError { - - fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> { - try!(write!(fmt, "[{}]", store_error_type_as_str(&self.err_type.clone()))); - Ok(()) - } - -} - -impl Error for StoreError { - - fn description(&self) -> &str { - store_error_type_as_str(&self.err_type) - } - - fn cause(&self) -> Option<&Error> { - self.cause.as_ref().map(|e| &**e) - } - -} +generate_error_types!(StoreError, StoreErrorKind, + BackendError => "Backend Error", + NoCommandlineCall => "No commandline call" +); diff --git a/imag-store/src/main.rs b/imag-store/src/main.rs index a1e9e09a..fd0a2c4d 100644 --- a/imag-store/src/main.rs +++ b/imag-store/src/main.rs @@ -22,6 +22,7 @@ extern crate toml; extern crate libimagrt; extern crate libimagstore; extern crate libimagutil; +#[macro_use] extern crate libimagerror; use libimagrt::runtime::Runtime; use std::process::exit; From 9140c36301dc8c1c6792b8806058b40406d03982 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sun, 15 May 2016 16:53:31 +0200 Subject: [PATCH 078/288] imag-view: Replace error code with code generator macro --- imag-view/Cargo.toml | 3 ++ imag-view/src/error.rs | 87 +++--------------------------------------- imag-view/src/main.rs | 1 + 3 files changed, 10 insertions(+), 81 deletions(-) diff --git a/imag-view/Cargo.toml b/imag-view/Cargo.toml index b3a52460..7c7b3d55 100644 --- a/imag-view/Cargo.toml +++ b/imag-view/Cargo.toml @@ -21,3 +21,6 @@ path = "../libimagrt" [dependencies.libimagutil] path = "../libimagutil" +[dependencies.libimagerror] +path = "../libimagerror" + diff --git a/imag-view/src/error.rs b/imag-view/src/error.rs index 7a1ede78..64aa071d 100644 --- a/imag-view/src/error.rs +++ b/imag-view/src/error.rs @@ -2,85 +2,10 @@ use std::error::Error; use std::fmt::Error as FmtError; use std::fmt::{Display, Formatter}; -/** - * Kind of store error - */ -#[derive(Clone, Copy, Debug, PartialEq)] -pub enum ViewErrorKind { - StoreError, - NoVersion, - PatternError, - GlobBuildError, -} - -fn view_error_type_as_str(e: &ViewErrorKind) -> &'static str { - match *e { - ViewErrorKind::StoreError => "Store error", - ViewErrorKind::NoVersion => "No version specified", - ViewErrorKind::PatternError => "Error in Pattern", - ViewErrorKind::GlobBuildError => "Could not build glob() Argument", - } -} - -impl Display for ViewErrorKind { - - fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> { - try!(write!(fmt, "{}", view_error_type_as_str(self))); - Ok(()) - } - -} - -/** - * View error type - */ -#[derive(Debug)] -pub struct ViewError { - err_type: ViewErrorKind, - cause: Option>, -} - -impl ViewError { - - /** - * Build a new ViewError from an ViewErrorKind, optionally with cause - */ - pub fn new(errtype: ViewErrorKind, cause: Option>) - -> ViewError - { - ViewError { - err_type: errtype, - cause: cause, - } - } - - /** - * Get the error type of this ViewError - */ - pub fn err_type(&self) -> ViewErrorKind { - self.err_type - } - -} - -impl Display for ViewError { - - fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> { - try!(write!(fmt, "[{}]", view_error_type_as_str(&self.err_type))); - Ok(()) - } - -} - -impl Error for ViewError { - - fn description(&self) -> &str { - view_error_type_as_str(&self.err_type) - } - - fn cause(&self) -> Option<&Error> { - self.cause.as_ref().map(|e| &**e) - } - -} +generate_error_types!(ViewError, ViewErrorKind, + StoreError => "Store error", + NoVersion => "No version specified", + PatternError => "Error in Pattern", + GlobBuildError => "Could not build glob() Argument" +); diff --git a/imag-view/src/main.rs b/imag-view/src/main.rs index 100d9aab..0efc25c8 100644 --- a/imag-view/src/main.rs +++ b/imag-view/src/main.rs @@ -23,6 +23,7 @@ extern crate toml; extern crate libimagrt; extern crate libimagstore; extern crate libimagutil; +#[macro_use] extern crate libimagerror; use std::result::Result as RResult; use std::process::exit; From 8602d5855a1b9b661516bc93db69850605b0253e Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sun, 15 May 2016 16:53:31 +0200 Subject: [PATCH 079/288] libimagcounter: Replace error code with code generator macro --- libimagcounter/Cargo.toml | 3 ++ libimagcounter/src/error.rs | 87 +++---------------------------------- libimagcounter/src/lib.rs | 1 + 3 files changed, 10 insertions(+), 81 deletions(-) diff --git a/libimagcounter/Cargo.toml b/libimagcounter/Cargo.toml index 8d880182..da194678 100644 --- a/libimagcounter/Cargo.toml +++ b/libimagcounter/Cargo.toml @@ -11,3 +11,6 @@ semver = "0.2" [dependencies.libimagstore] path = "../libimagstore" +[dependencies.libimagerror] +path = "../libimagerror" + diff --git a/libimagcounter/src/error.rs b/libimagcounter/src/error.rs index 1aa347a6..f2e11eeb 100644 --- a/libimagcounter/src/error.rs +++ b/libimagcounter/src/error.rs @@ -2,85 +2,10 @@ use std::error::Error; use std::fmt::Error as FmtError; use std::fmt::{Display, Formatter}; -/** - * Kind of error - */ -#[derive(Clone, Copy, Debug, PartialEq)] -pub enum CounterErrorKind { - StoreReadError, - StoreWriteError, - HeaderTypeError, - HeaderFieldMissingError, -} - -fn counter_error_type_as_str(e: &CounterErrorKind) -> &'static str { - match *e { - CounterErrorKind::StoreReadError => "Store read error", - CounterErrorKind::StoreWriteError => "Store write error", - CounterErrorKind::HeaderTypeError => "Header type error", - CounterErrorKind::HeaderFieldMissingError => "Header field missing error", - } -} - -impl Display for CounterErrorKind { - - fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> { - try!(write!(fmt, "{}", counter_error_type_as_str(self))); - Ok(()) - } - -} - -/** - * Store error type - */ -#[derive(Debug)] -pub struct CounterError { - err_type: CounterErrorKind, - cause: Option>, -} - -impl CounterError { - - /** - * Build a new CounterError from an CounterErrorKind, optionally with cause - */ - pub fn new(errtype: CounterErrorKind, cause: Option>) - -> CounterError - { - CounterError { - err_type: errtype, - cause: cause, - } - } - - /** - * Get the error type of this CounterError - */ - pub fn err_type(&self) -> CounterErrorKind { - self.err_type - } - -} - -impl Display for CounterError { - - fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> { - try!(write!(fmt, "[{}]", counter_error_type_as_str(&self.err_type))); - Ok(()) - } - -} - -impl Error for CounterError { - - fn description(&self) -> &str { - counter_error_type_as_str(&self.err_type) - } - - fn cause(&self) -> Option<&Error> { - self.cause.as_ref().map(|e| &**e) - } - -} +generate_error_types!(CounterError, CounterErrorKind, + StoreReadError => "Store read error", + StoreWriteError => "Store write error", + HeaderTypeError => "Header type error", + HeaderFieldMissingError => "Header field missing error" +); diff --git a/libimagcounter/src/lib.rs b/libimagcounter/src/lib.rs index 77033170..0426384d 100644 --- a/libimagcounter/src/lib.rs +++ b/libimagcounter/src/lib.rs @@ -17,6 +17,7 @@ extern crate toml; #[macro_use] extern crate semver; #[macro_use] extern crate libimagstore; +#[macro_use] extern crate libimagerror; module_entry_path_mod!("counter", "0.1.0"); From 6850146e4286df3529e291eec129b92ebf6a02fb Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sun, 15 May 2016 16:53:31 +0200 Subject: [PATCH 080/288] libimagentrylink: Replace error code with code generator macro --- libimagentrylink/Cargo.toml | 3 ++ libimagentrylink/src/error.rs | 95 ++++------------------------------- libimagentrylink/src/lib.rs | 1 + 3 files changed, 14 insertions(+), 85 deletions(-) diff --git a/libimagentrylink/Cargo.toml b/libimagentrylink/Cargo.toml index 7ac8457e..f14869be 100644 --- a/libimagentrylink/Cargo.toml +++ b/libimagentrylink/Cargo.toml @@ -14,3 +14,6 @@ rust-crypto = "0.2.35" [dependencies.libimagstore] path = "../libimagstore" +[dependencies.libimagerror] +path = "../libimagerror" + diff --git a/libimagentrylink/src/error.rs b/libimagentrylink/src/error.rs index a26e3d58..b587b0ef 100644 --- a/libimagentrylink/src/error.rs +++ b/libimagentrylink/src/error.rs @@ -2,89 +2,14 @@ use std::error::Error; use std::fmt::Error as FmtError; use std::fmt::{Display, Formatter}; -#[derive(Clone, Copy, Debug, PartialEq)] -pub enum LinkErrorKind { - EntryHeaderReadError, - EntryHeaderWriteError, - ExistingLinkTypeWrong, - LinkTargetDoesNotExist, - InternalConversionError, - InvalidUri, - StoreReadError, - StoreWriteError, -} +generate_error_types!(LinkError, LinkErrorKind, + EntryHeaderReadError => "Error while reading an entry header", + EntryHeaderWriteError => "Error while writing an entry header", + ExistingLinkTypeWrong => "Existing link entry has wrong type", + LinkTargetDoesNotExist => "Link target does not exist in the store", + InternalConversionError => "Error while converting values internally", + InvalidUri => "URI is not valid", + StoreReadError => "Store read error", + StoreWriteError => "Store write error" +); -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", - - LinkErrorKind::StoreReadError - => "Store read error", - - LinkErrorKind::StoreWriteError - => "Store write error", - } -} - -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>, -} - -impl LinkError { - - pub fn new(errtype: LinkErrorKind, cause: Option>) -> 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) - } - -} diff --git a/libimagentrylink/src/lib.rs b/libimagentrylink/src/lib.rs index 448bb853..e04b6bf4 100644 --- a/libimagentrylink/src/lib.rs +++ b/libimagentrylink/src/lib.rs @@ -20,6 +20,7 @@ extern crate url; extern crate crypto; #[macro_use] extern crate libimagstore; +#[macro_use] extern crate libimagerror; module_entry_path_mod!("links", "0.1.0"); From 20ac5247f1be9cb65fd511e4a3ce693a45dd8a8a Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sun, 15 May 2016 16:53:31 +0200 Subject: [PATCH 081/288] libimagentrylist: Replace error code with code generator macro --- libimagentrylist/Cargo.toml | 3 ++ libimagentrylist/src/error.rs | 85 +++-------------------------------- libimagentrylist/src/lib.rs | 1 + 3 files changed, 10 insertions(+), 79 deletions(-) diff --git a/libimagentrylist/Cargo.toml b/libimagentrylist/Cargo.toml index e8905dfe..462331c7 100644 --- a/libimagentrylist/Cargo.toml +++ b/libimagentrylist/Cargo.toml @@ -11,3 +11,6 @@ toml = "0.1.25" [dependencies.libimagstore] path = "../libimagstore" +[dependencies.libimagerror] +path = "../libimagerror" + diff --git a/libimagentrylist/src/error.rs b/libimagentrylist/src/error.rs index 24051753..15640042 100644 --- a/libimagentrylist/src/error.rs +++ b/libimagentrylist/src/error.rs @@ -2,83 +2,10 @@ use std::error::Error; use std::fmt::Error as FmtError; use std::fmt::{Display, Formatter}; -/** - * Kind of error - */ -#[derive(Clone, Copy, Debug, PartialEq)] -pub enum ListErrorKind { - FormatError, - EntryError, - IterationError, - CLIError, -} - -fn counter_error_type_as_str(err: &ListErrorKind) -> &'static str{ - match *err { - ListErrorKind::FormatError => "FormatError", - ListErrorKind::EntryError => "EntryError", - ListErrorKind::IterationError => "IterationError", - ListErrorKind::CLIError => "No CLI subcommand for listing entries", - } -} - -impl Display for ListErrorKind { - - fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> { - try!(write!(fmt, "{}", counter_error_type_as_str(self))); - Ok(()) - } - -} - -/** - * Store error type - */ -#[derive(Debug)] -pub struct ListError { - err_type: ListErrorKind, - cause: Option>, -} - -impl ListError { - - /** - * Build a new ListError from an ListErrorKind, optionally with cause - */ - pub fn new(errtype: ListErrorKind, cause: Option>) -> ListError { - ListError { - err_type: errtype, - cause: cause, - } - } - - /** - * Get the error type of this ListError - */ - pub fn err_type(&self) -> ListErrorKind { - self.err_type - } - -} - -impl Display for ListError { - - fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> { - try!(write!(fmt, "[{}]", counter_error_type_as_str(&self.err_type))); - Ok(()) - } - -} - -impl Error for ListError { - - fn description(&self) -> &str { - counter_error_type_as_str(&self.err_type) - } - - fn cause(&self) -> Option<&Error> { - self.cause.as_ref().map(|e| &**e) - } - -} +generate_error_types!(ListError, ListErrorKind, + FormatError => "FormatError", + EntryError => "EntryError", + IterationError => "IterationError", + CLIError => "No CLI subcommand for listing entries" +); diff --git a/libimagentrylist/src/lib.rs b/libimagentrylist/src/lib.rs index b364e4d9..082b6fa3 100644 --- a/libimagentrylist/src/lib.rs +++ b/libimagentrylist/src/lib.rs @@ -19,6 +19,7 @@ extern crate clap; extern crate toml; extern crate libimagstore; +#[macro_use] extern crate libimagerror; pub mod cli; pub mod error; From 5c7412ebc6cf48b9814085b83987d6d2086c8c13 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sun, 15 May 2016 16:53:31 +0200 Subject: [PATCH 082/288] libimagentrytag: Replace error code with code generator macro --- libimagentrytag/Cargo.toml | 3 ++ libimagentrytag/src/error.rs | 69 ++++-------------------------------- libimagentrytag/src/lib.rs | 1 + 3 files changed, 10 insertions(+), 63 deletions(-) diff --git a/libimagentrytag/Cargo.toml b/libimagentrytag/Cargo.toml index db2df486..2a4e1ed2 100644 --- a/libimagentrytag/Cargo.toml +++ b/libimagentrytag/Cargo.toml @@ -13,3 +13,6 @@ itertools = "0.4" [dependencies.libimagstore] path = "../libimagstore" +[dependencies.libimagerror] +path = "../libimagerror" + diff --git a/libimagentrytag/src/error.rs b/libimagentrytag/src/error.rs index 19d4a92e..5be68b90 100644 --- a/libimagentrytag/src/error.rs +++ b/libimagentrytag/src/error.rs @@ -2,67 +2,10 @@ use std::error::Error; use std::fmt::Error as FmtError; use std::fmt::{Display, Formatter}; -#[derive(Clone, Copy, Debug, PartialEq)] -pub enum TagErrorKind { - TagTypeError, - HeaderReadError, - HeaderWriteError, - NotATag, -} - -fn tag_error_type_as_str(e: &TagErrorKind) -> &'static str { - match *e { - TagErrorKind::TagTypeError => "Entry Header Tag Type wrong", - TagErrorKind::HeaderReadError => "Error while reading entry header", - TagErrorKind::HeaderWriteError => "Error while writing entry header", - TagErrorKind::NotATag => "String is not a tag", - } -} - -impl Display for TagErrorKind { - - fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> { - try!(write!(fmt, "{}", tag_error_type_as_str(self))); - Ok(()) - } - -} - -#[derive(Debug)] -pub struct TagError { - kind: TagErrorKind, - cause: Option>, -} - -impl TagError { - - pub fn new(errtype: TagErrorKind, cause: Option>) -> TagError { - TagError { - kind: errtype, - cause: cause, - } - } - -} - -impl Display for TagError { - - fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> { - try!(write!(fmt, "[{}]", tag_error_type_as_str(&self.kind))); - Ok(()) - } - -} - -impl Error for TagError { - - fn description(&self) -> &str { - tag_error_type_as_str(&self.kind) - } - - fn cause(&self) -> Option<&Error> { - self.cause.as_ref().map(|e| &**e) - } - -} +generate_error_types!(TagError, TagErrorKind, + TagTypeError => "Entry Header Tag Type wrong", + HeaderReadError => "Error while reading entry header", + HeaderWriteError => "Error while writing entry header", + NotATag => "String is not a tag" +); diff --git a/libimagentrytag/src/lib.rs b/libimagentrytag/src/lib.rs index d90f5fa5..232de3b3 100644 --- a/libimagentrytag/src/lib.rs +++ b/libimagentrytag/src/lib.rs @@ -19,6 +19,7 @@ extern crate regex; extern crate toml; extern crate libimagstore; +#[macro_use] extern crate libimagerror; pub mod error; pub mod exec; From ea98cc41da8e6d8ac843265f70c2e4345c42920e Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sun, 15 May 2016 16:53:31 +0200 Subject: [PATCH 083/288] libimagentryview: Replace error code with code generator macro --- libimagentryview/Cargo.toml | 3 ++ libimagentryview/src/error.rs | 77 ++--------------------------------- libimagentryview/src/lib.rs | 1 + 3 files changed, 7 insertions(+), 74 deletions(-) diff --git a/libimagentryview/Cargo.toml b/libimagentryview/Cargo.toml index e9711be0..7c0124a3 100644 --- a/libimagentryview/Cargo.toml +++ b/libimagentryview/Cargo.toml @@ -8,3 +8,6 @@ authors = ["Matthias Beyer "] [dependencies.libimagstore] path = "../libimagstore" +[dependencies.libimagerror] +path = "../libimagerror" + diff --git a/libimagentryview/src/error.rs b/libimagentryview/src/error.rs index 4bc8af54..32982342 100644 --- a/libimagentryview/src/error.rs +++ b/libimagentryview/src/error.rs @@ -2,78 +2,7 @@ use std::error::Error; use std::fmt::Error as FmtError; use std::fmt::{Display, Formatter}; -/** - * Kind of error - */ -#[derive(Clone, Copy, Debug, PartialEq)] -pub enum ViewErrorKind { -} - -fn counter_error_type_as_str(e: &ViewErrorKind) -> &'static str { - match e { - _ => "", - } -} - -impl Display for ViewErrorKind { - - fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> { - try!(write!(fmt, "{}", counter_error_type_as_str(self))); - Ok(()) - } - -} - -/** - * Store error type - */ -#[derive(Debug)] -pub struct ViewError { - err_type: ViewErrorKind, - cause: Option>, -} - -impl ViewError { - - /** - * Build a new ViewError from an ViewErrorKind, optionally with cause - */ - pub fn new(errtype: ViewErrorKind, cause: Option>) - -> ViewError - { - ViewError { - err_type: errtype, - cause: cause, - } - } - - /** - * Get the error type of this ViewError - */ - pub fn err_type(&self) -> ViewErrorKind { - self.err_type - } - -} - -impl Display for ViewError { - - fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> { - try!(write!(fmt, "[{}]", counter_error_type_as_str(&self.err_type))); - Ok(()) - } - -} - -impl Error for ViewError { - - fn description(&self) -> &str { - counter_error_type_as_str(&self.err_type) - } - - fn cause(&self) -> Option<&Error> { - self.cause.as_ref().map(|e| &**e) - } - -} +generate_error_types!(ViewError, ViewErrorKind, + Unknown => "Unknown view error" +); diff --git a/libimagentryview/src/lib.rs b/libimagentryview/src/lib.rs index 73833b7d..950332c5 100644 --- a/libimagentryview/src/lib.rs +++ b/libimagentryview/src/lib.rs @@ -15,6 +15,7 @@ )] extern crate libimagstore; +#[macro_use] extern crate libimagerror; pub mod error; pub mod builtin; From 841d26fdd0c848359a23e3bd73b72ab73f32d868 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sun, 15 May 2016 16:53:31 +0200 Subject: [PATCH 084/288] libimaginteraction: Replace error code with code generator macro --- libimaginteraction/Cargo.toml | 3 ++ libimaginteraction/src/error.rs | 75 ++------------------------------- libimaginteraction/src/lib.rs | 1 + 3 files changed, 7 insertions(+), 72 deletions(-) diff --git a/libimaginteraction/Cargo.toml b/libimaginteraction/Cargo.toml index e0bea398..1ee8e63f 100644 --- a/libimaginteraction/Cargo.toml +++ b/libimaginteraction/Cargo.toml @@ -20,3 +20,6 @@ path = "../libimagentryfilter" [dependencies.libimagutil] path = "../libimagutil" +[dependencies.libimagerror] +path = "../libimagerror" + diff --git a/libimaginteraction/src/error.rs b/libimaginteraction/src/error.rs index ed7d974e..a85c9b25 100644 --- a/libimaginteraction/src/error.rs +++ b/libimaginteraction/src/error.rs @@ -2,76 +2,7 @@ use std::error::Error; use std::fmt::Error as FmtError; use std::fmt::{Display, Formatter}; -/** - * Kind of error - */ -#[derive(Clone, Copy, Debug, PartialEq)] -pub enum InteractionErrorKind { - Unknown -} - -fn interaction_error_type_as_str(e: &InteractionErrorKind) -> &'static str { - match *e { - InteractionErrorKind::Unknown => "Unknown Error", - } -} - -impl Display for InteractionErrorKind { - - fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> { - try!(write!(fmt, "{}", interaction_error_type_as_str(self))); - Ok(()) - } - -} - -#[derive(Debug)] -pub struct InteractionError { - err_type: InteractionErrorKind, - cause: Option>, -} - -impl InteractionError { - - /** - * Build a new InteractionError from an InteractionErrorKind, optionally with cause - */ - pub fn new(errtype: InteractionErrorKind, cause: Option>) - -> InteractionError - { - InteractionError { - err_type: errtype, - cause: cause, - } - } - - /** - * Get the error type of this InteractionError - */ - pub fn err_type(&self) -> InteractionErrorKind { - self.err_type - } - -} - -impl Display for InteractionError { - - fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> { - try!(write!(fmt, "[{}]", interaction_error_type_as_str(&self.err_type))); - Ok(()) - } - -} - -impl Error for InteractionError { - - fn description(&self) -> &str { - interaction_error_type_as_str(&self.err_type) - } - - fn cause(&self) -> Option<&Error> { - self.cause.as_ref().map(|e| &**e) - } - -} +generate_error_types!(InteractionError, InteractionErrorKind, + Unknown => "Unknown Error" +); diff --git a/libimaginteraction/src/lib.rs b/libimaginteraction/src/lib.rs index ff0fff06..3600b942 100644 --- a/libimaginteraction/src/lib.rs +++ b/libimaginteraction/src/lib.rs @@ -8,6 +8,7 @@ extern crate regex; extern crate libimagentryfilter; extern crate libimagstore; #[macro_use] extern crate libimagutil; +#[macro_use] extern crate libimagerror; pub mod ask; pub mod error; From c730cce83baeb49cb90346456ccc2a09db675d75 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sun, 15 May 2016 16:53:31 +0200 Subject: [PATCH 085/288] libimagnotes: Replace error code with code generator macro --- libimagnotes/Cargo.toml | 3 ++ libimagnotes/src/error.rs | 86 +++------------------------------------ libimagnotes/src/lib.rs | 1 + 3 files changed, 10 insertions(+), 80 deletions(-) diff --git a/libimagnotes/Cargo.toml b/libimagnotes/Cargo.toml index 6bc99cee..f13cf218 100644 --- a/libimagnotes/Cargo.toml +++ b/libimagnotes/Cargo.toml @@ -11,6 +11,9 @@ toml = "0.1.25" [dependencies.libimagstore] path = "../libimagstore" +[dependencies.libimagerror] +path = "../libimagerror" + [dependencies.libimagrt] path = "../libimagrt" diff --git a/libimagnotes/src/error.rs b/libimagnotes/src/error.rs index ec1f5535..527aa710 100644 --- a/libimagnotes/src/error.rs +++ b/libimagnotes/src/error.rs @@ -2,84 +2,10 @@ use std::error::Error; use std::fmt::Error as FmtError; use std::fmt::{Display, Formatter}; -/** - * Kind of error - */ -#[derive(Clone, Copy, Debug, PartialEq)] -pub enum NoteErrorKind { - StoreWriteError, - StoreReadError, - HeaderTypeError, - NoteToEntryConversion, - // Nothing here yet -} - -fn note_error_type_as_str(e: &NoteErrorKind) -> &'static str { - match *e { - NoteErrorKind::StoreWriteError => "Error writing store", - NoteErrorKind::StoreReadError => "Error reading store", - NoteErrorKind::HeaderTypeError => "Header type error", - NoteErrorKind::NoteToEntryConversion => "Error converting Note instance to Entry instance", - } -} - -impl Display for NoteErrorKind { - - fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> { - try!(write!(fmt, "{}", note_error_type_as_str(self))); - Ok(()) - } - -} - -/** - * Store error type - */ -#[derive(Debug)] -pub struct NoteError { - err_type: NoteErrorKind, - cause: Option>, -} - -impl NoteError { - - /** - * Build a new NoteError from an NoteErrorKind, optionally with cause - */ - pub fn new(errtype: NoteErrorKind, cause: Option>) -> NoteError { - NoteError { - err_type: errtype, - cause: cause, - } - } - - /** - * Get the error type of this NoteError - */ - pub fn err_type(&self) -> NoteErrorKind { - self.err_type - } - -} - -impl Display for NoteError { - - fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> { - try!(write!(fmt, "[{}]", note_error_type_as_str(&self.err_type))); - Ok(()) - } - -} - -impl Error for NoteError { - - fn description(&self) -> &str { - note_error_type_as_str(&self.err_type) - } - - fn cause(&self) -> Option<&Error> { - self.cause.as_ref().map(|e| &**e) - } - -} +generate_error_types!(NoteError, NoteErrorKind, + StoreWriteError => "Error writing store", + StoreReadError => "Error reading store", + HeaderTypeError => "Header type error", + NoteToEntryConversion => "Error converting Note instance to Entry instance" +); diff --git a/libimagnotes/src/lib.rs b/libimagnotes/src/lib.rs index 64ef75a2..ee43c9a3 100644 --- a/libimagnotes/src/lib.rs +++ b/libimagnotes/src/lib.rs @@ -20,6 +20,7 @@ extern crate toml; extern crate libimagrt; #[macro_use] extern crate libimagstore; +#[macro_use] extern crate libimagerror; extern crate libimagentrytag; module_entry_path_mod!("notes", "0.1.0"); From f27b114f850b94b1826faf9e07303ad9c7b96b9b Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sun, 15 May 2016 16:53:31 +0200 Subject: [PATCH 086/288] libimagrt: Replace error code with code generator macro --- libimagrt/Cargo.toml | 3 +++ libimagrt/src/error.rs | 59 ++++-------------------------------------- libimagrt/src/lib.rs | 1 + 3 files changed, 9 insertions(+), 54 deletions(-) diff --git a/libimagrt/Cargo.toml b/libimagrt/Cargo.toml index 485994b5..89610457 100644 --- a/libimagrt/Cargo.toml +++ b/libimagrt/Cargo.toml @@ -21,3 +21,6 @@ path = "../libimagstorestdhook" [dependencies.libimagutil] path = "../libimagutil" +[dependencies.libimagerror] +path = "../libimagerror" + diff --git a/libimagrt/src/error.rs b/libimagrt/src/error.rs index ca343ede..93752552 100644 --- a/libimagrt/src/error.rs +++ b/libimagrt/src/error.rs @@ -4,60 +4,11 @@ use std::fmt::Formatter; use std::fmt::Error as FmtError; use std::io::Error as IOError; -#[derive(Debug, PartialEq, Clone, Copy)] -pub enum RuntimeErrorKind { - Instantiate, - IOError, - ProcessExitFailure, - - // more? -} - -#[derive(Debug)] -pub struct RuntimeError { - kind: RuntimeErrorKind, - cause: Option>, -} - -impl RuntimeError { - - pub fn new(kind: RuntimeErrorKind, cause: Option>) -> RuntimeError { - RuntimeError { - kind: kind, - cause: cause, - } - } - -} - -fn runtime_error_kind_as_str(e: &RuntimeErrorKind) -> &'static str { - match *e { - RuntimeErrorKind::Instantiate => "Could not instantiate", - RuntimeErrorKind::IOError => "IO Error", - RuntimeErrorKind::ProcessExitFailure => "Process exited with failure", - } -} - -impl Display for RuntimeError { - - fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> { - try!(write!(fmt, "{}", runtime_error_kind_as_str(&self.kind))); - Ok(()) - } - -} - -impl Error for RuntimeError { - - fn description(&self) -> &str { - runtime_error_kind_as_str(&self.kind) - } - - fn cause(&self) -> Option<&Error> { - self.cause.as_ref().map(|e| &**e) - } - -} +generate_error_types!(RuntimeError, RuntimeErrorKind, + Instantiate => "Could not instantiate", + IOError => "IO Error", + ProcessExitFailure => "Process exited with failure" +); impl From for RuntimeError { diff --git a/libimagrt/src/lib.rs b/libimagrt/src/lib.rs index 7c9e3f59..ef0874e2 100644 --- a/libimagrt/src/lib.rs +++ b/libimagrt/src/lib.rs @@ -26,6 +26,7 @@ extern crate toml; extern crate libimagstore; extern crate libimagstorestdhook; extern crate libimagutil; +#[macro_use] extern crate libimagerror; mod configuration; mod logger; From 1c723a9a0eaadfd06b72732d4baaa0bc08894587 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Mon, 16 May 2016 18:52:41 +0200 Subject: [PATCH 087/288] Move trace_error() functionality from libimagutil to libimagerror --- libimagerror/Cargo.toml | 2 ++ libimagerror/src/lib.rs | 4 ++++ {libimagutil => libimagerror}/src/trace.rs | 0 libimagutil/Cargo.toml | 1 - libimagutil/src/lib.rs | 2 -- 5 files changed, 6 insertions(+), 3 deletions(-) rename {libimagutil => libimagerror}/src/trace.rs (100%) diff --git a/libimagerror/Cargo.toml b/libimagerror/Cargo.toml index bd769698..2227ce9e 100644 --- a/libimagerror/Cargo.toml +++ b/libimagerror/Cargo.toml @@ -4,3 +4,5 @@ version = "0.1.0" authors = ["Matthias Beyer "] [dependencies] +log = "0.3" +ansi_term = "0.7" diff --git a/libimagerror/src/lib.rs b/libimagerror/src/lib.rs index 9f79f549..d7f374a7 100644 --- a/libimagerror/src/lib.rs +++ b/libimagerror/src/lib.rs @@ -1 +1,5 @@ +#[macro_use] extern crate log; +extern crate ansi_term; + pub mod error_gen; +pub mod trace; diff --git a/libimagutil/src/trace.rs b/libimagerror/src/trace.rs similarity index 100% rename from libimagutil/src/trace.rs rename to libimagerror/src/trace.rs diff --git a/libimagutil/Cargo.toml b/libimagutil/Cargo.toml index efcbff44..96638623 100644 --- a/libimagutil/Cargo.toml +++ b/libimagutil/Cargo.toml @@ -7,5 +7,4 @@ authors = ["Matthias Beyer "] lazy_static = "0.1.15" log = "0.3" regex = "0.1" -ansi_term = "0.7" diff --git a/libimagutil/src/lib.rs b/libimagutil/src/lib.rs index e0d7a3ce..bde49b00 100644 --- a/libimagutil/src/lib.rs +++ b/libimagutil/src/lib.rs @@ -16,9 +16,7 @@ #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; extern crate regex; -extern crate ansi_term; pub mod ismatch; pub mod key_value_split; -pub mod trace; pub mod variants; From ea01312412697e82d8a2175ef1059e6acf9d7f9a Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Mon, 16 May 2016 18:59:02 +0200 Subject: [PATCH 088/288] imag-counter: Change dependency from libimagutil -> libimagerror --- imag-counter/Cargo.toml | 3 +++ imag-counter/src/create.rs | 2 +- imag-counter/src/delete.rs | 2 +- imag-counter/src/interactive.rs | 2 +- imag-counter/src/list.rs | 2 +- imag-counter/src/main.rs | 3 ++- 6 files changed, 9 insertions(+), 5 deletions(-) diff --git a/imag-counter/Cargo.toml b/imag-counter/Cargo.toml index d3441fbb..964eda85 100644 --- a/imag-counter/Cargo.toml +++ b/imag-counter/Cargo.toml @@ -11,6 +11,9 @@ version = "2.0.1" [dependencies.libimagrt] path = "../libimagrt" +[dependencies.libimagerror] +path = "../libimagerror" + [dependencies.libimagutil] path = "../libimagutil" diff --git a/imag-counter/src/create.rs b/imag-counter/src/create.rs index 1b2838a5..22a38b34 100644 --- a/imag-counter/src/create.rs +++ b/imag-counter/src/create.rs @@ -2,7 +2,7 @@ use std::str::FromStr; use std::process::exit; use libimagrt::runtime::Runtime; -use libimagutil::trace::trace_error; +use libimagerror::trace::trace_error; use libimagcounter::counter::Counter; pub fn create(rt: &Runtime) { diff --git a/imag-counter/src/delete.rs b/imag-counter/src/delete.rs index bb68f2f1..4d7e6067 100644 --- a/imag-counter/src/delete.rs +++ b/imag-counter/src/delete.rs @@ -1,7 +1,7 @@ use std::process::exit; use libimagrt::runtime::Runtime; -use libimagutil::trace::trace_error; +use libimagerror::trace::trace_error; use libimagcounter::counter::Counter; pub fn delete(rt: &Runtime) { diff --git a/imag-counter/src/interactive.rs b/imag-counter/src/interactive.rs index 5a2b1e01..e07d8e1d 100644 --- a/imag-counter/src/interactive.rs +++ b/imag-counter/src/interactive.rs @@ -10,7 +10,7 @@ use libimagcounter::counter::Counter; use libimagcounter::error::CounterError; use libimagrt::runtime::Runtime; use libimagutil::key_value_split::IntoKeyValue; -use libimagutil::trace::trace_error; +use libimagerror::trace::trace_error; type Result = RResult; diff --git a/imag-counter/src/list.rs b/imag-counter/src/list.rs index 41e9ce62..57f1ef32 100644 --- a/imag-counter/src/list.rs +++ b/imag-counter/src/list.rs @@ -1,5 +1,5 @@ use libimagrt::runtime::Runtime; -use libimagutil::trace::trace_error; +use libimagerror::trace::trace_error; use libimagcounter::counter::Counter; pub fn list(rt: &Runtime) { diff --git a/imag-counter/src/main.rs b/imag-counter/src/main.rs index 538149dc..8eaa72d4 100644 --- a/imag-counter/src/main.rs +++ b/imag-counter/src/main.rs @@ -19,6 +19,7 @@ extern crate clap; extern crate libimagcounter; extern crate libimagrt; +extern crate libimagerror; extern crate libimagutil; use std::process::exit; @@ -26,7 +27,7 @@ use std::str::FromStr; use libimagrt::runtime::Runtime; use libimagcounter::counter::Counter; -use libimagutil::trace::trace_error; +use libimagerror::trace::trace_error; use libimagutil::key_value_split::IntoKeyValue; mod create; From 93ce1dbfd2890fdc8c596594d09890449b0fc993 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Mon, 16 May 2016 18:59:02 +0200 Subject: [PATCH 089/288] imag-link: Change dependency from libimagutil -> libimagerror --- imag-link/Cargo.toml | 4 ++-- imag-link/src/main.rs | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/imag-link/Cargo.toml b/imag-link/Cargo.toml index 858ff6f0..59ee82f1 100644 --- a/imag-link/Cargo.toml +++ b/imag-link/Cargo.toml @@ -20,6 +20,6 @@ path = "../libimagrt" [dependencies.libimagentrylink] path = "../libimagentrylink" -[dependencies.libimagutil] -path = "../libimagutil" +[dependencies.libimagerror] +path = "../libimagerror" diff --git a/imag-link/src/main.rs b/imag-link/src/main.rs index 8e2399df..48da0014 100644 --- a/imag-link/src/main.rs +++ b/imag-link/src/main.rs @@ -23,7 +23,7 @@ extern crate url; extern crate libimagentrylink; extern crate libimagrt; extern crate libimagstore; -extern crate libimagutil; +extern crate libimagerror; use std::process::exit; use std::ops::Deref; @@ -33,7 +33,7 @@ use libimagstore::error::StoreError; use libimagstore::store::Entry; use libimagstore::store::FileLockEntry; use libimagstore::store::Store; -use libimagutil::trace::trace_error; +use libimagerror::trace::trace_error; use libimagentrylink::external::ExternalLinker; use clap::ArgMatches; use url::Url; @@ -74,7 +74,7 @@ fn main() { fn handle_internal_linking(rt: &Runtime) { use libimagentrylink::internal::InternalLinker; - use libimagutil::trace::trace_error; + use libimagerror::trace::trace_error; debug!("Handle internal linking call"); let cmd = rt.cli().subcommand_matches("internal").unwrap(); @@ -192,7 +192,7 @@ fn get_entry_by_name<'a>(rt: &'a Runtime, name: &str) -> Result Date: Mon, 16 May 2016 18:59:02 +0200 Subject: [PATCH 090/288] imag-notes: Change dependency from libimagutil -> libimagerror --- imag-notes/Cargo.toml | 4 ++-- imag-notes/src/main.rs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/imag-notes/Cargo.toml b/imag-notes/Cargo.toml index 64f9f990..d6f78bfd 100644 --- a/imag-notes/Cargo.toml +++ b/imag-notes/Cargo.toml @@ -18,6 +18,6 @@ path = "../libimagnotes" [dependencies.libimagentrytag] path = "../libimagentrytag" -[dependencies.libimagutil] -path = "../libimagutil" +[dependencies.libimagerror] +path = "../libimagerror" diff --git a/imag-notes/src/main.rs b/imag-notes/src/main.rs index ee0df3d3..7e615afd 100644 --- a/imag-notes/src/main.rs +++ b/imag-notes/src/main.rs @@ -6,14 +6,14 @@ extern crate semver; extern crate libimagnotes; extern crate libimagrt; extern crate libimagentrytag; -extern crate libimagutil; +extern crate libimagerror; use std::process::exit; use libimagrt::edit::Edit; use libimagrt::runtime::Runtime; use libimagnotes::note::Note; -use libimagutil::trace::trace_error; +use libimagerror::trace::trace_error; mod ui; use ui::build_ui; From ab29265b1094dda481049bdfe16078de18cf5278 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Mon, 16 May 2016 18:59:02 +0200 Subject: [PATCH 091/288] imag-store: Change dependency from libimagutil -> libimagerror --- imag-store/src/create.rs | 2 +- imag-store/src/delete.rs | 2 +- imag-store/src/retrieve.rs | 2 +- imag-store/src/update.rs | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/imag-store/src/create.rs b/imag-store/src/create.rs index fc33c9ee..8cb2b2aa 100644 --- a/imag-store/src/create.rs +++ b/imag-store/src/create.rs @@ -14,7 +14,7 @@ use libimagrt::runtime::Runtime; use libimagstore::store::Entry; use libimagstore::store::EntryHeader; use libimagstore::storeid::build_entry_path; -use libimagutil::trace::trace_error; +use libimagerror::trace::trace_error; use error::StoreError; use error::StoreErrorKind; diff --git a/imag-store/src/delete.rs b/imag-store/src/delete.rs index 0c59fc37..fb994818 100644 --- a/imag-store/src/delete.rs +++ b/imag-store/src/delete.rs @@ -1,6 +1,6 @@ use libimagstore::storeid::build_entry_path; use libimagrt::runtime::Runtime; -use libimagutil::trace::trace_error; +use libimagerror::trace::trace_error; pub fn delete(rt: &Runtime) { use std::process::exit; diff --git a/imag-store/src/retrieve.rs b/imag-store/src/retrieve.rs index c6b6adc8..113d5e8e 100644 --- a/imag-store/src/retrieve.rs +++ b/imag-store/src/retrieve.rs @@ -6,7 +6,7 @@ use toml::Value; use libimagstore::store::FileLockEntry; use libimagstore::storeid::build_entry_path; use libimagrt::runtime::Runtime; -use libimagutil::trace::trace_error; +use libimagerror::trace::trace_error; pub fn retrieve(rt: &Runtime) { rt.cli() diff --git a/imag-store/src/update.rs b/imag-store/src/update.rs index 311ce138..5022aaac 100644 --- a/imag-store/src/update.rs +++ b/imag-store/src/update.rs @@ -3,7 +3,7 @@ use std::process::exit; use libimagrt::runtime::Runtime; use libimagstore::storeid::build_entry_path; -use libimagutil::trace::trace_error; +use libimagerror::trace::trace_error; use util::build_toml_header; From be397bcdb6ce89e1353596a91cf56b0c5ffbbc4f Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Mon, 16 May 2016 18:59:02 +0200 Subject: [PATCH 092/288] imag-tag: Change dependency from libimagutil -> libimagerror --- imag-tag/Cargo.toml | 4 ++-- imag-tag/src/main.rs | 5 ++--- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/imag-tag/Cargo.toml b/imag-tag/Cargo.toml index c3ed51ef..b9d7af38 100644 --- a/imag-tag/Cargo.toml +++ b/imag-tag/Cargo.toml @@ -16,8 +16,8 @@ path = "../libimagstore" [dependencies.libimagrt] path = "../libimagrt" -[dependencies.libimagutil] -path = "../libimagutil" +[dependencies.libimagerror] +path = "../libimagerror" [dependencies.libimagentrytag] path = "../libimagentrytag" diff --git a/imag-tag/src/main.rs b/imag-tag/src/main.rs index f070dbd1..f737d6e0 100644 --- a/imag-tag/src/main.rs +++ b/imag-tag/src/main.rs @@ -7,20 +7,19 @@ extern crate toml; extern crate libimagstore; extern crate libimagrt; extern crate libimagentrytag; -extern crate libimagutil; +extern crate libimagerror; use std::process::exit; use libimagrt::runtime::Runtime; use libimagentrytag::tagable::Tagable; use libimagstore::storeid::build_entry_path; +use libimagerror::trace::trace_error; mod ui; use ui::build_ui; -use libimagutil::trace::trace_error; - fn main() { let name = "imag-store"; let version = &version!()[..]; From 204e7761790219d4597b7fd1d93534e31acbf49d Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Mon, 16 May 2016 18:59:02 +0200 Subject: [PATCH 093/288] imag-view: Change dependency from libimagutil -> libimagerror --- imag-view/Cargo.toml | 3 --- imag-view/src/main.rs | 3 +-- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/imag-view/Cargo.toml b/imag-view/Cargo.toml index 7c7b3d55..2c43920e 100644 --- a/imag-view/Cargo.toml +++ b/imag-view/Cargo.toml @@ -18,9 +18,6 @@ path = "../libimagstore" [dependencies.libimagrt] path = "../libimagrt" -[dependencies.libimagutil] -path = "../libimagutil" - [dependencies.libimagerror] path = "../libimagerror" diff --git a/imag-view/src/main.rs b/imag-view/src/main.rs index 0efc25c8..81d2b5e9 100644 --- a/imag-view/src/main.rs +++ b/imag-view/src/main.rs @@ -22,7 +22,6 @@ extern crate toml; extern crate libimagrt; extern crate libimagstore; -extern crate libimagutil; #[macro_use] extern crate libimagerror; use std::result::Result as RResult; @@ -30,7 +29,7 @@ use std::process::exit; use libimagrt::runtime::Runtime; use libimagstore::store::FileLockEntry; -use libimagutil::trace::trace_error; +use libimagerror::trace::trace_error; mod error; mod ui; From ee32a85ff3888db5bbdad5eb5bd7a338239c24f8 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Mon, 16 May 2016 18:59:02 +0200 Subject: [PATCH 094/288] libimagrt: Change dependency from libimagutil -> libimagerror --- libimagrt/src/runtime.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/libimagrt/src/runtime.rs b/libimagrt/src/runtime.rs index cae46bda..5087d063 100644 --- a/libimagrt/src/runtime.rs +++ b/libimagrt/src/runtime.rs @@ -42,8 +42,8 @@ impl<'a> Runtime<'a> { use libimagstore::hook::position::HookPosition; use libimagstore::error::StoreErrorKind; use libimagstorestdhook::debug::DebugHook; - use libimagutil::trace::trace_error; - use libimagutil::trace::trace_error_dbg; + use libimagerror::trace::trace_error; + use libimagerror::trace::trace_error_dbg; use configuration::error::ConfigErrorKind; From 8e5f5bae0bf743b4d285ccee94d6e410a68eabb0 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Mon, 16 May 2016 18:59:02 +0200 Subject: [PATCH 095/288] libimagstorestdhook: Change dependency from libimagutil -> libimagerror --- libimagstorestdhook/Cargo.toml | 4 ++-- libimagstorestdhook/src/lib.rs | 2 +- libimagstorestdhook/src/linkverify.rs | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/libimagstorestdhook/Cargo.toml b/libimagstorestdhook/Cargo.toml index 81ba8f37..789fc053 100644 --- a/libimagstorestdhook/Cargo.toml +++ b/libimagstorestdhook/Cargo.toml @@ -14,6 +14,6 @@ path = "../libimagstore" [dependencies.libimagentrylink] path = "../libimagentrylink" -[dependencies.libimagutil] -path = "../libimagutil" +[dependencies.libimagerror] +path = "../libimagerror" diff --git a/libimagstorestdhook/src/lib.rs b/libimagstorestdhook/src/lib.rs index 05e92f75..c53cbc52 100644 --- a/libimagstorestdhook/src/lib.rs +++ b/libimagstorestdhook/src/lib.rs @@ -20,7 +20,7 @@ extern crate fs2; extern crate libimagstore; extern crate libimagentrylink; -extern crate libimagutil; +extern crate libimagerror; pub mod debug; pub mod flock; diff --git a/libimagstorestdhook/src/linkverify.rs b/libimagstorestdhook/src/linkverify.rs index 295a9de4..e97981b7 100644 --- a/libimagstorestdhook/src/linkverify.rs +++ b/libimagstorestdhook/src/linkverify.rs @@ -9,7 +9,7 @@ use libimagstore::hook::accessor::NonMutableHookDataAccessor; use libimagstore::hook::result::HookResult; use libimagstore::store::FileLockEntry; use libimagentrylink::internal::InternalLinker; -use libimagutil::trace::trace_error; +use libimagerror::trace::trace_error; #[derive(Debug, Clone)] pub struct LinkedEntriesExistHook { From f4f807bc1344c88e004b6b36af4d10f7e172a0bb Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Wed, 18 May 2016 22:26:35 +0200 Subject: [PATCH 096/288] Extract args into new helper functions --- libimagentrytag/src/ui.rs | 30 ++++++++++++++++++------------ 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/libimagentrytag/src/ui.rs b/libimagentrytag/src/ui.rs index ecef19d6..de0cbbfc 100644 --- a/libimagentrytag/src/ui.rs +++ b/libimagentrytag/src/ui.rs @@ -9,20 +9,26 @@ pub fn tag_subcommand<'a, 'b>() -> App<'a, 'b> { .author("Matthias Beyer ") .version("0.1") .about("Add or remove tags") + .arg(tag_add_arg()) + .arg(tag_remove_arg()) +} - .arg(Arg::with_name(tag_subcommand_add_arg_name()) - .short("a") - .long("add") - .takes_value(true) - .multiple(true) - .help("Add tags, seperated by comma or by specifying multiple times")) +pub fn tag_add_arg<'a, 'b>() -> Arg<'a, 'b> { + Arg::with_name(tag_subcommand_add_arg_name()) + .short("a") + .long("add") + .takes_value(true) + .multiple(true) + .help("Add tags, seperated by comma or by specifying multiple times") +} - .arg(Arg::with_name(tag_subcommand_remove_arg_name()) - .short("r") - .long("remove") - .takes_value(true) - .multiple(true) - .help("Remove tags, seperated by comma or by specifying multiple times")) +pub fn tag_remove_arg<'a, 'b>() -> Arg<'a, 'b> { + Arg::with_name(tag_subcommand_remove_arg_name()) + .short("r") + .long("remove") + .takes_value(true) + .multiple(true) + .help("Remove tags, seperated by comma or by specifying multiple times") } pub fn tag_subcommand_name() -> &'static str { From c6821a53cafabc935ebcbaeda9e879d017bc829d Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Wed, 18 May 2016 22:27:01 +0200 Subject: [PATCH 097/288] Change get_add_tags() to get to-add-tags from top level, if there are any --- libimagentrytag/src/ui.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/libimagentrytag/src/ui.rs b/libimagentrytag/src/ui.rs index de0cbbfc..474bfd5b 100644 --- a/libimagentrytag/src/ui.rs +++ b/libimagentrytag/src/ui.rs @@ -66,7 +66,13 @@ pub fn tag_argument_name() -> &'static str { /// /// Returns none if the argument was not specified pub fn get_add_tags(matches: &ArgMatches) -> Option> { - extract_tags(matches, "add-tags", '+') + if let Some(v) = extract_tags(matches, tag_subcommand_add_arg_name(), '+') { + return Some(v); + } else { + matches + .values_of(tag_subcommand_add_arg_name()) + .map(|values| values.map(String::from).collect()) + } } /// Get the tags which should be removed from the commandline From ed724d3726356edb1753b21ec3860fe512c1b4ea Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Wed, 18 May 2016 22:28:15 +0200 Subject: [PATCH 098/288] Change get_remove_tags() to get to-remove-tags from top level if there are any --- libimagentrytag/src/ui.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/libimagentrytag/src/ui.rs b/libimagentrytag/src/ui.rs index 474bfd5b..70b9337e 100644 --- a/libimagentrytag/src/ui.rs +++ b/libimagentrytag/src/ui.rs @@ -79,7 +79,13 @@ pub fn get_add_tags(matches: &ArgMatches) -> Option> { /// /// Returns none if the argument was not specified pub fn get_remove_tags(matches: &ArgMatches) -> Option> { - extract_tags(matches, "remove-tags", '-') + if let Some(v) = extract_tags(matches, tag_subcommand_remove_arg_name(), '-') { + return Some(v); + } else { + matches + .values_of(tag_subcommand_remove_arg_name()) + .map(|values| values.map(String::from).collect()) + } } fn extract_tags(matches: &ArgMatches, specifier: &str, specchar: char) -> Option> { From f88e3e629b1e1a0b6ed80c4e4efba704e56741c0 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Wed, 18 May 2016 19:00:41 +0200 Subject: [PATCH 099/288] Add runtime setup helper function --- libimagrt/src/lib.rs | 1 + libimagrt/src/setup.rs | 27 +++++++++++++++++++++++++++ 2 files changed, 28 insertions(+) create mode 100644 libimagrt/src/setup.rs diff --git a/libimagrt/src/lib.rs b/libimagrt/src/lib.rs index ef0874e2..e4503f2e 100644 --- a/libimagrt/src/lib.rs +++ b/libimagrt/src/lib.rs @@ -34,4 +34,5 @@ mod logger; pub mod edit; pub mod error; pub mod runtime; +pub mod setup; diff --git a/libimagrt/src/setup.rs b/libimagrt/src/setup.rs new file mode 100644 index 00000000..620a81cf --- /dev/null +++ b/libimagrt/src/setup.rs @@ -0,0 +1,27 @@ +use clap::App; + +use runtime::Runtime; + +pub type Name = &'static str; +pub type Version<'a> = &'a str; +pub type About = &'static str; + +/// Helper to generate the Runtime object +/// +/// exit()s the program if the runtime couldn't be build, prints error with println!() before +/// exiting +pub fn generate_runtime_setup<'a, B>(name: Name, version: Version<'a>, about: About, builder: B) + -> Runtime<'a> + where B: FnOnce(App<'a, 'a>) -> App<'a, 'a> +{ + use std::process::exit; + use libimagerror::trace::trace_error_dbg; + + Runtime::new(builder(Runtime::get_default_cli_builder(name, version, about))) + .unwrap_or_else(|e| { + println!("Could not set up Runtime"); + println!("{:?}", e); + trace_error_dbg(&e); + exit(1); + }) +} From 2a27bd10c9f9f9294aa7f8264dae6fe00c629167 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Wed, 18 May 2016 19:06:05 +0200 Subject: [PATCH 100/288] imag-counter: Remove setup code and use helper --- imag-counter/src/main.rs | 20 +++++--------------- 1 file changed, 5 insertions(+), 15 deletions(-) diff --git a/imag-counter/src/main.rs b/imag-counter/src/main.rs index 8eaa72d4..76dcc00c 100644 --- a/imag-counter/src/main.rs +++ b/imag-counter/src/main.rs @@ -25,7 +25,7 @@ extern crate libimagutil; use std::process::exit; use std::str::FromStr; -use libimagrt::runtime::Runtime; +use libimagrt::setup::generate_runtime_setup; use libimagcounter::counter::Counter; use libimagerror::trace::trace_error; use libimagutil::key_value_split::IntoKeyValue; @@ -50,20 +50,10 @@ enum Action { } fn main() { - let name = "imag-counter"; - let version = &version!()[..]; - let about = "Counter tool to count things"; - let ui = build_ui(Runtime::get_default_cli_builder(name, version, about)); - let rt = { - let rt = Runtime::new(ui); - if rt.is_ok() { - rt.unwrap() - } else { - println!("Could not set up Runtime"); - println!("{:?}", rt.unwrap_err()); - exit(1); - } - }; + let rt = generate_runtime_setup("imag-counter", + &version!()[..], + "Counter tool to count things", + build_ui); rt.cli() .subcommand_name() From 2e94de2fcec6b3b3cfd9abb10a479c5caf5d32b4 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Wed, 18 May 2016 19:06:05 +0200 Subject: [PATCH 101/288] imag-link: Remove setup code and use helper --- imag-link/src/main.rs | 19 +++++-------------- 1 file changed, 5 insertions(+), 14 deletions(-) diff --git a/imag-link/src/main.rs b/imag-link/src/main.rs index 48da0014..fdfdb764 100644 --- a/imag-link/src/main.rs +++ b/imag-link/src/main.rs @@ -29,6 +29,7 @@ use std::process::exit; use std::ops::Deref; use libimagrt::runtime::Runtime; +use libimagrt::setup::generate_runtime_setup; use libimagstore::error::StoreError; use libimagstore::store::Entry; use libimagstore::store::FileLockEntry; @@ -43,20 +44,10 @@ mod ui; use ui::build_ui; fn main() { - let name = "imag-link"; - let version = &version!()[..]; - let about = "Link entries"; - let ui = build_ui(Runtime::get_default_cli_builder(name, version, about)); - let rt = { - let rt = Runtime::new(ui); - if rt.is_ok() { - rt.unwrap() - } else { - println!("Could not set up Runtime"); - println!("{:?}", rt.unwrap_err()); - exit(1); - } - }; + let rt = generate_runtime_setup("imag-link", + &version!()[..], + "Link entries", + build_ui); rt.cli() .subcommand_name() From 04d66d269e753c97ee7eef6bf17996343ce73aca Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Wed, 18 May 2016 19:06:05 +0200 Subject: [PATCH 102/288] imag-notes: Remove setup code and use helper --- imag-notes/src/main.rs | 19 +++++-------------- 1 file changed, 5 insertions(+), 14 deletions(-) diff --git a/imag-notes/src/main.rs b/imag-notes/src/main.rs index 7e615afd..4dcaac34 100644 --- a/imag-notes/src/main.rs +++ b/imag-notes/src/main.rs @@ -12,6 +12,7 @@ use std::process::exit; use libimagrt::edit::Edit; use libimagrt::runtime::Runtime; +use libimagrt::setup::generate_runtime_setup; use libimagnotes::note::Note; use libimagerror::trace::trace_error; @@ -19,20 +20,10 @@ mod ui; use ui::build_ui; fn main() { - let name = "imag-notes"; - let version = &version!()[..]; - let about = "Note taking helper"; - let ui = build_ui(Runtime::get_default_cli_builder(name, version, about)); - let rt = { - let rt = Runtime::new(ui); - if rt.is_ok() { - rt.unwrap() - } else { - println!("Could not set up Runtime"); - println!("{:?}", rt.unwrap_err()); - exit(1); - } - }; + let rt = generate_runtime_setup("imag-notes", + &version!()[..], + "Note taking helper", + build_ui); rt.cli() .subcommand_name() From 77f9e5ae0e7b77853d6867ce4087f04eba59c89a Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Wed, 18 May 2016 19:06:05 +0200 Subject: [PATCH 103/288] imag-store: Remove setup code and use helper --- imag-store/src/main.rs | 21 +++++---------------- 1 file changed, 5 insertions(+), 16 deletions(-) diff --git a/imag-store/src/main.rs b/imag-store/src/main.rs index fd0a2c4d..6537687e 100644 --- a/imag-store/src/main.rs +++ b/imag-store/src/main.rs @@ -24,8 +24,7 @@ extern crate libimagstore; extern crate libimagutil; #[macro_use] extern crate libimagerror; -use libimagrt::runtime::Runtime; -use std::process::exit; +use libimagrt::setup::generate_runtime_setup; mod error; mod ui; @@ -42,20 +41,10 @@ use update::update; use delete::delete; fn main() { - let name = "imag-store"; - let version = &version!()[..]; - let about = "Direct interface to the store. Use with great care!"; - let ui = build_ui(Runtime::get_default_cli_builder(name, version, about)); - let rt = { - let rt = Runtime::new(ui); - if rt.is_ok() { - rt.unwrap() - } else { - println!("Could not set up Runtime"); - println!("{:?}", rt.unwrap_err()); - exit(1); - } - }; + let rt = generate_runtime_setup("imag-store", + &version!()[..], + "Direct interface to the store. Use with great care!", + build_ui); rt.cli() .subcommand_name() From 9c374528d9c5c20ef4f9bdaf7d50e0f5da07a563 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Wed, 18 May 2016 19:06:05 +0200 Subject: [PATCH 104/288] imag-tag: Remove setup code and use helper --- imag-tag/src/main.rs | 19 +++++-------------- 1 file changed, 5 insertions(+), 14 deletions(-) diff --git a/imag-tag/src/main.rs b/imag-tag/src/main.rs index f737d6e0..d653686f 100644 --- a/imag-tag/src/main.rs +++ b/imag-tag/src/main.rs @@ -12,6 +12,7 @@ extern crate libimagerror; use std::process::exit; use libimagrt::runtime::Runtime; +use libimagrt::setup::generate_runtime_setup; use libimagentrytag::tagable::Tagable; use libimagstore::storeid::build_entry_path; use libimagerror::trace::trace_error; @@ -21,20 +22,10 @@ mod ui; use ui::build_ui; fn main() { - let name = "imag-store"; - let version = &version!()[..]; - let about = "Direct interface to the store. Use with great care!"; - let ui = build_ui(Runtime::get_default_cli_builder(name, version, about)); - let rt = { - let rt = Runtime::new(ui); - if rt.is_ok() { - rt.unwrap() - } else { - println!("Could not set up Runtime"); - println!("{:?}", rt.unwrap_err()); - exit(1); - } - }; + let rt = generate_runtime_setup("imag-store", + &version!()[..], + "Direct interface to the store. Use with great care!", + build_ui); let id = rt.cli().value_of("id").unwrap(); // enforced by clap rt.cli() From 2e9dc4730f5f3eeac17471606037600e55244c6e Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Wed, 18 May 2016 19:06:05 +0200 Subject: [PATCH 105/288] imag-view: Remove setup code and use helper --- imag-view/src/main.rs | 19 +++++-------------- 1 file changed, 5 insertions(+), 14 deletions(-) diff --git a/imag-view/src/main.rs b/imag-view/src/main.rs index 81d2b5e9..2fa7802b 100644 --- a/imag-view/src/main.rs +++ b/imag-view/src/main.rs @@ -28,6 +28,7 @@ use std::result::Result as RResult; use std::process::exit; use libimagrt::runtime::Runtime; +use libimagrt::setup::generate_runtime_setup; use libimagstore::store::FileLockEntry; use libimagerror::trace::trace_error; @@ -44,20 +45,10 @@ use viewer::stdout::StdoutViewer; type Result = RResult; fn main() { - let name = "imag-view"; - let version = &version!()[..]; - let about = "View entries (readonly)"; - let ui = build_ui(Runtime::get_default_cli_builder(name, version, about)); - let rt = { - let rt = Runtime::new(ui); - if rt.is_ok() { - rt.unwrap() - } else { - println!("Could not set up Runtime"); - println!("{:?}", rt.unwrap_err()); - exit(1); // we can afford not-executing destructors here - } - }; + let rt = generate_runtime_setup( "imag-view", + &version!()[..], + "View entries (readonly)", + build_ui); let entry_id = rt.cli().value_of("id").unwrap(); // enforced by clap From 257474be22b9a1b9dbf39abdca98e5cd14165f9f Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Thu, 19 May 2016 16:20:06 +0200 Subject: [PATCH 106/288] imag-tag: Replace UI spec with helpers from libimagentrytag --- imag-tag/src/ui.rs | 19 ++++--------------- 1 file changed, 4 insertions(+), 15 deletions(-) diff --git a/imag-tag/src/ui.rs b/imag-tag/src/ui.rs index 74916879..32e3383c 100644 --- a/imag-tag/src/ui.rs +++ b/imag-tag/src/ui.rs @@ -1,5 +1,7 @@ use clap::{Arg, App, ArgGroup, SubCommand}; +use libimagentrytag::ui::{tag_add_arg, tag_remove_arg}; + pub fn build_ui<'a>(app: App<'a, 'a>) -> App<'a, 'a> { app.arg(Arg::with_name("id") .long("id") @@ -8,21 +10,8 @@ pub fn build_ui<'a>(app: App<'a, 'a>) -> App<'a, 'a> { .required(true) .help("Use this entry")) - .arg(Arg::with_name("add") - .long("add") - .short("a") - .takes_value(true) - .required(false) - .multiple(true) - .help("Add this tag")) - - .arg(Arg::with_name("remove") - .long("remove") - .short("r") - .takes_value(true) - .required(false) - .multiple(true) - .help("Remove this tag")) + .arg(tag_add_arg()) + .arg(tag_remove_arg()) .subcommand(SubCommand::with_name("list") .about("List tags (default)") From 435fd6d7aacba133abdd291600322fd0953c0187 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Thu, 19 May 2016 16:20:32 +0200 Subject: [PATCH 107/288] imag-tag: Fix commandline extracting by using helpers from libimagentrytag --- imag-tag/src/main.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/imag-tag/src/main.rs b/imag-tag/src/main.rs index f737d6e0..4ab50895 100644 --- a/imag-tag/src/main.rs +++ b/imag-tag/src/main.rs @@ -13,8 +13,10 @@ use std::process::exit; use libimagrt::runtime::Runtime; use libimagentrytag::tagable::Tagable; +use libimagentrytag::tag::Tag; use libimagstore::storeid::build_entry_path; use libimagerror::trace::trace_error; +use libimagentrytag::ui::{get_add_tags, get_remove_tags}; mod ui; @@ -41,9 +43,8 @@ fn main() { .subcommand_name() .map_or_else( || { - let add = rt.cli().values_of("add").map(|o| o.map(String::from)); - let rem = rt.cli().values_of("remove").map(|o| o.map(String::from)); - + let add = get_add_tags(rt.cli()); + let rem = get_remove_tags(rt.cli()); alter(&rt, id, add, rem); }, |name| { @@ -58,7 +59,7 @@ fn main() { }); } -fn alter>(rt: &Runtime, id: &str, add: Option, rem: Option) { +fn alter(rt: &Runtime, id: &str, add: Option>, rem: Option>) { let path = { match build_entry_path(rt.store(), id) { Err(e) => { From 227acd492ce15ca9c7e56f5ca860d781a8c9622c Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Thu, 19 May 2016 17:33:28 +0200 Subject: [PATCH 108/288] Shorten code in get_add_tags() --- libimagentrytag/src/ui.rs | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/libimagentrytag/src/ui.rs b/libimagentrytag/src/ui.rs index 70b9337e..f2b61d75 100644 --- a/libimagentrytag/src/ui.rs +++ b/libimagentrytag/src/ui.rs @@ -66,13 +66,9 @@ pub fn tag_argument_name() -> &'static str { /// /// Returns none if the argument was not specified pub fn get_add_tags(matches: &ArgMatches) -> Option> { - if let Some(v) = extract_tags(matches, tag_subcommand_add_arg_name(), '+') { - return Some(v); - } else { - matches - .values_of(tag_subcommand_add_arg_name()) - .map(|values| values.map(String::from).collect()) - } + let add = tag_subcommand_add_arg_name(); + extract_tags(matches, add, '+') + .or_else(|| matches.values_of(add).map(|values| values.map(String::from).collect())) } /// Get the tags which should be removed from the commandline From 397a82f52844029604c6f5944817067217f64675 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Thu, 19 May 2016 17:33:38 +0200 Subject: [PATCH 109/288] Shorten code in get_remove_tags() --- libimagentrytag/src/ui.rs | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/libimagentrytag/src/ui.rs b/libimagentrytag/src/ui.rs index f2b61d75..29cf8bc8 100644 --- a/libimagentrytag/src/ui.rs +++ b/libimagentrytag/src/ui.rs @@ -75,13 +75,9 @@ pub fn get_add_tags(matches: &ArgMatches) -> Option> { /// /// Returns none if the argument was not specified pub fn get_remove_tags(matches: &ArgMatches) -> Option> { - if let Some(v) = extract_tags(matches, tag_subcommand_remove_arg_name(), '-') { - return Some(v); - } else { - matches - .values_of(tag_subcommand_remove_arg_name()) - .map(|values| values.map(String::from).collect()) - } + let rem = tag_subcommand_remove_arg_name(); + extract_tags(matches, rem, '+') + .or_else(|| matches.values_of(rem).map(|values| values.map(String::from).collect())) } fn extract_tags(matches: &ArgMatches, specifier: &str, specchar: char) -> Option> { From 62cd7871a295741ad54af50cd1429d42648c2b4a Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Thu, 19 May 2016 16:58:42 +0200 Subject: [PATCH 110/288] Expand error generating to be able to generate modules --- libimagerror/src/error_gen.rs | 83 ++++++++++++++++++++++++++++++++--- 1 file changed, 77 insertions(+), 6 deletions(-) diff --git a/libimagerror/src/error_gen.rs b/libimagerror/src/error_gen.rs index 471c6362..2f22078a 100644 --- a/libimagerror/src/error_gen.rs +++ b/libimagerror/src/error_gen.rs @@ -1,3 +1,22 @@ +#[macro_export] +macro_rules! generate_error_imports { + () => { + use std::error::Error; + use std::fmt::Error as FmtError; + use std::fmt::{Display, Formatter}; + } +} + +#[macro_export] +macro_rules! generate_error_module { + ( $exprs:item ) => { + pub mod error { + generate_error_imports!(); + $exprs + } + } +} + #[macro_export] macro_rules! generate_error_types { ( @@ -71,16 +90,17 @@ macro_rules! generate_error_types { #[cfg(test)] mod test { - use std::error::Error; - use std::fmt::Error as FmtError; - use std::fmt::{Display, Formatter}; - generate_error_types!(TestError, TestErrorKind, - TestErrorKindA => "testerrorkind a", - TestErrorKindB => "testerrorkind B"); + generate_error_module!( + generate_error_types!(TestError, TestErrorKind, + TestErrorKindA => "testerrorkind a", + TestErrorKindB => "testerrorkind B"); + ); #[test] fn test_a() { + use self::error::{TestError, TestErrorKind}; + let kind = TestErrorKind::TestErrorKindA; assert_eq!(String::from("testerrorkind a"), format!("{}", kind)); @@ -90,6 +110,8 @@ mod test { #[test] fn test_b() { + use self::error::{TestError, TestErrorKind}; + let kind = TestErrorKind::TestErrorKindB; assert_eq!(String::from("testerrorkind B"), format!("{}", kind)); @@ -100,6 +122,55 @@ mod test { #[test] fn test_ab() { + use std::error::Error; + use self::error::{TestError, TestErrorKind}; + + let kinda = TestErrorKind::TestErrorKindA; + let kindb = TestErrorKind::TestErrorKindB; + assert_eq!(String::from("testerrorkind a"), format!("{}", kinda)); + assert_eq!(String::from("testerrorkind B"), format!("{}", kindb)); + + let e = TestError::new(kinda, Some(Box::new(TestError::new(kindb, None)))); + assert_eq!(String::from("[testerrorkind a]"), format!("{}", e)); + assert_eq!(TestErrorKind::TestErrorKindA, e.err_type()); + assert_eq!(String::from("[testerrorkind B]"), format!("{}", e.cause().unwrap())); + } + + pub mod anothererrormod { + generate_error_imports!(); + generate_error_types!(TestError, TestErrorKind, + TestErrorKindA => "testerrorkind a", + TestErrorKindB => "testerrorkind B"); + } + + #[test] + fn test_other_a() { + use self::anothererrormod::{TestError, TestErrorKind}; + + let kind = TestErrorKind::TestErrorKindA; + assert_eq!(String::from("testerrorkind a"), format!("{}", kind)); + + let e = TestError::new(kind, None); + assert_eq!(String::from("[testerrorkind a]"), format!("{}", e)); + } + + #[test] + fn test_other_b() { + use self::anothererrormod::{TestError, TestErrorKind}; + + let kind = TestErrorKind::TestErrorKindB; + assert_eq!(String::from("testerrorkind B"), format!("{}", kind)); + + let e = TestError::new(kind, None); + assert_eq!(String::from("[testerrorkind B]"), format!("{}", e)); + + } + + #[test] + fn test_other_ab() { + use std::error::Error; + use self::anothererrormod::{TestError, TestErrorKind}; + let kinda = TestErrorKind::TestErrorKindA; let kindb = TestErrorKind::TestErrorKindB; assert_eq!(String::from("testerrorkind a"), format!("{}", kinda)); From 0315b93c04050909a769c75d735ed71ec8d52b98 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Thu, 19 May 2016 17:05:14 +0200 Subject: [PATCH 111/288] imag-store: Replace error module imports with macro helper --- imag-store/src/error.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/imag-store/src/error.rs b/imag-store/src/error.rs index 472070f2..f68d5dc0 100644 --- a/imag-store/src/error.rs +++ b/imag-store/src/error.rs @@ -1,6 +1,4 @@ -use std::error::Error; -use std::fmt::Error as FmtError; -use std::fmt::{Display, Formatter}; +generate_error_imports!(); generate_error_types!(StoreError, StoreErrorKind, BackendError => "Backend Error", From ddcdaca3e825a350a22f0f0d9d9dd83e0accc901 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Thu, 19 May 2016 17:05:14 +0200 Subject: [PATCH 112/288] imag-view: Replace error module imports with macro helper --- imag-view/src/error.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/imag-view/src/error.rs b/imag-view/src/error.rs index 64aa071d..077bb9f4 100644 --- a/imag-view/src/error.rs +++ b/imag-view/src/error.rs @@ -1,6 +1,4 @@ -use std::error::Error; -use std::fmt::Error as FmtError; -use std::fmt::{Display, Formatter}; +generate_error_imports!(); generate_error_types!(ViewError, ViewErrorKind, StoreError => "Store error", From 22e015b8fd5805dcfbfde4308e79f4b82224be92 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Thu, 19 May 2016 17:05:14 +0200 Subject: [PATCH 113/288] libimagcounter: Replace error module imports with macro helper --- libimagcounter/src/error.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/libimagcounter/src/error.rs b/libimagcounter/src/error.rs index f2e11eeb..d3858d33 100644 --- a/libimagcounter/src/error.rs +++ b/libimagcounter/src/error.rs @@ -1,6 +1,4 @@ -use std::error::Error; -use std::fmt::Error as FmtError; -use std::fmt::{Display, Formatter}; +generate_error_imports!(); generate_error_types!(CounterError, CounterErrorKind, StoreReadError => "Store read error", From 91f26220c65d61ad91a16e4d6befe839b971cc59 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Thu, 19 May 2016 17:05:14 +0200 Subject: [PATCH 114/288] libimagentrylink: Replace error module imports with macro helper --- libimagentrylink/src/error.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/libimagentrylink/src/error.rs b/libimagentrylink/src/error.rs index b587b0ef..4cd28512 100644 --- a/libimagentrylink/src/error.rs +++ b/libimagentrylink/src/error.rs @@ -1,6 +1,4 @@ -use std::error::Error; -use std::fmt::Error as FmtError; -use std::fmt::{Display, Formatter}; +generate_error_imports!(); generate_error_types!(LinkError, LinkErrorKind, EntryHeaderReadError => "Error while reading an entry header", From fb79aedbd29a40d8160828fc880774f62bc2dadb Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Thu, 19 May 2016 17:05:14 +0200 Subject: [PATCH 115/288] libimagentrylist: Replace error module imports with macro helper --- libimagentrylist/src/error.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/libimagentrylist/src/error.rs b/libimagentrylist/src/error.rs index 15640042..d9843280 100644 --- a/libimagentrylist/src/error.rs +++ b/libimagentrylist/src/error.rs @@ -1,6 +1,4 @@ -use std::error::Error; -use std::fmt::Error as FmtError; -use std::fmt::{Display, Formatter}; +generate_error_imports!(); generate_error_types!(ListError, ListErrorKind, FormatError => "FormatError", From be3d39a65c02f941772046d3413b9384f8f7d464 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Thu, 19 May 2016 17:05:14 +0200 Subject: [PATCH 116/288] libimagentrytag: Replace error module imports with macro helper --- libimagentrytag/src/error.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/libimagentrytag/src/error.rs b/libimagentrytag/src/error.rs index 5be68b90..0e8aa3e7 100644 --- a/libimagentrytag/src/error.rs +++ b/libimagentrytag/src/error.rs @@ -1,6 +1,4 @@ -use std::error::Error; -use std::fmt::Error as FmtError; -use std::fmt::{Display, Formatter}; +generate_error_imports!(); generate_error_types!(TagError, TagErrorKind, TagTypeError => "Entry Header Tag Type wrong", From 128bb73a204c66d7a7aabaa57005286129bc1647 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Thu, 19 May 2016 17:05:14 +0200 Subject: [PATCH 117/288] libimagentryview: Replace error module imports with macro helper --- libimagentryview/src/error.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/libimagentryview/src/error.rs b/libimagentryview/src/error.rs index 32982342..4f4889d1 100644 --- a/libimagentryview/src/error.rs +++ b/libimagentryview/src/error.rs @@ -1,6 +1,4 @@ -use std::error::Error; -use std::fmt::Error as FmtError; -use std::fmt::{Display, Formatter}; +generate_error_imports!(); generate_error_types!(ViewError, ViewErrorKind, Unknown => "Unknown view error" From 81d46f9e74a47d8081a37424eb4dc862df9fe1f5 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Thu, 19 May 2016 17:05:14 +0200 Subject: [PATCH 118/288] libimaginteraction: Replace error module imports with macro helper --- libimaginteraction/src/error.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/libimaginteraction/src/error.rs b/libimaginteraction/src/error.rs index a85c9b25..dd3b5807 100644 --- a/libimaginteraction/src/error.rs +++ b/libimaginteraction/src/error.rs @@ -1,6 +1,4 @@ -use std::error::Error; -use std::fmt::Error as FmtError; -use std::fmt::{Display, Formatter}; +generate_error_imports!(); generate_error_types!(InteractionError, InteractionErrorKind, Unknown => "Unknown Error" From c88d5b308f59f44b6c561e6053edffd746912b0c Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Thu, 19 May 2016 17:05:14 +0200 Subject: [PATCH 119/288] libimagnotes: Replace error module imports with macro helper --- libimagnotes/src/error.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/libimagnotes/src/error.rs b/libimagnotes/src/error.rs index 527aa710..d5659622 100644 --- a/libimagnotes/src/error.rs +++ b/libimagnotes/src/error.rs @@ -1,6 +1,4 @@ -use std::error::Error; -use std::fmt::Error as FmtError; -use std::fmt::{Display, Formatter}; +generate_error_imports!(); generate_error_types!(NoteError, NoteErrorKind, StoreWriteError => "Error writing store", From 1dbfb7cf2891138f5ae7b5748e653b9c120c6695 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Thu, 19 May 2016 17:05:14 +0200 Subject: [PATCH 120/288] libimagrt: Replace error module imports with macro helper --- libimagrt/src/error.rs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/libimagrt/src/error.rs b/libimagrt/src/error.rs index 93752552..50d640d7 100644 --- a/libimagrt/src/error.rs +++ b/libimagrt/src/error.rs @@ -1,7 +1,4 @@ -use std::error::Error; -use std::fmt::Display; -use std::fmt::Formatter; -use std::fmt::Error as FmtError; +generate_error_imports!(); use std::io::Error as IOError; generate_error_types!(RuntimeError, RuntimeErrorKind, From cc8642f54f4e9f49b00cc5ffcb3aab4b77aabc6e Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Thu, 19 May 2016 17:05:14 +0200 Subject: [PATCH 121/288] libimagstore: Replace error module imports with macro helper --- libimagstore/src/error.rs | 4 +--- libimagstore/src/hook/error.rs | 4 +--- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/libimagstore/src/error.rs b/libimagstore/src/error.rs index ad36963e..3e32bf96 100644 --- a/libimagstore/src/error.rs +++ b/libimagstore/src/error.rs @@ -1,6 +1,4 @@ -use std::error::Error; -use std::fmt::Error as FmtError; -use std::fmt::{Display, Formatter}; +generate_error_imports!(); use std::convert::From; generate_error_types!(StoreError, StoreErrorKind, diff --git a/libimagstore/src/hook/error.rs b/libimagstore/src/hook/error.rs index ec06dd98..e55c2b8f 100644 --- a/libimagstore/src/hook/error.rs +++ b/libimagstore/src/hook/error.rs @@ -1,6 +1,4 @@ -use std::error::Error; -use std::fmt::Error as FmtError; -use std::fmt::{Display, Formatter}; +generate_error_imports!(); use std::convert::Into; generate_error_types!(HookError, HookErrorKind, From 6bc5099accf8a1404d74700ba128512f0d217516 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Thu, 19 May 2016 17:11:18 +0200 Subject: [PATCH 122/288] imag-store: use generate_error_module!() macro and reexport generated types --- imag-store/src/error.rs | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/imag-store/src/error.rs b/imag-store/src/error.rs index f68d5dc0..ae9162f0 100644 --- a/imag-store/src/error.rs +++ b/imag-store/src/error.rs @@ -1,7 +1,10 @@ -generate_error_imports!(); - -generate_error_types!(StoreError, StoreErrorKind, - BackendError => "Backend Error", - NoCommandlineCall => "No commandline call" +generate_error_module!( + generate_error_types!(StoreError, StoreErrorKind, + BackendError => "Backend Error", + NoCommandlineCall => "No commandline call" + ); ); +pub use self::error::StoreError; +pub use self::error::StoreErrorKind; + From 537fe88e13f0356bcf54f1f2109ca812097914a0 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Thu, 19 May 2016 17:11:18 +0200 Subject: [PATCH 123/288] imag-view: use generate_error_module!() macro and reexport generated types --- imag-view/src/error.rs | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/imag-view/src/error.rs b/imag-view/src/error.rs index 077bb9f4..77c7b95d 100644 --- a/imag-view/src/error.rs +++ b/imag-view/src/error.rs @@ -1,9 +1,12 @@ -generate_error_imports!(); - -generate_error_types!(ViewError, ViewErrorKind, - StoreError => "Store error", - NoVersion => "No version specified", - PatternError => "Error in Pattern", - GlobBuildError => "Could not build glob() Argument" +generate_error_module!( + generate_error_types!(ViewError, ViewErrorKind, + StoreError => "Store error", + NoVersion => "No version specified", + PatternError => "Error in Pattern", + GlobBuildError => "Could not build glob() Argument" + ); ); +pub use self::error::ViewError; +pub use self::error::ViewErrorKind; + From d3dc4eb57d77a7d77131986466a6c13014042f41 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Thu, 19 May 2016 17:11:18 +0200 Subject: [PATCH 124/288] libimagcounter: use generate_error_module!() macro and reexport generated types --- libimagcounter/src/error.rs | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/libimagcounter/src/error.rs b/libimagcounter/src/error.rs index d3858d33..e8016fb6 100644 --- a/libimagcounter/src/error.rs +++ b/libimagcounter/src/error.rs @@ -1,9 +1,12 @@ -generate_error_imports!(); - -generate_error_types!(CounterError, CounterErrorKind, - StoreReadError => "Store read error", - StoreWriteError => "Store write error", - HeaderTypeError => "Header type error", - HeaderFieldMissingError => "Header field missing error" +generate_error_module!( + generate_error_types!(CounterError, CounterErrorKind, + StoreReadError => "Store read error", + StoreWriteError => "Store write error", + HeaderTypeError => "Header type error", + HeaderFieldMissingError => "Header field missing error" + ); ); +pub use self::error::CounterError; +pub use self::error::CounterErrorKind; + From cf393b4bde2d36bf30b438692f8535c5e6420151 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Thu, 19 May 2016 17:11:18 +0200 Subject: [PATCH 125/288] libimagentrylink: use generate_error_module!() macro and reexport generated types --- libimagentrylink/src/error.rs | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/libimagentrylink/src/error.rs b/libimagentrylink/src/error.rs index 4cd28512..2802c414 100644 --- a/libimagentrylink/src/error.rs +++ b/libimagentrylink/src/error.rs @@ -1,13 +1,16 @@ -generate_error_imports!(); - -generate_error_types!(LinkError, LinkErrorKind, - EntryHeaderReadError => "Error while reading an entry header", - EntryHeaderWriteError => "Error while writing an entry header", - ExistingLinkTypeWrong => "Existing link entry has wrong type", - LinkTargetDoesNotExist => "Link target does not exist in the store", - InternalConversionError => "Error while converting values internally", - InvalidUri => "URI is not valid", - StoreReadError => "Store read error", - StoreWriteError => "Store write error" +generate_error_module!( + generate_error_types!(LinkError, LinkErrorKind, + EntryHeaderReadError => "Error while reading an entry header", + EntryHeaderWriteError => "Error while writing an entry header", + ExistingLinkTypeWrong => "Existing link entry has wrong type", + LinkTargetDoesNotExist => "Link target does not exist in the store", + InternalConversionError => "Error while converting values internally", + InvalidUri => "URI is not valid", + StoreReadError => "Store read error", + StoreWriteError => "Store write error" + ); ); +pub use self::error::LinkError; +pub use self::error::LinkErrorKind; + From 698c219e04677654be45849fe0a73429860d7e51 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Thu, 19 May 2016 17:11:18 +0200 Subject: [PATCH 126/288] libimagentrylist: use generate_error_module!() macro and reexport generated types --- libimagentrylist/src/error.rs | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/libimagentrylist/src/error.rs b/libimagentrylist/src/error.rs index d9843280..2cd5cde5 100644 --- a/libimagentrylist/src/error.rs +++ b/libimagentrylist/src/error.rs @@ -1,9 +1,12 @@ -generate_error_imports!(); - -generate_error_types!(ListError, ListErrorKind, - FormatError => "FormatError", - EntryError => "EntryError", - IterationError => "IterationError", - CLIError => "No CLI subcommand for listing entries" +generate_error_module!( + generate_error_types!(ListError, ListErrorKind, + FormatError => "FormatError", + EntryError => "EntryError", + IterationError => "IterationError", + CLIError => "No CLI subcommand for listing entries" + ); ); +pub use self::error::ListError; +pub use self::error::ListErrorKind; + From b624ba9c06cb8fbbfe601576e1a99afa8f866b6b Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Thu, 19 May 2016 17:11:18 +0200 Subject: [PATCH 127/288] libimagentrytag: use generate_error_module!() macro and reexport generated types --- libimagentrytag/src/error.rs | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/libimagentrytag/src/error.rs b/libimagentrytag/src/error.rs index 0e8aa3e7..45895019 100644 --- a/libimagentrytag/src/error.rs +++ b/libimagentrytag/src/error.rs @@ -1,9 +1,12 @@ -generate_error_imports!(); - -generate_error_types!(TagError, TagErrorKind, - TagTypeError => "Entry Header Tag Type wrong", - HeaderReadError => "Error while reading entry header", - HeaderWriteError => "Error while writing entry header", - NotATag => "String is not a tag" +generate_error_module!( + generate_error_types!(TagError, TagErrorKind, + TagTypeError => "Entry Header Tag Type wrong", + HeaderReadError => "Error while reading entry header", + HeaderWriteError => "Error while writing entry header", + NotATag => "String is not a tag" + ); ); +pub use self::error::TagError; +pub use self::error::TagErrorKind; + From 21dfa9fba2e4aef994c2b636e081acd99a2c1e52 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Thu, 19 May 2016 17:11:18 +0200 Subject: [PATCH 128/288] libimagentryview: use generate_error_module!() macro and reexport generated types --- libimagentryview/src/error.rs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/libimagentryview/src/error.rs b/libimagentryview/src/error.rs index 4f4889d1..e54d2fcc 100644 --- a/libimagentryview/src/error.rs +++ b/libimagentryview/src/error.rs @@ -1,6 +1,9 @@ -generate_error_imports!(); - -generate_error_types!(ViewError, ViewErrorKind, - Unknown => "Unknown view error" +generate_error_module!( + generate_error_types!(ViewError, ViewErrorKind, + Unknown => "Unknown view error" + ); ); +pub use self::error::ViewError; +pub use self::error::ViewErrorKind; + From d2fa853a08181e540b0abae3da250334cc59b598 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Thu, 19 May 2016 17:11:18 +0200 Subject: [PATCH 129/288] libimaginteraction: use generate_error_module!() macro and reexport generated types --- libimaginteraction/src/error.rs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/libimaginteraction/src/error.rs b/libimaginteraction/src/error.rs index dd3b5807..9285f0fd 100644 --- a/libimaginteraction/src/error.rs +++ b/libimaginteraction/src/error.rs @@ -1,6 +1,9 @@ -generate_error_imports!(); - -generate_error_types!(InteractionError, InteractionErrorKind, - Unknown => "Unknown Error" +generate_error_module!( + generate_error_types!(InteractionError, InteractionErrorKind, + Unknown => "Unknown Error" + ); ); +pub use self::error::InteractionError; +pub use self::error::InteractionErrorKind; + From bfa1fc5c875570c8f251dcb6cf02e3c8fbe1cfbd Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Thu, 19 May 2016 17:11:18 +0200 Subject: [PATCH 130/288] libimagnotes: use generate_error_module!() macro and reexport generated types --- libimagnotes/src/error.rs | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/libimagnotes/src/error.rs b/libimagnotes/src/error.rs index d5659622..bbb02d0c 100644 --- a/libimagnotes/src/error.rs +++ b/libimagnotes/src/error.rs @@ -1,9 +1,12 @@ -generate_error_imports!(); - -generate_error_types!(NoteError, NoteErrorKind, - StoreWriteError => "Error writing store", - StoreReadError => "Error reading store", - HeaderTypeError => "Header type error", - NoteToEntryConversion => "Error converting Note instance to Entry instance" +generate_error_module!( + generate_error_types!(NoteError, NoteErrorKind, + StoreWriteError => "Error writing store", + StoreReadError => "Error reading store", + HeaderTypeError => "Header type error", + NoteToEntryConversion => "Error converting Note instance to Entry instance" + ); ); +pub use self::error::NoteError; +pub use self::error::NoteErrorKind; + From 8e0014d5079fc1b5d0036965b8fa452038a79e11 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Mon, 16 May 2016 23:51:13 +0200 Subject: [PATCH 131/288] Add IntoError trait to convert Error kinds into Error instances --- libimagerror/src/into.rs | 14 ++++++++++++++ libimagerror/src/lib.rs | 1 + 2 files changed, 15 insertions(+) create mode 100644 libimagerror/src/into.rs diff --git a/libimagerror/src/into.rs b/libimagerror/src/into.rs new file mode 100644 index 00000000..a959abd4 --- /dev/null +++ b/libimagerror/src/into.rs @@ -0,0 +1,14 @@ +use std::error::Error; + +/// Trait to help converting Error kinds into Error instances +pub trait IntoError { + type Target: Error; + + /// Convert the type into an error with no cause + fn into_error(self) -> Self::Target; + + /// Convert the type into an error with cause + fn into_error_with_cause(self, cause: Box) -> Self::Target; + +} + diff --git a/libimagerror/src/lib.rs b/libimagerror/src/lib.rs index d7f374a7..1d1f75e2 100644 --- a/libimagerror/src/lib.rs +++ b/libimagerror/src/lib.rs @@ -1,5 +1,6 @@ #[macro_use] extern crate log; extern crate ansi_term; +pub mod into; pub mod error_gen; pub mod trace; From 3845f28dad3e94166dbcc4658f14e6465c558d5a Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Mon, 16 May 2016 23:51:26 +0200 Subject: [PATCH 132/288] Implement IntoError for all generated Errors automatically --- libimagerror/src/error_gen.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/libimagerror/src/error_gen.rs b/libimagerror/src/error_gen.rs index 2f22078a..f54334e4 100644 --- a/libimagerror/src/error_gen.rs +++ b/libimagerror/src/error_gen.rs @@ -1,3 +1,5 @@ +use into::IntoError; + #[macro_export] macro_rules! generate_error_imports { () => { @@ -41,6 +43,19 @@ macro_rules! generate_error_types { } + impl IntoError for $kindname { + type Target = $name; + + fn into_error(self) -> Self::Target { + $name::new(self, None) + } + + fn into_error_with_cause(self, cause: Box) -> Self::Target { + $name::new(self, Some(cause)) + } + + } + #[derive(Debug)] pub struct $name { err_type: $kindname, From 972d313ed545df6ce1d8f8f2d949791b9da70903 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Fri, 20 May 2016 17:11:51 +0200 Subject: [PATCH 133/288] Import IntoError trait --- libimagerror/src/error_gen.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/libimagerror/src/error_gen.rs b/libimagerror/src/error_gen.rs index f54334e4..e88da514 100644 --- a/libimagerror/src/error_gen.rs +++ b/libimagerror/src/error_gen.rs @@ -6,6 +6,8 @@ macro_rules! generate_error_imports { use std::error::Error; use std::fmt::Error as FmtError; use std::fmt::{Display, Formatter}; + + use $crate::into::IntoError; } } From bf14b9ae4e6c7d7975dca3ec4c886e7f877e1a49 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Mon, 23 May 2016 13:37:26 +0200 Subject: [PATCH 134/288] Update dependency: fs2 0.2.2 -> 0.2.* --- libimagstore/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libimagstore/Cargo.toml b/libimagstore/Cargo.toml index 72d068d5..25001ed4 100644 --- a/libimagstore/Cargo.toml +++ b/libimagstore/Cargo.toml @@ -4,7 +4,7 @@ version = "0.1.0" authors = ["Matthias Beyer "] [dependencies] -fs2 = "0.2.2" +fs2 = "0.2" glob = "0.2.11" lazy_static = "0.1.15" log = "0.3" From 5959b6b3cb236ca7f5f432627af029c93a315a77 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Mon, 23 May 2016 13:37:36 +0200 Subject: [PATCH 135/288] Update dependency: fs2 0.2.2 -> 0.2.* --- libimagstorestdhook/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libimagstorestdhook/Cargo.toml b/libimagstorestdhook/Cargo.toml index 789fc053..31a1e790 100644 --- a/libimagstorestdhook/Cargo.toml +++ b/libimagstorestdhook/Cargo.toml @@ -6,7 +6,7 @@ authors = ["Matthias Beyer "] [dependencies] toml = "0.1.25" log = "0.3" -fs2 = "0.2.3" +fs2 = "0.2" [dependencies.libimagstore] path = "../libimagstore" From b4f17576f6c09686779204e64a759073dfb36983 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Thu, 12 May 2016 14:52:33 +0200 Subject: [PATCH 136/288] Add Store::get() for getting or failing if entry does not exist --- libimagstore/src/store.rs | 42 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) diff --git a/libimagstore/src/store.rs b/libimagstore/src/store.rs index 53cd60ca..dbb37474 100644 --- a/libimagstore/src/store.rs +++ b/libimagstore/src/store.rs @@ -324,6 +324,9 @@ impl Store { /// Borrow a given Entry. When the `FileLockEntry` is either `update`d or /// dropped, the new Entry is written to disk + /// + /// Implicitely creates a entry in the store if there is no entry with the id `id`. For a + /// non-implicitely-create look at `Store::get`. pub fn retrieve<'a, S: IntoStoreId>(&'a self, id: S) -> Result> { let id = self.storify_id(id.into_storeid()); if let Err(e) = self.execute_hooks_for_id(self.pre_retrieve_aspects.clone(), &id) { @@ -345,7 +348,44 @@ impl Store { .map_err(|e| SE::new(SEK::HookExecutionError, Some(Box::new(e)))) .and(Ok(fle)) }) - } + } + + /// Get an entry from the store if it exists. + /// + /// This executes the {pre,post}_retrieve_aspects hooks. + pub fn get<'a, S: IntoStoreId>(&'a self, id: S) -> Result>> + { + let id = self.storify_id(id.into_storeid()); + if let Err(e) = self.execute_hooks_for_id(self.pre_retrieve_aspects.clone(), &id) { + return Err(e); + } + + let mut entries = match self.entries.write() { + // Loosing the error here + Err(_) => return Err(SE::new(SEK::LockPoisoned, None)), + Ok(e) => e, + }; + + let mut se = match entries.get_mut(&id) { + Some(e) => e, + None => return Ok(None), + }; + + let entry = match se.get_entry() { + Ok(e) => e, + Err(e) => return Err(e), + }; + + se.status = StoreEntryStatus::Borrowed; + + let mut fle = FileLockEntry::new(self, entry, id); + + if let Err(e) = self.execute_hooks_for_mut_file(self.post_retrieve_aspects.clone(), &mut fle) { + Err(SE::new(SEK::HookExecutionError, Some(Box::new(e)))) + } else { + Ok(Some(fle)) + } + } /// Iterate over all StoreIds for one module name pub fn retrieve_for_module(&self, mod_name: &str) -> Result { From df33dec0c37e65bafebe8bc9dd3579390c48d925 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Thu, 12 May 2016 15:03:57 +0200 Subject: [PATCH 137/288] Add new error kind: StorePathError --- libimagstore/src/error.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/libimagstore/src/error.rs b/libimagstore/src/error.rs index 3e32bf96..dda0f9fd 100644 --- a/libimagstore/src/error.rs +++ b/libimagstore/src/error.rs @@ -28,7 +28,8 @@ generate_error_types!(StoreError, StoreErrorKind, PostHookExecuteError => "Post-Hook execution error", StorePathLacksVersion => "The supplied store path has no version part", GlobError => "glob() error", - EncodingError => "Encoding error" + EncodingError => "Encoding error", + StorePathError => "Store Path error" ); generate_error_types!(ParserError, ParserErrorKind, From 839ec051a4ace34113930435a5844dbad963c2fb Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Thu, 12 May 2016 15:04:18 +0200 Subject: [PATCH 138/288] Add Store::get_all_versions() for getting all versions of a StoreId entry --- libimagstore/src/store.rs | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/libimagstore/src/store.rs b/libimagstore/src/store.rs index dbb37474..cf3f3be2 100644 --- a/libimagstore/src/store.rs +++ b/libimagstore/src/store.rs @@ -387,6 +387,45 @@ impl Store { } } + /// Same as `Store::get()` but also tries older versions of the entry, returning an iterator + /// over all versions of the entry. + pub fn get_all_versions<'a, S: IntoStoreId>(&'a self, id: S) -> Result + { + // get PathBuf component from storeid, but not version component + fn path_component(id: S) -> Result { + let p : PathBuf = id.into_storeid().into(); + match p.to_str() { + Some(s) => { + let mut split = s.split("~"); + let path_element = match split.next() { + Some(s) => s, + None => return Err(SE::new(SEK::StorePathError, None)), + }; + + Ok(PathBuf::from(path_element)) + }, + + None => Err(SE::new(SEK::StorePathError, None)), + } + } + + fn build_glob_pattern(mut pb: PathBuf) -> Option { + pb.push("~*.*.*"); + pb.to_str().map(String::from) + } + + match path_component(id).map(build_glob_pattern) { + Err(e) => Err(SE::new(SEK::StorePathError, Some(Box::new(e)))), + Ok(None) => Err(SE::new(SEK::StorePathError, None)), + Ok(Some(pattern)) => { + glob(&pattern[..]) + .map(|paths| GlobStoreIdIterator::new(paths).into()) + .map_err(|e| SE::new(SEK::GlobError, Some(Box::new(e)))) + } + } + + } + /// Iterate over all StoreIds for one module name pub fn retrieve_for_module(&self, mod_name: &str) -> Result { let mut path = self.path().clone(); From dd7e146081e91b2575a5f5865f9f67c25d219076 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Fri, 13 May 2016 14:48:20 +0200 Subject: [PATCH 139/288] impl Into for GlobStoreIdIterator to be able to convert easily --- libimagstore/src/store.rs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/libimagstore/src/store.rs b/libimagstore/src/store.rs index cf3f3be2..b7013b4d 100644 --- a/libimagstore/src/store.rs +++ b/libimagstore/src/store.rs @@ -438,7 +438,8 @@ impl Store { debug!("glob()ing with '{}'", path); glob(&path[..]).map_err(|e| SE::new(SEK::GlobError, Some(Box::new(e)))) }) - .map(|paths| StoreIdIterator::new(Box::new(GlobStoreIdIterator::new(paths)))) + .map(|paths| GlobStoreIdIterator::new(paths).into()) + .map_err(|e| SE::new(SEK::GlobError, Some(Box::new(e)))) } // Walk the store tree for the module @@ -1299,6 +1300,7 @@ mod glob_store_iter { use std::fmt::Error as FmtError; use glob::Paths; use storeid::StoreId; + use storeid::StoreIdIterator; pub struct GlobStoreIdIterator { paths: Paths, @@ -1312,6 +1314,14 @@ mod glob_store_iter { } + impl Into for GlobStoreIdIterator { + + fn into(self) -> StoreIdIterator { + StoreIdIterator::new(Box::new(self)) + } + + } + impl GlobStoreIdIterator { pub fn new(paths: Paths) -> GlobStoreIdIterator { From b4b3a0ede852007d557ef31911756c3786c21daa Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Fri, 22 Apr 2016 15:06:44 +0200 Subject: [PATCH 140/288] Only warn if there is no config file --- libimagrt/src/runtime.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/libimagrt/src/runtime.rs b/libimagrt/src/runtime.rs index 5087d063..57540b76 100644 --- a/libimagrt/src/runtime.rs +++ b/libimagrt/src/runtime.rs @@ -75,7 +75,8 @@ impl<'a> Runtime<'a> { let cause : Option> = Some(Box::new(e)); return Err(RuntimeError::new(RuntimeErrorKind::Instantiate, cause)); } else { - trace_error(&e); + warn!("No config file found."); + warn!("Continuing without configuration file"); None }, From 603b4de5939e376660fdef556b77168d868e4f79 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Tue, 17 May 2016 00:14:00 +0200 Subject: [PATCH 141/288] Add macro to generate error types with custom fields and functions --- libimagerror/src/error_gen.rs | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/libimagerror/src/error_gen.rs b/libimagerror/src/error_gen.rs index e88da514..e32feedb 100644 --- a/libimagerror/src/error_gen.rs +++ b/libimagerror/src/error_gen.rs @@ -22,12 +22,13 @@ macro_rules! generate_error_module { } #[macro_export] -macro_rules! generate_error_types { - ( +macro_rules! generate_custom_error_types { + { $name: ident, $kindname: ident, + $customMemberTypeName: ident, $($kind:ident => $string:expr),* - ) => { + } => { #[derive(Clone, Copy, Debug, PartialEq)] pub enum $kindname { $( $kind ),* @@ -62,6 +63,7 @@ macro_rules! generate_error_types { pub struct $name { err_type: $kindname, cause: Option>, + custom_data: Option<$customMemberTypeName>, } impl $name { @@ -70,6 +72,7 @@ macro_rules! generate_error_types { $name { err_type: errtype, cause: cause, + custom_data: None, } } @@ -105,6 +108,18 @@ macro_rules! generate_error_types { } } +#[macro_export] +macro_rules! generate_error_types { + ( + $name: ident, + $kindname: ident, + $($kind:ident => $string:expr),* + ) => { + generate_custom_error_types!($name, $kindname, members = {}, functions = {}, $($kind),*); + } +} + + #[cfg(test)] mod test { From b117d7fb9fdd36501a7f7c095333999a81e512cb Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Tue, 17 May 2016 00:14:10 +0200 Subject: [PATCH 142/288] Add tests for error types with custom functions and types --- libimagerror/src/error_gen.rs | 36 ++++++++++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/libimagerror/src/error_gen.rs b/libimagerror/src/error_gen.rs index e32feedb..c715eb13 100644 --- a/libimagerror/src/error_gen.rs +++ b/libimagerror/src/error_gen.rs @@ -115,7 +115,11 @@ macro_rules! generate_error_types { $kindname: ident, $($kind:ident => $string:expr),* ) => { - generate_custom_error_types!($name, $kindname, members = {}, functions = {}, $($kind),*); + #[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Copy)] + pub struct SomeNotExistingTypeWithATypeNameNoOneWillEverChoose {} + generate_custom_error_types!($name, $kindname, + SomeNotExistingTypeWithATypeNameNoOneWillEverChoose, + $($kind => $string),*); } } @@ -129,6 +133,36 @@ mod test { TestErrorKindB => "testerrorkind B"); ); + #[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Copy)] + pub struct CustomData { + pub test: i32, + pub othr: i64, + } + + generate_error_imports!(); + + generate_custom_error_types!(CustomTestError, CustomTestErrorKind, + CustomData, + CustomErrorKindA => "customerrorkind a", + CustomErrorKindB => "customerrorkind B"); + + impl CustomTestError { + pub fn test(&self) -> i32 { + match self.custom_data { + Some(t) => t.test, + None => 0, + } + } + + pub fn bar(&self) -> i64 { + match self.custom_data { + Some(t) => t.othr, + None => 0, + } + } + } + + #[test] fn test_a() { use self::error::{TestError, TestErrorKind}; From e45d9200bfd45759d6a5cf02e2b639968cb5bddf Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Mon, 23 May 2016 15:21:16 +0200 Subject: [PATCH 143/288] Adapt error generating code in libimagstore --- libimagstore/src/error.rs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/libimagstore/src/error.rs b/libimagstore/src/error.rs index 3e32bf96..997da6c0 100644 --- a/libimagstore/src/error.rs +++ b/libimagstore/src/error.rs @@ -1,7 +1,10 @@ generate_error_imports!(); use std::convert::From; -generate_error_types!(StoreError, StoreErrorKind, +#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Copy)] +pub struct CustomErrorData {} + +generate_custom_error_types!(StoreError, StoreErrorKind, CustomErrorData, ConfigurationError => "Store Configuration Error", FileError => "File Error", IoError => "IO Error", @@ -31,7 +34,7 @@ generate_error_types!(StoreError, StoreErrorKind, EncodingError => "Encoding error" ); -generate_error_types!(ParserError, ParserErrorKind, +generate_custom_error_types!(ParserError, ParserErrorKind, CustomErrorData, TOMLParserErrors => "Several TOML-Parser-Errors", MissingMainSection => "Missing main section", MissingVersionInfo => "Missing version information in main section", @@ -44,6 +47,7 @@ impl From for StoreError { StoreError { err_type: StoreErrorKind::MalformedEntry, cause: Some(Box::new(ps)), + custom_data: None, } } } @@ -53,6 +57,7 @@ impl From<::std::io::Error> for StoreError { StoreError { err_type: StoreErrorKind::IoError, cause: Some(Box::new(ps)), + custom_data: None, } } } From 38031d5798d385eb2521e48f350509b97a3dd1b1 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Mon, 23 May 2016 19:16:05 +0200 Subject: [PATCH 144/288] Add counter in libimagentrylist::listers::Core --- libimagentrylist/src/listers/core.rs | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/libimagentrylist/src/listers/core.rs b/libimagentrylist/src/listers/core.rs index 8c7ccf72..50913258 100644 --- a/libimagentrylist/src/listers/core.rs +++ b/libimagentrylist/src/listers/core.rs @@ -27,12 +27,19 @@ impl<'a> Lister for CoreLister<'a> { use error::ListError as LE; use error::ListErrorKind as LEK; - entries.fold(Ok(()), |accu, entry| { - accu.and_then(|_| { - write!(stdout(), "{:?}\n", (self.lister)(&entry)) - .map_err(|e| LE::new(LEK::FormatError, Some(Box::new(e)))) - }) - }) + debug!("Called list()"); + let (r, n) = entries + .fold((Ok(()), 0), |(accu, i), entry| { + debug!("fold({:?}, {:?})", accu, entry); + let r = accu.and_then(|_| { + debug!("Listing Entry: {:?}", entry); + write!(stdout(), "{:?}\n", (self.lister)(&entry)) + .map_err(|e| LE::new(LEK::FormatError, Some(Box::new(e)))) + }); + (r, i + 1) + }); + debug!("Iterated over {} entries", n); + r } } From f0b665e5f214a3a526096a6b25b628a88137d42a Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sat, 14 May 2016 18:51:12 +0200 Subject: [PATCH 145/288] libimagstore: Add dependency: libimagutil --- libimagstore/Cargo.toml | 3 +++ libimagstore/src/lib.rs | 1 + 2 files changed, 4 insertions(+) diff --git a/libimagstore/Cargo.toml b/libimagstore/Cargo.toml index 72d068d5..5bba9e4a 100644 --- a/libimagstore/Cargo.toml +++ b/libimagstore/Cargo.toml @@ -18,6 +18,9 @@ walkdir = "0.1.5" [dependencies.libimagerror] path = "../libimagerror" +[dependencies.libimagutil] +path = "../libimagutil" + [dev-dependencies] tempdir = "0.3.4" env_logger = "0.3" diff --git a/libimagstore/src/lib.rs b/libimagstore/src/lib.rs index 89657283..1be684b3 100644 --- a/libimagstore/src/lib.rs +++ b/libimagstore/src/lib.rs @@ -25,6 +25,7 @@ extern crate crossbeam; extern crate walkdir; #[macro_use] extern crate libimagerror; +#[macro_use] extern crate libimagutil; pub mod storeid; pub mod error; From 0e03998499e63dd5a117c4c0c1515d2f39cce26d Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sat, 14 May 2016 19:43:20 +0200 Subject: [PATCH 146/288] libimagentrylink: Add dependency: libimagutil --- libimagentrylink/Cargo.toml | 3 +++ libimagentrylink/src/lib.rs | 1 + 2 files changed, 4 insertions(+) diff --git a/libimagentrylink/Cargo.toml b/libimagentrylink/Cargo.toml index f14869be..e4aeb4a6 100644 --- a/libimagentrylink/Cargo.toml +++ b/libimagentrylink/Cargo.toml @@ -17,3 +17,6 @@ path = "../libimagstore" [dependencies.libimagerror] path = "../libimagerror" +[dependencies.libimagutil] +path = "../libimagutil" + diff --git a/libimagentrylink/src/lib.rs b/libimagentrylink/src/lib.rs index e04b6bf4..4f3b6ee7 100644 --- a/libimagentrylink/src/lib.rs +++ b/libimagentrylink/src/lib.rs @@ -21,6 +21,7 @@ extern crate crypto; #[macro_use] extern crate libimagstore; #[macro_use] extern crate libimagerror; +#[macro_use] extern crate libimagutil; module_entry_path_mod!("links", "0.1.0"); From 394b90f03881b48f8247654c6929a2de4c927e58 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Mon, 23 May 2016 21:42:49 +0200 Subject: [PATCH 147/288] libimagentrylink: Refactor code with is_match!() macro --- libimagentrylink/src/internal.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libimagentrylink/src/internal.rs b/libimagentrylink/src/internal.rs index 16186ddb..0c6b977b 100644 --- a/libimagentrylink/src/internal.rs +++ b/libimagentrylink/src/internal.rs @@ -160,7 +160,7 @@ fn process_rw_result(links: StoreResult>) -> Result> { } }; - if !links.iter().all(|l| match *l { Value::String(_) => true, _ => false }) { + if !links.iter().all(|l| is_match!(*l, Value::String(_))) { debug!("At least one of the Values which were expected in the Array of links is a non-String!"); debug!("Generating LinkError"); return Err(LinkError::new(LinkErrorKind::ExistingLinkTypeWrong, None)); From e30d2480ab11957c077a0ad9000d3c980b8fdef2 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Mon, 23 May 2016 21:42:49 +0200 Subject: [PATCH 148/288] libimagentrytag: Refactor code with is_match!() macro --- libimagentrytag/Cargo.toml | 3 +++ libimagentrytag/src/lib.rs | 1 + libimagentrytag/src/tagable.rs | 4 ++-- 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/libimagentrytag/Cargo.toml b/libimagentrytag/Cargo.toml index 2a4e1ed2..64d62192 100644 --- a/libimagentrytag/Cargo.toml +++ b/libimagentrytag/Cargo.toml @@ -16,3 +16,6 @@ path = "../libimagstore" [dependencies.libimagerror] path = "../libimagerror" +[dependencies.libimagutil] +path = "../libimagutil" + diff --git a/libimagentrytag/src/lib.rs b/libimagentrytag/src/lib.rs index 232de3b3..87e4fe87 100644 --- a/libimagentrytag/src/lib.rs +++ b/libimagentrytag/src/lib.rs @@ -20,6 +20,7 @@ extern crate toml; extern crate libimagstore; #[macro_use] extern crate libimagerror; +#[macro_use] extern crate libimagutil; pub mod error; pub mod exec; diff --git a/libimagentrytag/src/tagable.rs b/libimagentrytag/src/tagable.rs index 6206a53e..44143d98 100644 --- a/libimagentrytag/src/tagable.rs +++ b/libimagentrytag/src/tagable.rs @@ -37,7 +37,7 @@ impl Tagable for EntryHeader { match tags { Some(Value::Array(tags)) => { - if !tags.iter().all(|t| match *t { Value::String(_) => true, _ => false }) { + if !tags.iter().all(|t| is_match!(*t, Value::String(_))) { return Err(TagError::new(TagErrorKind::TagTypeError, None)); } if tags.iter().any(|t| match *t { @@ -110,7 +110,7 @@ impl Tagable for EntryHeader { } let tags = tags.unwrap(); - if !tags.iter().all(|t| match *t { Value::String(_) => true, _ => false }) { + if !tags.iter().all(|t| is_match!(*t, Value::String(_))) { return Err(TagError::new(TagErrorKind::TagTypeError, None)); } From b6f5b71df1eca076f0b0be0c5a623d5cb122bccb Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Mon, 23 May 2016 21:42:49 +0200 Subject: [PATCH 149/288] libimagstore: Refactor code with is_match!() macro --- libimagstore/src/configuration.rs | 10 ++++------ libimagstore/src/hook/aspect.rs | 10 +++------- 2 files changed, 7 insertions(+), 13 deletions(-) diff --git a/libimagstore/src/configuration.rs b/libimagstore/src/configuration.rs index 6004a3d8..33e0a49e 100644 --- a/libimagstore/src/configuration.rs +++ b/libimagstore/src/configuration.rs @@ -128,15 +128,13 @@ pub fn config_is_valid(config: &Option) -> bool { // The section "hooks" has maps which have a key "aspect" which has a value of type // String - check_all_inner_maps_have_key_with(t, "hooks", "aspect", |asp| { - match *asp { Value::String(_) => true, _ => false } - }) && + check_all_inner_maps_have_key_with(t, "hooks", "aspect", + |asp| is_match!(asp, &Value::String(_))) && // The section "aspects" has maps which have a key "parllel" which has a value of type // Boolean - check_all_inner_maps_have_key_with(t, "aspects", "parallel", |asp| { - match *asp { Value::Boolean(_) => true, _ => false, } - }) + check_all_inner_maps_have_key_with(t, "aspects", "parallel", + |asp| is_match!(asp, &Value::Boolean(_))) } _ => { write!(stderr(), "Store config is no table").ok(); diff --git a/libimagstore/src/hook/aspect.rs b/libimagstore/src/hook/aspect.rs index f3d914e4..29d8c375 100644 --- a/libimagstore/src/hook/aspect.rs +++ b/libimagstore/src/hook/aspect.rs @@ -41,7 +41,7 @@ impl StoreIdAccessor for Aspect { use crossbeam; let accessors : Vec = self.hooks.iter().map(|h| h.accessor()).collect(); - if !accessors.iter().all(|a| match *a { HDA::StoreIdAccess(_) => true, _ => false }) { + if !accessors.iter().all(|a| is_match!(*a, HDA::StoreIdAccess(_))) { return Err(HE::new(HEK::AccessTypeViolation, None)); } @@ -76,11 +76,7 @@ impl MutableHookDataAccessor for Aspect { let accessors : Vec = self.hooks.iter().map(|h| h.accessor()).collect(); fn is_file_accessor(a: &HDA) -> bool { - match *a { - HDA::MutableAccess(_) | - HDA::NonMutableAccess(_) => true, - _ => false, - } + is_match!(*a, HDA::MutableAccess(_) | HDA::NonMutableAccess(_)) } if !accessors.iter().all(|a| is_file_accessor(a)) { @@ -108,7 +104,7 @@ impl NonMutableHookDataAccessor for Aspect { use crossbeam; let accessors : Vec = self.hooks.iter().map(|h| h.accessor()).collect(); - if !accessors.iter().all(|a| match *a { HDA::NonMutableAccess(_) => true, _ => false }) { + if !accessors.iter().all(|a| is_match!(*a, HDA::NonMutableAccess(_))) { return Err(HE::new(HEK::AccessTypeViolation, None)); } From b1f43e3ef53500c4931a97147d238c2ae70673b7 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Mon, 23 May 2016 22:00:50 +0200 Subject: [PATCH 150/288] Impl Into for all --- libimagerror/src/error_gen.rs | 8 ++++++++ libimagstore/src/hook/error.rs | 8 -------- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/libimagerror/src/error_gen.rs b/libimagerror/src/error_gen.rs index c715eb13..9511c988 100644 --- a/libimagerror/src/error_gen.rs +++ b/libimagerror/src/error_gen.rs @@ -82,6 +82,14 @@ macro_rules! generate_custom_error_types { } + impl Into<$name> for $kindname { + + fn into(self) -> $name { + $name::new(self, None) + } + + } + impl Display for $name { fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> { diff --git a/libimagstore/src/hook/error.rs b/libimagstore/src/hook/error.rs index e55c2b8f..472dc142 100644 --- a/libimagstore/src/hook/error.rs +++ b/libimagstore/src/hook/error.rs @@ -11,14 +11,6 @@ pub trait IntoHookError { fn into_hookerror_with_cause(self, cause: Box) -> HookError; } -impl Into for HookErrorKind { - - fn into(self) -> HookError { - HookError::new(self, None) - } - -} - impl Into for (HookErrorKind, Box) { fn into(self) -> HookError { From 4066ae404831c7bbbe70a018c38ea2f50406fc0a Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Tue, 24 May 2016 16:42:32 +0200 Subject: [PATCH 151/288] Add dep: env_logger = 0.3 --- libimagrt/Cargo.toml | 1 + libimagrt/src/lib.rs | 1 + 2 files changed, 2 insertions(+) diff --git a/libimagrt/Cargo.toml b/libimagrt/Cargo.toml index 89610457..4e3dd673 100644 --- a/libimagrt/Cargo.toml +++ b/libimagrt/Cargo.toml @@ -5,6 +5,7 @@ authors = ["Matthias Beyer "] [dependencies] clap = "2.1.1" +env_logger = "0.3" toml = "0.1.27" log = "0.3" xdg-basedir = "0.2.2" diff --git a/libimagrt/src/lib.rs b/libimagrt/src/lib.rs index e4503f2e..d1d7e249 100644 --- a/libimagrt/src/lib.rs +++ b/libimagrt/src/lib.rs @@ -17,6 +17,7 @@ #[macro_use] extern crate log; #[macro_use] extern crate itertools; #[cfg(unix)] extern crate xdg_basedir; +extern crate env_logger; extern crate tempfile; extern crate ansi_term; From 9a92f9091fa41e97dac7acb06181df748e04c807 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Tue, 24 May 2016 16:43:04 +0200 Subject: [PATCH 152/288] Add env_logger as fallback if IMAG_LOG_ENV is present --- libimagrt/src/runtime.rs | 39 +++++++++++++++++++++++---------------- 1 file changed, 23 insertions(+), 16 deletions(-) diff --git a/libimagrt/src/runtime.rs b/libimagrt/src/runtime.rs index 57540b76..ba520445 100644 --- a/libimagrt/src/runtime.rs +++ b/libimagrt/src/runtime.rs @@ -197,23 +197,30 @@ impl<'a> Runtime<'a> { * Initialize the internal logger */ fn init_logger(is_debugging: bool, is_verbose: bool) { - let lvl = if is_debugging { - LogLevelFilter::Debug - } else if is_verbose { - LogLevelFilter::Info - } else { - LogLevelFilter::Error - }; + use std::env::var as env_var; + use env_logger; - log::set_logger(|max_log_lvl| { - max_log_lvl.set(lvl); - debug!("Init logger with {}", lvl); - Box::new(ImagLogger::new(lvl.to_log_level().unwrap())) - }) - .map_err(|_| { - panic!("Could not setup logger"); - }) - .ok(); + if env_var("IMAG_LOG_ENV").is_ok() { + env_logger::init().unwrap(); + } else { + let lvl = if is_debugging { + LogLevelFilter::Debug + } else if is_verbose { + LogLevelFilter::Info + } else { + LogLevelFilter::Error + }; + + log::set_logger(|max_log_lvl| { + max_log_lvl.set(lvl); + debug!("Init logger with {}", lvl); + Box::new(ImagLogger::new(lvl.to_log_level().unwrap())) + }) + .map_err(|_| { + panic!("Could not setup logger"); + }) + .ok(); + } } /** From b344be00588faade3cda838ce04da728429befb3 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Wed, 25 May 2016 16:28:39 +0200 Subject: [PATCH 153/288] Remove unused import --- libimagnotes/src/note.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libimagnotes/src/note.rs b/libimagnotes/src/note.rs index 8847b888..bf1c0095 100644 --- a/libimagnotes/src/note.rs +++ b/libimagnotes/src/note.rs @@ -1,5 +1,5 @@ use std::collections::BTreeMap; -use std::ops::{DerefMut, Deref}; +use std::ops::Deref; use toml::Value; From 9f3878d43f56c10a4db75bd2fb6ef151ab1fc20a Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Thu, 26 May 2016 08:49:05 +0200 Subject: [PATCH 154/288] Initial import --- libimagentryselect/Cargo.toml | 6 ++++++ libimagentryselect/src/lib.rs | 6 ++++++ 2 files changed, 12 insertions(+) create mode 100644 libimagentryselect/Cargo.toml create mode 100644 libimagentryselect/src/lib.rs diff --git a/libimagentryselect/Cargo.toml b/libimagentryselect/Cargo.toml new file mode 100644 index 00000000..753f3c86 --- /dev/null +++ b/libimagentryselect/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "libimagentryselect" +version = "0.1.0" +authors = ["Matthias Beyer "] + +[dependencies] diff --git a/libimagentryselect/src/lib.rs b/libimagentryselect/src/lib.rs new file mode 100644 index 00000000..cdfbe1aa --- /dev/null +++ b/libimagentryselect/src/lib.rs @@ -0,0 +1,6 @@ +#[cfg(test)] +mod tests { + #[test] + fn it_works() { + } +} From a0b7e9b9801c6c253cbf125e5cb5fe73ff338009 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Thu, 26 May 2016 10:35:11 +0200 Subject: [PATCH 155/288] Add dependencies --- libimagentryselect/Cargo.toml | 10 ++++++++++ libimagentryselect/src/lib.rs | 12 ++++++------ 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/libimagentryselect/Cargo.toml b/libimagentryselect/Cargo.toml index 753f3c86..ccd52838 100644 --- a/libimagentryselect/Cargo.toml +++ b/libimagentryselect/Cargo.toml @@ -4,3 +4,13 @@ version = "0.1.0" authors = ["Matthias Beyer "] [dependencies] +clap = "2" +log = "0.3" +interactor = "0.1" + +[dependencies.libimagstore] +path = "../libimagstore" + +[dependencies.libimagerror] +path = "../libimagerror" + diff --git a/libimagentryselect/src/lib.rs b/libimagentryselect/src/lib.rs index cdfbe1aa..c7472aa6 100644 --- a/libimagentryselect/src/lib.rs +++ b/libimagentryselect/src/lib.rs @@ -1,6 +1,6 @@ -#[cfg(test)] -mod tests { - #[test] - fn it_works() { - } -} +extern crate clap; +extern crate log; +extern crate interactor; + +extern crate libimagstore; + From bad8e1ced17362cb759c9c1b4c55742a133e6ec7 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Thu, 26 May 2016 10:35:26 +0200 Subject: [PATCH 156/288] Add id argument helper and getter --- libimagentryselect/src/lib.rs | 2 ++ libimagentryselect/src/ui.rs | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 libimagentryselect/src/ui.rs diff --git a/libimagentryselect/src/lib.rs b/libimagentryselect/src/lib.rs index c7472aa6..98806550 100644 --- a/libimagentryselect/src/lib.rs +++ b/libimagentryselect/src/lib.rs @@ -4,3 +4,5 @@ extern crate interactor; extern crate libimagstore; +pub mod ui; + diff --git a/libimagentryselect/src/ui.rs b/libimagentryselect/src/ui.rs new file mode 100644 index 00000000..9be677ac --- /dev/null +++ b/libimagentryselect/src/ui.rs @@ -0,0 +1,35 @@ +use clap::{Arg, ArgMatches}; + +use libimagstore::storeid::StoreId; + +pub fn id_argument<'a, 'b>() -> Arg<'a, 'b> { + Arg::with_name(id_argument_name()) + .short(id_argument_short()) + .long(id_argument_long()) + .takes_value(true) + .multiple(true) + .help("Specify the Store-Id") +} + +pub fn id_argument_name() -> &'static str { + "id-argument" +} + +pub fn id_argument_short() -> &'static str { + "i" +} + +pub fn id_argument_long() -> &'static str { + "id" +} + +pub fn get_id(matches: &ArgMatches) -> Option> { + matches.values_of(id_argument_name()) + .map(|vals| { + vals.into_iter() + .map(String::from) + .map(StoreId::from) + .collect() + }) +} + From 2aeb853c5f0465182d740a4702c20ce28450f5c0 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Thu, 26 May 2016 10:41:25 +0200 Subject: [PATCH 157/288] Implement get_or_select_id() --- libimagentryselect/src/lib.rs | 1 + libimagentryselect/src/ui.rs | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/libimagentryselect/src/lib.rs b/libimagentryselect/src/lib.rs index 98806550..182aecdb 100644 --- a/libimagentryselect/src/lib.rs +++ b/libimagentryselect/src/lib.rs @@ -3,6 +3,7 @@ extern crate log; extern crate interactor; extern crate libimagstore; +extern crate libimagerror; pub mod ui; diff --git a/libimagentryselect/src/ui.rs b/libimagentryselect/src/ui.rs index 9be677ac..c8c524d5 100644 --- a/libimagentryselect/src/ui.rs +++ b/libimagentryselect/src/ui.rs @@ -1,6 +1,9 @@ +use std::path::PathBuf; + use clap::{Arg, ArgMatches}; use libimagstore::storeid::StoreId; +use libimagerror::trace::trace_error; pub fn id_argument<'a, 'b>() -> Arg<'a, 'b> { Arg::with_name(id_argument_name()) @@ -33,3 +36,18 @@ pub fn get_id(matches: &ArgMatches) -> Option> { }) } +pub fn get_or_select_id(matches: &ArgMatches, store_path: &PathBuf) -> Option> { + use interactor::{pick_file, default_menu_cmd}; + + get_id(matches).or_else(|| { + match pick_file(default_menu_cmd, store_path.clone()) { + Err(e) => { + trace_error(&e); + None + }, + + Ok(p) => Some(vec![StoreId::from(p)]), + } + }) +} + From 2ad5cb48aa3fc763207d1f8ab9b4c20974f56af7 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Thu, 26 May 2016 18:40:58 +0200 Subject: [PATCH 158/288] Implement store-unload hooks --- libimagstore/src/configuration.rs | 9 ++++++++- libimagstore/src/hook/position.rs | 2 ++ libimagstore/src/store.rs | 21 ++++++++++++++++++++- libimagstorestdhook/src/debug.rs | 1 + 4 files changed, 31 insertions(+), 2 deletions(-) diff --git a/libimagstore/src/configuration.rs b/libimagstore/src/configuration.rs index 33e0a49e..cdad60d2 100644 --- a/libimagstore/src/configuration.rs +++ b/libimagstore/src/configuration.rs @@ -117,7 +117,10 @@ pub fn config_is_valid(config: &Option) -> bool { } match *config { - Some(Value::Table(ref t)) => { has_key_with_string_ary(t, "pre-create-hook-aspects") && + Some(Value::Table(ref t)) => { + has_key_with_string_ary(t, "store-unload-hook-aspects") && + + has_key_with_string_ary(t, "pre-create-hook-aspects") && has_key_with_string_ary(t, "post-create-hook-aspects") && has_key_with_string_ary(t, "pre-retrieve-hook-aspects") && has_key_with_string_ary(t, "post-retrieve-hook-aspects") && @@ -143,6 +146,10 @@ pub fn config_is_valid(config: &Option) -> bool { } } +pub fn get_store_unload_aspect_names(value: &Option) -> Vec { + get_aspect_names_for_aspect_position("store-unload-hook-aspects", value) +} + pub fn get_pre_create_aspect_names(value: &Option) -> Vec { get_aspect_names_for_aspect_position("pre-create-hook-aspects", value) } diff --git a/libimagstore/src/hook/position.rs b/libimagstore/src/hook/position.rs index 6e74436d..0ccb563e 100644 --- a/libimagstore/src/hook/position.rs +++ b/libimagstore/src/hook/position.rs @@ -1,5 +1,7 @@ #[derive(Debug, Clone)] pub enum HookPosition { + StoreUnload, + PreCreate, PostCreate, PreRetrieve, diff --git a/libimagstore/src/store.rs b/libimagstore/src/store.rs index b7013b4d..1ab53093 100644 --- a/libimagstore/src/store.rs +++ b/libimagstore/src/store.rs @@ -171,6 +171,8 @@ pub struct Store { * Registered hooks */ + store_unload_aspects : Arc>>, + pre_create_aspects : Arc>>, post_create_aspects : Arc>>, pre_retrieve_aspects : Arc>>, @@ -216,6 +218,12 @@ impl Store { return Err(SE::new(SEK::StorePathExists, None)); } + let store_unload_aspects = get_store_unload_aspect_names(&store_config) + .into_iter().map(|n| { + let cfg = AspectConfig::get_for(&store_config, n.clone()); + Aspect::new(n, cfg) + }).collect(); + let pre_create_aspects = get_pre_create_aspect_names(&store_config) .into_iter().map(|n| { let cfg = AspectConfig::get_for(&store_config, n.clone()); @@ -265,8 +273,11 @@ impl Store { }).collect(); let store = Store { - location: location, + location: location.clone(), configuration: store_config, + + store_unload_aspects : Arc::new(Mutex::new(store_unload_aspects)), + pre_create_aspects : Arc::new(Mutex::new(pre_create_aspects)), post_create_aspects : Arc::new(Mutex::new(post_create_aspects)), pre_retrieve_aspects : Arc::new(Mutex::new(pre_retrieve_aspects)), @@ -544,6 +555,8 @@ impl Store { debug!(" with aspect: {:?}", aspect_name); let guard = match position { + HookPosition::StoreUnload => self.store_unload_aspects.clone(), + HookPosition::PreCreate => self.pre_create_aspects.clone(), HookPosition::PostCreate => self.post_create_aspects.clone(), HookPosition::PreRetrieve => self.pre_retrieve_aspects.clone(), @@ -649,6 +662,12 @@ impl Drop for Store { * TODO: Unlock them */ fn drop(&mut self) { + let store_id = StoreId::from(self.location.clone()); + if let Err(e) = self.execute_hooks_for_id(self.store_unload_aspects.clone(), &store_id) { + debug!("Store-load hooks execution failed. Cannot create store object."); + warn!("Store Unload Hook error: {:?}", e); + } + debug!("Dropping store"); } diff --git a/libimagstorestdhook/src/debug.rs b/libimagstorestdhook/src/debug.rs index 830c8e3d..9f7bd63e 100644 --- a/libimagstorestdhook/src/debug.rs +++ b/libimagstorestdhook/src/debug.rs @@ -43,6 +43,7 @@ impl HookDataAccessorProvider for DebugHook { use libimagstore::hook::accessor::HookDataAccessor as HDA; match self.position { + HP::StoreUnload | HP::PreCreate | HP::PreRetrieve | HP::PreDelete | From 376832631a8fd0c12336c13ef3ca0302ea830df3 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Thu, 26 May 2016 18:42:20 +0200 Subject: [PATCH 159/288] Add entry in example config file --- imagrc.toml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/imagrc.toml b/imagrc.toml index 8c65046f..148e53d0 100644 --- a/imagrc.toml +++ b/imagrc.toml @@ -3,6 +3,10 @@ [store] +# Hooks which get executed right before the Store is closed. +# They get the store path as StoreId passed, so they can alter the complete +# store, so these hooks should be chosen carefully. +store-unload-hook-aspects = [ "debug" ] pre-create-hook-aspects = [ "debug" ] post-create-hook-aspects = [ "debug" ] From 0f529004565fc5235a704485e0f8bb2df2ce4962 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Thu, 26 May 2016 18:18:21 +0200 Subject: [PATCH 160/288] Add missing keyword "pub" for Link type --- libimagentrylink/src/external.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libimagentrylink/src/external.rs b/libimagentrylink/src/external.rs index 486ab306..7c504f3a 100644 --- a/libimagentrylink/src/external.rs +++ b/libimagentrylink/src/external.rs @@ -32,7 +32,7 @@ use crypto::sha1::Sha1; use crypto::digest::Digest; /// "Link" Type, just an abstraction over `FileLockEntry` to have some convenience internally. -struct Link<'a> { +pub struct Link<'a> { link: FileLockEntry<'a> } From fdb5d1bb24377884fc8827d5895d1a0149017c3a Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Thu, 26 May 2016 22:16:29 +0200 Subject: [PATCH 161/288] Replace old error construction code with new libimagerror functionality --- libimagstore/src/lazyfile.rs | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/libimagstore/src/lazyfile.rs b/libimagstore/src/lazyfile.rs index ec3e8f45..5079b686 100644 --- a/libimagstore/src/lazyfile.rs +++ b/libimagstore/src/lazyfile.rs @@ -1,3 +1,4 @@ +use libimagerror::into::IntoError; use error::{StoreError, StoreErrorKind}; use std::io::{Seek, SeekFrom}; @@ -39,14 +40,15 @@ impl LazyFile { // We seek to the beginning of the file since we expect each // access to the file to be in a different context f.seek(SeekFrom::Start(0)) - .map_err(|e| StoreError::new(StoreErrorKind::FileNotCreated, Some(Box::new(e)))) + .map_err(Box::new) + .map_err(|e| StoreErrorKind::FileNotCreated.into_error_with_cause(e)) .map(|_| f) }, LazyFile::Absent(ref p) => { - try!(open_file(p).map_err(|e| { - StoreError::new(StoreErrorKind::FileNotFound, - Some(Box::new(e))) - })) + try!(open_file(p) + .map_err(Box::new) + .map_err(|e| StoreErrorKind::FileNotFound.into_error_with_cause(e)) + ) } }; *self = LazyFile::File(file); @@ -64,10 +66,10 @@ impl LazyFile { let file = match *self { LazyFile::File(ref mut f) => return Ok(f), LazyFile::Absent(ref p) => { - try!(create_file(p).map_err(|e| { - StoreError::new(StoreErrorKind::FileNotFound, - Some(Box::new(e))) - })) + try!(create_file(p) + .map_err(Box::new) + .map_err(|e| StoreErrorKind::FileNotFound.into_error_with_cause(e)) + ) } }; *self = LazyFile::File(file); From 25c4bea8189c180802367f50f034a79f57071e50 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Thu, 26 May 2016 22:17:08 +0200 Subject: [PATCH 162/288] Shorten type names in import --- libimagstore/src/lazyfile.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/libimagstore/src/lazyfile.rs b/libimagstore/src/lazyfile.rs index 5079b686..1e5cd66d 100644 --- a/libimagstore/src/lazyfile.rs +++ b/libimagstore/src/lazyfile.rs @@ -1,6 +1,6 @@ use libimagerror::into::IntoError; -use error::{StoreError, StoreErrorKind}; +use error::{StoreError as SE, StoreErrorKind as SEK}; use std::io::{Seek, SeekFrom}; use std::path::{Path, PathBuf}; use std::fs::{File, OpenOptions, create_dir_all}; @@ -33,7 +33,7 @@ impl LazyFile { /** * Get the mutable file behind a LazyFile object */ - pub fn get_file_mut(&mut self) -> Result<&mut File, StoreError> { + pub fn get_file_mut(&mut self) -> Result<&mut File, SE> { debug!("Getting lazy file: {:?}", self); let file = match *self { LazyFile::File(ref mut f) => return { @@ -41,13 +41,13 @@ impl LazyFile { // access to the file to be in a different context f.seek(SeekFrom::Start(0)) .map_err(Box::new) - .map_err(|e| StoreErrorKind::FileNotCreated.into_error_with_cause(e)) + .map_err(|e| SEK::FileNotCreated.into_error_with_cause(e)) .map(|_| f) }, LazyFile::Absent(ref p) => { try!(open_file(p) .map_err(Box::new) - .map_err(|e| StoreErrorKind::FileNotFound.into_error_with_cause(e)) + .map_err(|e| SEK::FileNotFound.into_error_with_cause(e)) ) } }; @@ -61,14 +61,14 @@ impl LazyFile { /** * Create a file out of this LazyFile object */ - pub fn create_file(&mut self) -> Result<&mut File, StoreError> { + pub fn create_file(&mut self) -> Result<&mut File, SE> { debug!("Creating lazy file: {:?}", self); let file = match *self { LazyFile::File(ref mut f) => return Ok(f), LazyFile::Absent(ref p) => { try!(create_file(p) .map_err(Box::new) - .map_err(|e| StoreErrorKind::FileNotFound.into_error_with_cause(e)) + .map_err(|e| SEK::FileNotFound.into_error_with_cause(e)) ) } }; From 5e98bd76b1e8b4ca1faba5832bdc5aeb5731a781 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Thu, 26 May 2016 22:17:53 +0200 Subject: [PATCH 163/288] Shorten type names in import --- libimagstore/src/storeid.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/libimagstore/src/storeid.rs b/libimagstore/src/storeid.rs index d6631333..140797f9 100644 --- a/libimagstore/src/storeid.rs +++ b/libimagstore/src/storeid.rs @@ -8,7 +8,7 @@ use std::fmt::{Debug, Formatter}; use std::fmt::Error as FmtError; use std::result::Result as RResult; -use error::{StoreError, StoreErrorKind}; +use error::{StoreError as SE, StoreErrorKind as SEK}; use store::Result; use store::Store; @@ -88,7 +88,7 @@ pub fn build_entry_path(store: &Store, path_elem: &str) -> Result { if path_elem.split('~').last().map_or(false, |v| Version::parse(v).is_err()) { debug!("Version cannot be parsed from {:?}", path_elem); debug!("Path does not contain version!"); - return Err(StoreError::new(StoreErrorKind::StorePathLacksVersion, None)); + return Err(SE::new(SEK::StorePathLacksVersion, None)); } debug!("Version checking succeeded"); From e91eb2f55d007ba28ef44f36941616901d7f050b Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Thu, 26 May 2016 22:19:29 +0200 Subject: [PATCH 164/288] Use error.into() instead of building full type --- libimagstore/src/storeid.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/libimagstore/src/storeid.rs b/libimagstore/src/storeid.rs index 140797f9..147b80cb 100644 --- a/libimagstore/src/storeid.rs +++ b/libimagstore/src/storeid.rs @@ -8,7 +8,7 @@ use std::fmt::{Debug, Formatter}; use std::fmt::Error as FmtError; use std::result::Result as RResult; -use error::{StoreError as SE, StoreErrorKind as SEK}; +use error::StoreErrorKind as SEK; use store::Result; use store::Store; @@ -88,7 +88,7 @@ pub fn build_entry_path(store: &Store, path_elem: &str) -> Result { if path_elem.split('~').last().map_or(false, |v| Version::parse(v).is_err()) { debug!("Version cannot be parsed from {:?}", path_elem); debug!("Path does not contain version!"); - return Err(SE::new(SEK::StorePathLacksVersion, None)); + return Err(SEK::StorePathLacksVersion.into()); } debug!("Version checking succeeded"); From 183c46a7ddacf88d9bd1f151176392e9e355eeae Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Fri, 27 May 2016 10:11:51 +0200 Subject: [PATCH 165/288] Use Into implementations to convert error kinds into error types --- libimagstore/src/store.rs | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/libimagstore/src/store.rs b/libimagstore/src/store.rs index b7013b4d..c3962f11 100644 --- a/libimagstore/src/store.rs +++ b/libimagstore/src/store.rs @@ -33,6 +33,8 @@ use hook::accessor::{ MutableHookDataAccessor, use hook::position::HookPosition; use hook::Hook; +use libimagerror::into::IntoError; + use self::glob_store_iter::*; /// The Result Type returned by any interaction with the store that could fail @@ -739,7 +741,7 @@ impl EntryHeader { let mut parser = Parser::new(s); parser.parse() - .ok_or(ParserError::new(ParserErrorKind::TOMLParserErrors, None)) + .ok_or(ParserErrorKind::TOMLParserErrors.into()) .and_then(verify_header_consistency) .map(EntryHeader::from_table) } @@ -1151,12 +1153,12 @@ fn build_default_header() -> Value { // BTreeMap } fn verify_header(t: &Table) -> Result<()> { if !has_main_section(t) { - Err(SE::from(ParserError::new(ParserErrorKind::MissingMainSection, None))) + Err(SE::from(ParserErrorKind::MissingMainSection.into_error())) } else if !has_imag_version_in_main_section(t) { - Err(SE::from(ParserError::new(ParserErrorKind::MissingVersionInfo, None))) + Err(SE::from(ParserErrorKind::MissingVersionInfo.into_error())) } else if !has_only_tables(t) { debug!("Could not verify that it only has tables in its base table"); - Err(SE::from(ParserError::new(ParserErrorKind::NonTableInBaseTable, None))) + Err(SE::from(ParserErrorKind::NonTableInBaseTable.into_error())) } else { Ok(()) } @@ -1164,7 +1166,8 @@ fn verify_header(t: &Table) -> Result<()> { fn verify_header_consistency(t: Table) -> EntryResult
{ verify_header(&t) - .map_err(|e| ParserError::new(ParserErrorKind::HeaderInconsistency, Some(Box::new(e)))) + .map_err(Box::new) + .map_err(|e| ParserErrorKind::HeaderInconsistency.into_error_with_cause(e)) .map(|_| t) } From cb87b4b5d8893c3ce856ddabb885e4eb30c6e777 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Fri, 27 May 2016 10:13:03 +0200 Subject: [PATCH 166/288] Remove old error code which is unused --- libimagstore/src/hook/error.rs | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/libimagstore/src/hook/error.rs b/libimagstore/src/hook/error.rs index 472dc142..451fb5a5 100644 --- a/libimagstore/src/hook/error.rs +++ b/libimagstore/src/hook/error.rs @@ -6,16 +6,3 @@ generate_error_types!(HookError, HookErrorKind, AccessTypeViolation => "Hook access type violation" ); -pub trait IntoHookError { - fn into_hookerror(self) -> HookError; - fn into_hookerror_with_cause(self, cause: Box) -> HookError; -} - -impl Into for (HookErrorKind, Box) { - - fn into(self) -> HookError { - HookError::new(self.0, Some(self.1)) - } - -} - From 3d9d5795e4948c427dd9936521b0f6c3ca676837 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Fri, 27 May 2016 10:15:29 +0200 Subject: [PATCH 167/288] Rewrite hook error module with error macros --- libimagstore/src/hook/error.rs | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/libimagstore/src/hook/error.rs b/libimagstore/src/hook/error.rs index 451fb5a5..afe9ef07 100644 --- a/libimagstore/src/hook/error.rs +++ b/libimagstore/src/hook/error.rs @@ -1,8 +1,10 @@ -generate_error_imports!(); -use std::convert::Into; - -generate_error_types!(HookError, HookErrorKind, - HookExecutionError => "Hook exec error", - AccessTypeViolation => "Hook access type violation" +generate_error_module!( + generate_error_types!(HookError, HookErrorKind, + HookExecutionError => "Hook exec error", + AccessTypeViolation => "Hook access type violation" + ); ); +pub use self::error::HookError; +pub use self::error::HookErrorKind; + From 70b6a4f5878b2bfe19dd8a28541a0fbd8e73c281 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Fri, 27 May 2016 10:21:56 +0200 Subject: [PATCH 168/288] Replace configuration error code with macro generator --- libimagrt/src/configuration.rs | 73 +++------------------------------- 1 file changed, 5 insertions(+), 68 deletions(-) diff --git a/libimagrt/src/configuration.rs b/libimagrt/src/configuration.rs index 15b94e09..3fb1c231 100644 --- a/libimagrt/src/configuration.rs +++ b/libimagrt/src/configuration.rs @@ -4,77 +4,14 @@ use std::ops::Deref; use toml::{Parser, Value}; -/** - * Errors which are related to configuration-file loading - */ -pub mod error { - use std::error::Error; - use std::fmt::{Display, Formatter}; - use std::fmt::Error as FmtError; - - /// The kind of an error - #[derive(Clone, Debug, PartialEq)] - pub enum ConfigErrorKind { - NoConfigFileFound, - } - - /// Configuration error type - #[derive(Debug)] - pub struct ConfigError { - kind: ConfigErrorKind, - cause: Option>, - } - - impl ConfigError { - - /// Instantiate a new `ConfigError`, optionally with cause - pub fn new(kind: ConfigErrorKind, cause: Option>) -> ConfigError { - ConfigError { - kind: kind, - cause: cause, - } - } - - ///get the Kind of the Error - pub fn err_type(&self) -> ConfigErrorKind { - self.kind.clone() - } - - /// Get the string, the `ConfigError` can be described with - pub fn as_str(e: &ConfigError) -> &'static str { - match e.err_type() { - ConfigErrorKind::NoConfigFileFound => "No config file found", - } - } - - } - - impl Display for ConfigError { - - fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> { - try!(write!(fmt, "{}", ConfigError::as_str(self))); - Ok(()) - } - - } - - impl Error for ConfigError { - - fn description(&self) -> &str { - ConfigError::as_str(self) - } - - fn cause(&self) -> Option<&Error> { - self.cause.as_ref().map(|e| &**e) - } - - } - -} +generate_error_module!( + generate_error_types!(ConfigError, ConfigErrorKind, + NoConfigFileFound => "No config file found" + ); +); use self::error::{ConfigError, ConfigErrorKind}; - /** * Result type of this module. Either `T` or `ConfigError` */ From e3db21b0091781ea4418f068e6703836f1c2358c Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Fri, 27 May 2016 10:27:06 +0200 Subject: [PATCH 169/288] Use IntoError trait for less ugly code --- libimagrt/src/configuration.rs | 2 +- libimagrt/src/edit.rs | 13 ++++++++----- libimagrt/src/error.rs | 2 +- libimagrt/src/runtime.rs | 10 ++++------ 4 files changed, 14 insertions(+), 13 deletions(-) diff --git a/libimagrt/src/configuration.rs b/libimagrt/src/configuration.rs index 3fb1c231..c3cb9735 100644 --- a/libimagrt/src/configuration.rs +++ b/libimagrt/src/configuration.rs @@ -182,6 +182,6 @@ fn fetch_config(rtp: &PathBuf) -> Result { .filter(|loaded| loaded.is_some()) .nth(0) .map(|inner| Value::Table(inner.unwrap())) - .ok_or_else(|| ConfigError::new(ConfigErrorKind::NoConfigFileFound, None)) + .ok_or(ConfigErrorKind::NoConfigFileFound.into()) } diff --git a/libimagrt/src/edit.rs b/libimagrt/src/edit.rs index 93fa1a6b..67f495b8 100644 --- a/libimagrt/src/edit.rs +++ b/libimagrt/src/edit.rs @@ -7,6 +7,8 @@ use error::RuntimeErrorKind; use libimagstore::store::FileLockEntry; use libimagstore::store::Entry; +use libimagerror::into::IntoError; + pub type EditResult = Result; pub trait Edit { @@ -55,18 +57,19 @@ pub fn edit_in_tmpfile(rt: &Runtime, s: &mut String) -> EditResult<()> { if let Some(mut editor) = rt.editor() { let exit_status = editor.arg(file_path).status(); - match exit_status.map(|s| s.success()) { + match exit_status.map(|s| s.success()).map_err(Box::new) { Ok(true) => { file.sync_data() .and_then(|_| file.seek(SeekFrom::Start(0))) .and_then(|_| file.read_to_string(s)) .map(|_| ()) - .map_err(|e| RuntimeError::new(RuntimeErrorKind::IOError, Some(Box::new(e)))) + .map_err(Box::new) + .map_err(|e| RuntimeErrorKind::IOError.into_error_with_cause(e)) }, - Ok(false) => Err(RuntimeError::new(RuntimeErrorKind::ProcessExitFailure, None)), - Err(e) => Err(RuntimeError::new(RuntimeErrorKind::IOError, Some(Box::new(e)))), + Ok(false) => Err(RuntimeErrorKind::ProcessExitFailure.into()), + Err(e) => Err(RuntimeErrorKind::IOError.into_error_with_cause(e)), } } else { - Err(RuntimeError::new(RuntimeErrorKind::Instantiate, None)) + Err(RuntimeErrorKind::Instantiate.into()) } } diff --git a/libimagrt/src/error.rs b/libimagrt/src/error.rs index 50d640d7..e5f26baa 100644 --- a/libimagrt/src/error.rs +++ b/libimagrt/src/error.rs @@ -10,7 +10,7 @@ generate_error_types!(RuntimeError, RuntimeErrorKind, impl From for RuntimeError { fn from(ioe: IOError) -> RuntimeError { - RuntimeError::new(RuntimeErrorKind::IOError, Some(Box::new(ioe))) + RuntimeErrorKind::IOError.into_error_with_cause(Box::new(ioe)) } } diff --git a/libimagrt/src/runtime.rs b/libimagrt/src/runtime.rs index ba520445..e693feff 100644 --- a/libimagrt/src/runtime.rs +++ b/libimagrt/src/runtime.rs @@ -37,13 +37,13 @@ impl<'a> Runtime<'a> { */ pub fn new(cli_spec: App<'a, 'a>) -> Result, RuntimeError> { use std::env; - use std::error::Error; use libimagstore::hook::position::HookPosition; use libimagstore::error::StoreErrorKind; use libimagstorestdhook::debug::DebugHook; use libimagerror::trace::trace_error; use libimagerror::trace::trace_error_dbg; + use libimagerror::into::IntoError; use configuration::error::ConfigErrorKind; @@ -72,8 +72,7 @@ impl<'a> Runtime<'a> { let cfg = match Configuration::new(&rtp) { Err(e) => if e.err_type() != ConfigErrorKind::NoConfigFileFound { - let cause : Option> = Some(Box::new(e)); - return Err(RuntimeError::new(RuntimeErrorKind::Instantiate, cause)); + return Err(RuntimeErrorKind::Instantiate.into_error_with_cause(Box::new(e))); } else { warn!("No config file found."); warn!("Continuing without configuration file"); @@ -128,9 +127,8 @@ impl<'a> Runtime<'a> { store: store, } }) - .map_err(|e| { - RuntimeError::new(RuntimeErrorKind::Instantiate, Some(Box::new(e))) - }) + .map_err(Box::new) + .map_err(|e| RuntimeErrorKind::Instantiate.into_error_with_cause(e)) } /** From 98b39bbfa8fe7bee67209998dd1c409eb99f1ace Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Fri, 27 May 2016 10:38:35 +0200 Subject: [PATCH 170/288] Use IntoError to have less noise in the error construction code --- libimagentrylink/src/internal.rs | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/libimagentrylink/src/internal.rs b/libimagentrylink/src/internal.rs index 0c6b977b..1a97d46f 100644 --- a/libimagentrylink/src/internal.rs +++ b/libimagentrylink/src/internal.rs @@ -4,8 +4,9 @@ use libimagstore::storeid::StoreId; use libimagstore::store::Entry; use libimagstore::store::EntryHeader; use libimagstore::store::Result as StoreResult; +use libimagerror::into::IntoError; -use error::{LinkError, LinkErrorKind}; +use error::LinkErrorKind as LEK; use result::Result; use toml::Value; @@ -50,7 +51,7 @@ impl InternalLinker for Entry { let new_links = links_into_values(new_links); if new_links.iter().any(|o| o.is_none()) { - return Err(LinkError::new(LinkErrorKind::InternalConversionError, None)); + return Err(LEK::InternalConversionError.into()); } let new_links = new_links.into_iter().map(|o| o.unwrap()).collect(); process_rw_result(self.get_header_mut().set("imag.links", Value::Array(new_links))) @@ -109,7 +110,7 @@ fn rewrite_links(header: &mut EntryHeader, links: Vec) -> Result<()> { if links.iter().any(|o| o.is_none()) { // if any type convert failed we fail as well - Err(LinkError::new(LinkErrorKind::InternalConversionError, None)) + Err(LEK::InternalConversionError.into()) } else { // I know it is ugly let links = links.into_iter().map(|opt| opt.unwrap()).collect(); @@ -126,7 +127,7 @@ fn add_foreign_link(target: &mut Entry, from: StoreId) -> Result<()> { links.push(from); let links = links_into_values(links); if links.iter().any(|o| o.is_none()) { - Err(LinkError::new(LinkErrorKind::InternalConversionError, None)) + Err(LEK::InternalConversionError.into()) } else { let links = links.into_iter().map(|opt| opt.unwrap()).collect(); process_rw_result(target.get_header_mut().set("imag.links", Value::Array(links))) @@ -138,9 +139,7 @@ fn add_foreign_link(target: &mut Entry, from: StoreId) -> Result<()> { fn process_rw_result(links: StoreResult>) -> Result> { if links.is_err() { debug!("RW action on store failed. Generating LinkError"); - let lerr = LinkError::new(LinkErrorKind::EntryHeaderReadError, - Some(Box::new(links.unwrap_err()))); - return Err(lerr); + return Err(LEK::EntryHeaderReadError.into_error_with_cause(Box::new(links.unwrap_err()))) } let links = links.unwrap(); @@ -155,7 +154,7 @@ fn process_rw_result(links: StoreResult>) -> Result> { Value::Array(a) => a, _ => { debug!("We expected an Array for the links, but there was a non-Array!"); - return Err(LinkError::new(LinkErrorKind::ExistingLinkTypeWrong, None)); + return Err(LEK::ExistingLinkTypeWrong.into()); }, } }; @@ -163,7 +162,7 @@ fn process_rw_result(links: StoreResult>) -> Result> { if !links.iter().all(|l| is_match!(*l, Value::String(_))) { debug!("At least one of the Values which were expected in the Array of links is a non-String!"); debug!("Generating LinkError"); - return Err(LinkError::new(LinkErrorKind::ExistingLinkTypeWrong, None)); + return Err(LEK::ExistingLinkTypeWrong.into()); } let links : Vec = links.into_iter() From 5fbfe63e1b9bb6bca62b14bcf01462da783fc047 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Fri, 27 May 2016 10:44:37 +0200 Subject: [PATCH 171/288] Use IntoError functionality to have less noise in the error construction code --- libimagentrytag/src/tagable.rs | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/libimagentrytag/src/tagable.rs b/libimagentrytag/src/tagable.rs index 44143d98..c9584f8a 100644 --- a/libimagentrytag/src/tagable.rs +++ b/libimagentrytag/src/tagable.rs @@ -4,8 +4,9 @@ use std::ops::DerefMut; use itertools::Itertools; use libimagstore::store::{Entry, EntryHeader, FileLockEntry}; +use libimagerror::into::IntoError; -use error::{TagError, TagErrorKind}; +use error::TagErrorKind; use result::Result; use tag::{Tag, TagSlice}; use util::is_tag; @@ -31,20 +32,20 @@ impl Tagable for EntryHeader { let tags = self.read("imag.tags"); if tags.is_err() { let kind = TagErrorKind::HeaderReadError; - return Err(TagError::new(kind, Some(Box::new(tags.unwrap_err())))); + return Err(kind.into_error_with_cause(Box::new(tags.unwrap_err()))); } let tags = tags.unwrap(); match tags { Some(Value::Array(tags)) => { if !tags.iter().all(|t| is_match!(*t, Value::String(_))) { - return Err(TagError::new(TagErrorKind::TagTypeError, None)); + return Err(TagErrorKind::TagTypeError.into()); } if tags.iter().any(|t| match *t { Value::String(ref s) => !is_tag(s), _ => unreachable!()}) { - return Err(TagError::new(TagErrorKind::NotATag, None)); + return Err(TagErrorKind::NotATag.into()); } Ok(tags.iter() @@ -58,26 +59,27 @@ impl Tagable for EntryHeader { .collect()) }, None => Ok(vec![]), - _ => Err(TagError::new(TagErrorKind::TagTypeError, None)), + _ => Err(TagErrorKind::TagTypeError.into()), } } fn set_tags(&mut self, ts: &[Tag]) -> Result<()> { if ts.iter().any(|tag| !is_tag(tag)) { debug!("Not a tag: '{}'", ts.iter().filter(|t| !is_tag(t)).next().unwrap()); - return Err(TagError::new(TagErrorKind::NotATag, None)); + return Err(TagErrorKind::NotATag.into()); } let a = ts.iter().unique().map(|t| Value::String(t.clone())).collect(); self.set("imag.tags", Value::Array(a)) .map(|_| ()) - .map_err(|e| TagError::new(TagErrorKind::HeaderWriteError, Some(Box::new(e)))) + .map_err(Box::new) + .map_err(|e| TagErrorKind::HeaderWriteError.into_error_with_cause(e)) } fn add_tag(&mut self, t: Tag) -> Result<()> { if !is_tag(&t) { debug!("Not a tag: '{}'", t); - return Err(TagError::new(TagErrorKind::NotATag, None)); + return Err(TagErrorKind::NotATag.into()); } self.get_tags() @@ -91,7 +93,7 @@ impl Tagable for EntryHeader { fn remove_tag(&mut self, t: Tag) -> Result<()> { if !is_tag(&t) { debug!("Not a tag: '{}'", t); - return Err(TagError::new(TagErrorKind::NotATag, None)); + return Err(TagErrorKind::NotATag.into()); } self.get_tags() @@ -106,12 +108,12 @@ impl Tagable for EntryHeader { let tags = self.read("imag.tags"); if tags.is_err() { let kind = TagErrorKind::HeaderReadError; - return Err(TagError::new(kind, Some(Box::new(tags.unwrap_err())))); + return Err(kind.into_error_with_cause(Box::new(tags.unwrap_err()))); } let tags = tags.unwrap(); if !tags.iter().all(|t| is_match!(*t, Value::String(_))) { - return Err(TagError::new(TagErrorKind::TagTypeError, None)); + return Err(TagErrorKind::TagTypeError.into()); } Ok(tags From 19aec6327f1a34e6c4c5b874a2d5197611f6ea15 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Fri, 27 May 2016 12:23:26 +0200 Subject: [PATCH 172/288] Fix Store::get() --- libimagstore/src/store.rs | 36 +++++------------------------------- 1 file changed, 5 insertions(+), 31 deletions(-) diff --git a/libimagstore/src/store.rs b/libimagstore/src/store.rs index b7013b4d..2f6ace04 100644 --- a/libimagstore/src/store.rs +++ b/libimagstore/src/store.rs @@ -353,38 +353,12 @@ impl Store { /// Get an entry from the store if it exists. /// /// This executes the {pre,post}_retrieve_aspects hooks. - pub fn get<'a, S: IntoStoreId>(&'a self, id: S) -> Result>> - { - let id = self.storify_id(id.into_storeid()); - if let Err(e) = self.execute_hooks_for_id(self.pre_retrieve_aspects.clone(), &id) { - return Err(e); - } - - let mut entries = match self.entries.write() { - // Loosing the error here - Err(_) => return Err(SE::new(SEK::LockPoisoned, None)), - Ok(e) => e, - }; - - let mut se = match entries.get_mut(&id) { - Some(e) => e, - None => return Ok(None), - }; - - let entry = match se.get_entry() { - Ok(e) => e, - Err(e) => return Err(e), - }; - - se.status = StoreEntryStatus::Borrowed; - - let mut fle = FileLockEntry::new(self, entry, id); - - if let Err(e) = self.execute_hooks_for_mut_file(self.post_retrieve_aspects.clone(), &mut fle) { - Err(SE::new(SEK::HookExecutionError, Some(Box::new(e)))) - } else { - Ok(Some(fle)) + pub fn get<'a, S: IntoStoreId + Clone>(&'a self, id: S) -> Result>> { + if !self.storify_id(id.clone().into_storeid()).exists() { + debug!("Does not exist: {:?}", id.clone().into_storeid()); + return Ok(None); } + self.retrieve(id).map(Some) } /// Same as `Store::get()` but also tries older versions of the entry, returning an iterator From a2ea89e936c65f6cb6e8e0bf66e2c00363eb5440 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Fri, 27 May 2016 11:25:43 +0200 Subject: [PATCH 173/288] Add UI specification for get() functionality --- imag-store/src/ui.rs | 45 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git a/imag-store/src/ui.rs b/imag-store/src/ui.rs index c6e49432..e9ccb7e4 100644 --- a/imag-store/src/ui.rs +++ b/imag-store/src/ui.rs @@ -53,7 +53,50 @@ pub fn build_ui<'a>(app: App<'a, 'a>) -> App<'a, 'a> { ) .subcommand(SubCommand::with_name("retrieve") - .about("Get an entry from the store") + .about("Retrieve an entry from the store (implicitely creates the entry)") + .version("0.1") + .arg(Arg::with_name("id") + .long("id") + .short("i") + .takes_value(true) + .required(true) + .help("Retreive by Store Path, where root (/) is the store itself")) + .arg(Arg::with_name("content") + .long("content") + .short("c") + .help("Print content")) + .arg(Arg::with_name("header") + .long("header") + .short("h") + .help("Print header")) + .arg(Arg::with_name("header-json") + .long("header-json") + .short("j") + .help("Print header as json")) + .arg(Arg::with_name("raw") + .long("raw") + .short("r") + .help("Print Entries as they are in the store")) + + .subcommand(SubCommand::with_name("filter-header") + .about("Retrieve Entries by filtering") + .version("0.1") + .arg(Arg::with_name("header-field-where") + .long("where") + .short("w") + .takes_value(true) + .help("Filter with 'header.field=foo' where the header field 'header.field' equals 'foo'") + ) + .arg(Arg::with_name("header-field-grep") + .long("grep") + .short("g") + .takes_value(true) + .help("Filter with 'header.field=[a-zA-Z0-9]*' where the header field 'header.field' matches '[a-zA-Z0-9]*'")) + ) + ) + + .subcommand(SubCommand::with_name("get") + .about("Get an entry from the store (fails if non-existent)") .version("0.1") .arg(Arg::with_name("id") .long("id") From 203e649b4fe07a83d260fcd71092f269ac98cd71 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Fri, 27 May 2016 11:26:06 +0200 Subject: [PATCH 174/288] Make print_entry() pub to be available in get() implementation --- imag-store/src/retrieve.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imag-store/src/retrieve.rs b/imag-store/src/retrieve.rs index 113d5e8e..408cad4e 100644 --- a/imag-store/src/retrieve.rs +++ b/imag-store/src/retrieve.rs @@ -35,7 +35,7 @@ pub fn retrieve(rt: &Runtime) { }); } -fn print_entry(rt: &Runtime, scmd: &ArgMatches, e: FileLockEntry) { +pub fn print_entry(rt: &Runtime, scmd: &ArgMatches, e: FileLockEntry) { if do_print_raw(scmd) { debug!("Printing raw content..."); println!("{}", e.to_str()); From 95c640c1e9197e1664524a91a76ed4ffc8f75c64 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Fri, 27 May 2016 11:26:22 +0200 Subject: [PATCH 175/288] Implement get() functionality --- imag-store/src/get.rs | 31 +++++++++++++++++++++++++++++++ imag-store/src/main.rs | 25 ++++++++++++++----------- 2 files changed, 45 insertions(+), 11 deletions(-) create mode 100644 imag-store/src/get.rs diff --git a/imag-store/src/get.rs b/imag-store/src/get.rs new file mode 100644 index 00000000..813f48a4 --- /dev/null +++ b/imag-store/src/get.rs @@ -0,0 +1,31 @@ +use std::process::exit; + +use libimagstore::storeid::build_entry_path; +use libimagrt::runtime::Runtime; +use libimagerror::trace::trace_error; + +use retrieve::print_entry; + +pub fn get(rt: &Runtime) { + rt.cli() + .subcommand_matches("get") + .map(|scmd| { + scmd.value_of("id") + .map(|id| { + let path = build_entry_path(rt.store(), id); + if path.is_err() { + trace_error(&path.unwrap_err()); + exit(1); + } + let path = path.unwrap(); + debug!("path = {:?}", path); + + match rt.store().get(path) { + Ok(Some(entry)) => print_entry(rt, scmd, entry), + Ok(None) => info!("No entry found"), + Err(e) => trace_error(&e), + } + }) + }); +} + diff --git a/imag-store/src/main.rs b/imag-store/src/main.rs index 6537687e..c2996fc1 100644 --- a/imag-store/src/main.rs +++ b/imag-store/src/main.rs @@ -26,19 +26,21 @@ extern crate libimagutil; use libimagrt::setup::generate_runtime_setup; -mod error; -mod ui; mod create; -mod retrieve; -mod update; mod delete; +mod error; +mod get; +mod retrieve; +mod ui; +mod update; mod util; -use ui::build_ui; use create::create; -use retrieve::retrieve; -use update::update; use delete::delete; +use get::get; +use retrieve::retrieve; +use ui::build_ui; +use update::update; fn main() { let rt = generate_runtime_setup("imag-store", @@ -56,10 +58,11 @@ fn main() { |name| { debug!("Call: {}", name); match name { - "create" => create(&rt), - "retrieve" => retrieve(&rt), - "update" => update(&rt), - "delete" => delete(&rt), + "create" => create(&rt), + "delete" => delete(&rt), + "get" => get(&rt), + "retrieve" => retrieve(&rt), + "update" => update(&rt), _ => { debug!("Unknown command"); // More error handling From 42289a085e6cdfa3b4ca205a271004e59a756327 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sat, 28 May 2016 17:10:34 +0200 Subject: [PATCH 176/288] Fix glob() pattern --- libimagstore/src/store.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libimagstore/src/store.rs b/libimagstore/src/store.rs index 820384e4..d2c8edfd 100644 --- a/libimagstore/src/store.rs +++ b/libimagstore/src/store.rs @@ -410,7 +410,7 @@ impl Store { path.to_str() .ok_or(SE::new(SEK::EncodingError, None)) .and_then(|path| { - let path = [ path, "/*" ].join(""); + let path = [ path, "/**/*" ].join(""); debug!("glob()ing with '{}'", path); glob(&path[..]).map_err(|e| SE::new(SEK::GlobError, Some(Box::new(e)))) }) From b71c511b8f7eb11dfc605a235fe3bc615a497846 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sat, 28 May 2016 17:39:24 +0200 Subject: [PATCH 177/288] Initial import --- libimagtimeui/Cargo.toml | 6 ++++++ libimagtimeui/src/lib.rs | 6 ++++++ 2 files changed, 12 insertions(+) create mode 100644 libimagtimeui/Cargo.toml create mode 100644 libimagtimeui/src/lib.rs diff --git a/libimagtimeui/Cargo.toml b/libimagtimeui/Cargo.toml new file mode 100644 index 00000000..c532576f --- /dev/null +++ b/libimagtimeui/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "libimagtimeui" +version = "0.1.0" +authors = ["Matthias Beyer "] + +[dependencies] diff --git a/libimagtimeui/src/lib.rs b/libimagtimeui/src/lib.rs new file mode 100644 index 00000000..cdfbe1aa --- /dev/null +++ b/libimagtimeui/src/lib.rs @@ -0,0 +1,6 @@ +#[cfg(test)] +mod tests { + #[test] + fn it_works() { + } +} From b817f1ba46a9a1b7708969dcf7ab97f755cf83b8 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sat, 28 May 2016 17:42:39 +0200 Subject: [PATCH 178/288] Add dependencies --- libimagtimeui/Cargo.toml | 8 ++++++++ libimagtimeui/src/lib.rs | 12 ++++++------ 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/libimagtimeui/Cargo.toml b/libimagtimeui/Cargo.toml index c532576f..21a4bbb8 100644 --- a/libimagtimeui/Cargo.toml +++ b/libimagtimeui/Cargo.toml @@ -4,3 +4,11 @@ version = "0.1.0" authors = ["Matthias Beyer "] [dependencies] +lazy_static = "0.1" +log = "0.3" +chrono = "0.2" +regex = "0.1" + +[dependencies.libimagerror] +path = "../libimagerror" + diff --git a/libimagtimeui/src/lib.rs b/libimagtimeui/src/lib.rs index cdfbe1aa..a23c3557 100644 --- a/libimagtimeui/src/lib.rs +++ b/libimagtimeui/src/lib.rs @@ -1,6 +1,6 @@ -#[cfg(test)] -mod tests { - #[test] - fn it_works() { - } -} +extern crate chrono; +extern crate regex; +#[macro_use] extern crate lazy_static; +#[macro_use] extern crate log; + +#[macro_use] extern crate libimagerror; From 42b79bb0ee28c29a07896168a73a07f44a117ba3 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sat, 28 May 2016 17:51:45 +0200 Subject: [PATCH 179/288] Add ui simple helpers --- libimagtimeui/src/ui.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 libimagtimeui/src/ui.rs diff --git a/libimagtimeui/src/ui.rs b/libimagtimeui/src/ui.rs new file mode 100644 index 00000000..691e8c47 --- /dev/null +++ b/libimagtimeui/src/ui.rs @@ -0,0 +1,12 @@ +pub fn time_ui_fmtstr() -> &'static str { + "YYYY-MM-DD[THH[:mm[:ss]]]" +} + +pub fn time_ui_fmtstr_expl() -> &'static str { + #r"In the UI, the format for Time is always YEAR-MONTH-DAY. + Optionally, Time can be specified by seperating it from the date with 'T'. + Minutes and Seconds are optional. + "# +} + + From cc00e14cf7ac8975fb2a163efebcef0c40e2c13b Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sat, 28 May 2016 17:53:13 +0200 Subject: [PATCH 180/288] Add Date type --- libimagtimeui/src/date.rs | 34 ++++++++++++++++++++++++++++++++++ libimagtimeui/src/lib.rs | 3 +++ 2 files changed, 37 insertions(+) create mode 100644 libimagtimeui/src/date.rs diff --git a/libimagtimeui/src/date.rs b/libimagtimeui/src/date.rs new file mode 100644 index 00000000..b003af89 --- /dev/null +++ b/libimagtimeui/src/date.rs @@ -0,0 +1,34 @@ +use chrono::naive::date::NaiveDate as ChronoNaiveDate; + +use parse::Parse; + +pub struct Date { + year: i32, + month: u32, + day: u32, +} + +impl Date { + + fn new(year: i32, month: u32, day: u32) -> Date { + unimplemented!() + } + +} + +impl Into for Date { + + fn into(self) -> ChronoNaiveDate { + ChronoNaiveDate::from_ymd(self.year, self.month, self.day) + } + +} + +impl Parse for Date { + + fn parse(s: &str) -> Option { + unimplemented!() + } + +} + diff --git a/libimagtimeui/src/lib.rs b/libimagtimeui/src/lib.rs index a23c3557..2ec7af12 100644 --- a/libimagtimeui/src/lib.rs +++ b/libimagtimeui/src/lib.rs @@ -4,3 +4,6 @@ extern crate regex; #[macro_use] extern crate log; #[macro_use] extern crate libimagerror; + +pub mod date; + From ef81d87d9444e51ddf0aa7380e168dda793361b9 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sat, 28 May 2016 17:53:20 +0200 Subject: [PATCH 181/288] Add Time type --- libimagtimeui/src/lib.rs | 1 + libimagtimeui/src/time.rs | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 libimagtimeui/src/time.rs diff --git a/libimagtimeui/src/lib.rs b/libimagtimeui/src/lib.rs index 2ec7af12..2d527f50 100644 --- a/libimagtimeui/src/lib.rs +++ b/libimagtimeui/src/lib.rs @@ -6,4 +6,5 @@ extern crate regex; #[macro_use] extern crate libimagerror; pub mod date; +pub mod time; diff --git a/libimagtimeui/src/time.rs b/libimagtimeui/src/time.rs new file mode 100644 index 00000000..7da49971 --- /dev/null +++ b/libimagtimeui/src/time.rs @@ -0,0 +1,34 @@ +use chrono::naive::time::NaiveTime as ChronoNaiveTime; + +use parse::Parse; + +pub struct Time { + hour: u32, + minute: u32, + second: u32, +} + +impl Time { + + fn new(hour: u32, minute: u32, second: u32) -> Time { + unimplemented!() + } + +} + +impl Into for Time { + + fn into(self) -> ChronoNaiveTime { + ChronoNaiveTime::from_hms(self.hour, self.minute, self.second) + } + +} + +impl Parse for Time { + + fn parse(s: &str) -> Option