diff --git a/melib/src/addressbook/vcard.rs b/melib/src/addressbook/vcard.rs index 35ad9c00..2556b6d9 100644 --- a/melib/src/addressbook/vcard.rs +++ b/melib/src/addressbook/vcard.rs @@ -28,7 +28,7 @@ //! - Parameter escaping [RFC 6868 Parameter Value Encoding in iCalendar and vCard](https://datatracker.ietf.org/doc/rfc6868/) use super::*; -use crate::error::{MeliError, Result}; +use crate::error::{Error, Result}; use crate::parsec::{match_literal_anycase, one_or_more, peek, prefix, take_until, Parser}; use std::collections::HashMap; use std::convert::TryInto; @@ -86,7 +86,7 @@ impl CardDeserializer { input = if (!input.starts_with(HEADER_CRLF) || !input.ends_with(FOOTER_CRLF)) && (!input.starts_with(HEADER_LF) || !input.ends_with(FOOTER_LF)) { - return Err(MeliError::new(format!("Error while parsing vcard: input does not start or end with correct header and footer. input is:\n{:?}", input))); + return Err(Error::new(format!("Error while parsing vcard: input does not start or end with correct header and footer. input is:\n{:?}", input))); } else if input.starts_with(HEADER_CRLF) { &input[HEADER_CRLF.len()..input.len() - FOOTER_CRLF.len()] } else { @@ -147,13 +147,13 @@ impl CardDeserializer { } } if !has_colon { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Error while parsing vcard: error at line {}, no colon. {:?}", l, el ))); } if name.is_empty() { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Error while parsing vcard: error at line {}, no name for content line. {:?}", l, el ))); @@ -166,7 +166,7 @@ impl CardDeserializer { } impl TryInto for VCard { - type Error = crate::error::MeliError; + type Error = crate::error::Error; fn try_into(mut self) -> crate::error::Result { let mut card = Card::new(); @@ -187,7 +187,7 @@ impl TryInto for VCard { if let Some(val) = self.0.remove("FN") { card.set_name(val.value); } else { - return Err(MeliError::new("FN entry missing in VCard.")); + return Err(Error::new("FN entry missing in VCard.")); } if let Some(val) = self.0.remove("NICKNAME") { card.set_additionalname(val.value); diff --git a/melib/src/backends.rs b/melib/src/backends.rs index 78eec1c2..588291a5 100644 --- a/melib/src/backends.rs +++ b/melib/src/backends.rs @@ -40,7 +40,7 @@ pub use self::imap::ImapType; #[cfg(feature = "imap_backend")] pub use self::nntp::NntpType; use crate::conf::AccountSettings; -use crate::error::{ErrorKind, MeliError, Result}; +use crate::error::{ErrorKind, Error, Result}; #[cfg(feature = "maildir_backend")] use self::maildir::MaildirType; @@ -227,7 +227,7 @@ impl Backends { .map .get(key) .ok_or_else(|| { - MeliError::new(format!( + Error::new(format!( "{}{} is not a valid mail backend. {}", if key == "notmuch" { NOTMUCH_ERROR_MSG @@ -260,8 +260,8 @@ pub enum BackendEvent { //Job(Box> + Send + 'static>) } -impl From for BackendEvent { - fn from(val: MeliError) -> BackendEvent { +impl From for BackendEvent { + fn from(val: Error) -> BackendEvent { BackendEvent::Notice { description: val.summary.to_string(), content: Some(val.to_string()), @@ -279,7 +279,7 @@ pub enum RefreshEventKind { Remove(EnvelopeHash), NewFlags(EnvelopeHash, (Flag, Vec)), Rescan, - Failure(MeliError), + Failure(Error), MailboxCreate(Mailbox), MailboxDelete(MailboxHash), MailboxRename { @@ -426,7 +426,7 @@ pub trait MailBackend: ::std::fmt::Debug + Send + Sync { _mailbox_hash: Option, _flags: Option, ) -> ResultFuture<()> { - Err(MeliError::new("Submission not supported in this backend.") + Err(Error::new("Submission not supported in this backend.") .set_kind(ErrorKind::NotSupported)) } } diff --git a/melib/src/backends/imap.rs b/melib/src/backends/imap.rs index 980812fa..55d68111 100644 --- a/melib/src/backends/imap.rs +++ b/melib/src/backends/imap.rs @@ -45,7 +45,7 @@ use crate::collection::Collection; use crate::conf::AccountSettings; use crate::connections::timeout; use crate::email::{parser::BytesExt, *}; -use crate::error::{MeliError, Result, ResultIntoMeliError}; +use crate::error::{Error, Result, ResultIntoError}; use futures::lock::Mutex as FutureMutex; use futures::stream::Stream; use std::collections::hash_map::DefaultHasher; @@ -105,7 +105,7 @@ type Capabilities = HashSet>; macro_rules! get_conf_val { ($s:ident[$var:literal]) => { $s.extra.get($var).ok_or_else(|| { - MeliError::new(format!( + Error::new(format!( "Configuration error ({}): IMAP connection requires the field `{}` set", $s.name.as_str(), $var @@ -117,7 +117,7 @@ macro_rules! get_conf_val { .get($var) .map(|v| { <_>::from_str(v).map_err(|e| { - MeliError::new(format!( + Error::new(format!( "Configuration error ({}): Invalid value for field `{}`: {}\n{}", $s.name.as_str(), $var, @@ -180,7 +180,7 @@ impl UIDStore { collection: Default::default(), is_online: Arc::new(Mutex::new(( SystemTime::now(), - Err(MeliError::new("Account is uninitialised.")), + Err(Error::new("Account is uninitialised.")), ))), event_consumer, timeout, @@ -424,7 +424,7 @@ impl MailBackend for ImapType { m ).chars()); } - return Err(MeliError::new(err_string)); + return Err(Error::new(err_string)); } mailboxes.retain(|_, f| (self.is_subscribed)(f.path())); */ @@ -531,7 +531,7 @@ impl MailBackend for ImapType { { *v } else { - return Err(MeliError::new( + return Err(Error::new( "Message not found in local cache, it might have been deleted before you requested it." )); }; @@ -560,10 +560,10 @@ impl MailBackend for ImapType { let mailboxes = uid_store.mailboxes.lock().await; let mailbox = mailboxes.get(&mailbox_hash).ok_or_else(|| { - MeliError::new(format!("Mailbox with hash {} not found.", mailbox_hash)) + Error::new(format!("Mailbox with hash {} not found.", mailbox_hash)) })?; if !mailbox.permissions.lock().unwrap().create_messages { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "You are not allowed to create messages in mailbox {}", mailbox.path() ))); @@ -644,7 +644,7 @@ impl MailBackend for ImapType { let mailboxes = uid_store.mailboxes.lock().await; let mailbox = mailboxes .get(&destination_mailbox_hash) - .ok_or_else(|| MeliError::new("Destination mailbox not found"))?; + .ok_or_else(|| Error::new("Destination mailbox not found"))?; mailbox.imap_path().to_string() }; let mut response = Vec::with_capacity(8 * 1024); @@ -750,7 +750,7 @@ impl MailBackend for ImapType { } Ok(_) => { crate::log(format!("Application error: more than one flag bit set in set_flags: {:?}", flags), crate::ERROR); - return Err(MeliError::new(format!("Application error: more than one flag bit set in set_flags: {:?}", flags)).set_kind(crate::ErrorKind::Bug)); + return Err(Error::new(format!("Application error: more than one flag bit set in set_flags: {:?}", flags)).set_kind(crate::ErrorKind::Bug)); } Err(tag) => { let hash = TagHash::from_bytes(tag.as_bytes()); @@ -816,7 +816,7 @@ impl MailBackend for ImapType { ), crate::ERROR, ); - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Application error: more than one flag bit set in set_flags: {:?}", flags ))); } @@ -908,7 +908,7 @@ impl MailBackend for ImapType { let mailboxes = uid_store.mailboxes.lock().await; if mailboxes.values().any(|f| f.path == path) { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Mailbox named `{}` already exists.", path, ))); @@ -950,7 +950,7 @@ impl MailBackend for ImapType { ret?; let new_hash = MailboxHash::from_bytes(path.as_str().as_bytes()); uid_store.mailboxes.lock().await.clear(); - Ok((new_hash, new_mailbox_fut?.await.map_err(|err| MeliError::new(format!("Mailbox create was succesful (returned `{}`) but listing mailboxes afterwards returned `{}`", String::from_utf8_lossy(&response), err)))?)) + Ok((new_hash, new_mailbox_fut?.await.map_err(|err| Error::new(format!("Mailbox create was succesful (returned `{}`) but listing mailboxes afterwards returned `{}`", String::from_utf8_lossy(&response), err)))?)) })) } @@ -970,7 +970,7 @@ impl MailBackend for ImapType { imap_path = mailboxes[&mailbox_hash].imap_path().to_string(); let permissions = mailboxes[&mailbox_hash].permissions(); if !permissions.delete_mailbox { - return Err(MeliError::new(format!("You do not have permission to delete `{}`. Set permissions for this mailbox are {}", mailboxes[&mailbox_hash].name(), permissions))); + return Err(Error::new(format!("You do not have permission to delete `{}`. Set permissions for this mailbox are {}", mailboxes[&mailbox_hash].name(), permissions))); } } let mut response = Vec::with_capacity(8 * 1024); @@ -1064,7 +1064,7 @@ impl MailBackend for ImapType { let mailboxes = uid_store.mailboxes.lock().await; let permissions = mailboxes[&mailbox_hash].permissions(); if !permissions.delete_mailbox { - return Err(MeliError::new(format!("You do not have permission to rename mailbox `{}` (rename is equivalent to delete + create). Set permissions for this mailbox are {}", mailboxes[&mailbox_hash].name(), permissions))); + return Err(Error::new(format!("You do not have permission to rename mailbox `{}` (rename is equivalent to delete + create). Set permissions for this mailbox are {}", mailboxes[&mailbox_hash].name(), permissions))); } if mailboxes[&mailbox_hash].separator != b'/' { new_path = new_path.replace( @@ -1107,10 +1107,10 @@ impl MailBackend for ImapType { let mailboxes = uid_store.mailboxes.lock().await; let permissions = mailboxes[&mailbox_hash].permissions(); if !permissions.change_permissions { - return Err(MeliError::new(format!("You do not have permission to change permissions for mailbox `{}`. Set permissions for this mailbox are {}", mailboxes[&mailbox_hash].name(), permissions))); + return Err(Error::new(format!("You do not have permission to change permissions for mailbox `{}`. Set permissions for this mailbox are {}", mailboxes[&mailbox_hash].name(), permissions))); } - Err(MeliError::new("Unimplemented.")) + Err(Error::new("Unimplemented.")) })) } @@ -1120,7 +1120,7 @@ impl MailBackend for ImapType { mailbox_hash: Option, ) -> ResultFuture> { if mailbox_hash.is_none() { - return Err(MeliError::new( + return Err(Error::new( "Cannot search without specifying mailbox on IMAP", )); } @@ -1245,7 +1245,7 @@ impl MailBackend for ImapType { )); } } - Err(MeliError::new( + Err(Error::new( String::from_utf8_lossy(&response).to_string(), )) })) @@ -1263,7 +1263,7 @@ impl ImapType { let use_oauth2: bool = get_conf_val!(s["use_oauth2"], false)?; let server_password = if !s.extra.contains_key("server_password_command") { if use_oauth2 { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "({}) `use_oauth2` use requires `server_password_command` set with a command that returns an OAUTH2 token. Consult documentation for guidance.", s.name, ))); @@ -1278,7 +1278,7 @@ impl ImapType { .stderr(std::process::Stdio::piped()) .output()?; if !output.status.success() { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "({}) server_password_command `{}` returned {}: {}", s.name, get_conf_val!(s["server_password_command"])?, @@ -1299,7 +1299,7 @@ impl ImapType { let keep_offline_cache = get_conf_val!(s["offline_cache"], false)?; #[cfg(not(feature = "sqlite3"))] if keep_offline_cache { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "({}) keep_offline_cache is true but melib is not compiled with sqlite3", s.name, ))); @@ -1512,7 +1512,7 @@ impl ImapType { ($s:ident[$var:literal]) => {{ keys.insert($var); $s.extra.remove($var).ok_or_else(|| { - MeliError::new(format!( + Error::new(format!( "Configuration error ({}): IMAP connection requires the field `{}` set", $s.name.as_str(), $var @@ -1525,7 +1525,7 @@ impl ImapType { .remove($var) .map(|v| { <_>::from_str(&v).map_err(|e| { - MeliError::new(format!( + Error::new(format!( "Configuration error ({}): Invalid value for field `{}`: {}\n{}", $s.name.as_str(), $var, @@ -1543,14 +1543,14 @@ impl ImapType { keys.insert("server_password_command"); if !s.extra.contains_key("server_password_command") { if use_oauth2 { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "({}) `use_oauth2` use requires `server_password_command` set with a command that returns an OAUTH2 token. Consult documentation for guidance.", s.name, ))); } get_conf_val!(s["server_password"])?; } else if s.extra.contains_key("server_password") { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Configuration error ({}): both server_password and server_password_command are set, cannot choose", s.name.as_str(), ))); @@ -1560,7 +1560,7 @@ impl ImapType { let use_tls = get_conf_val!(s["use_tls"], true)?; let use_starttls = get_conf_val!(s["use_starttls"], false)?; if !use_tls && use_starttls { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Configuration error ({}): incompatible use_tls and use_starttls values: use_tls = false, use_starttls = true", s.name.as_str(), ))); @@ -1572,7 +1572,7 @@ impl ImapType { { let keep_offline_cache = get_conf_val!(s["offline_cache"], false)?; if keep_offline_cache { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "({}) keep_offline_cache is true but melib is not compiled with sqlite3", s.name, ))); @@ -1584,7 +1584,7 @@ impl ImapType { get_conf_val!(s["use_deflate"], true)?; #[cfg(not(feature = "deflate_compression"))] if s.extra.contains_key("use_deflate") { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Configuration error ({}): setting `use_deflate` is set but this version of meli isn't compiled with DEFLATE support.", s.name.as_str(), ))); @@ -1597,7 +1597,7 @@ impl ImapType { .collect::>(); let diff = extra_keys.difference(&keys).collect::>(); if !diff.is_empty() { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Configuration error ({}): the following flags are set but are not recognized: {:?}.", s.name.as_str(), diff ))); diff --git a/melib/src/backends/imap/cache.rs b/melib/src/backends/imap/cache.rs index 125dccff..f0bca452 100644 --- a/melib/src/backends/imap/cache.rs +++ b/melib/src/backends/imap/cache.rs @@ -441,7 +441,7 @@ mod sqlite3_m { .cloned() .unwrap_or_default(); if self.mailbox_state(mailbox_hash)?.is_none() { - return Err(MeliError::new("Mailbox is not in cache").set_kind(ErrorKind::Bug)); + return Err(Error::new("Mailbox is not in cache").set_kind(ErrorKind::Bug)); } let Self { ref mut connection, @@ -483,7 +483,7 @@ mod sqlite3_m { refresh_events: &[(UID, RefreshEvent)], ) -> Result<()> { if self.mailbox_state(mailbox_hash)?.is_none() { - return Err(MeliError::new("Mailbox is not in cache").set_kind(ErrorKind::Bug)); + return Err(Error::new("Mailbox is not in cache").set_kind(ErrorKind::Bug)); } let Self { ref mut connection, @@ -691,7 +691,7 @@ mod default_m { impl ImapCacheReset for DefaultCache { fn reset_db(uid_store: &UIDStore) -> Result<()> { - Err(MeliError::new("melib is not built with any imap cache").set_kind(ErrorKind::Bug)) + Err(Error::new("melib is not built with any imap cache").set_kind(ErrorKind::Bug)) } } @@ -701,7 +701,7 @@ mod default_m { } fn mailbox_state(&mut self, _mailbox_hash: MailboxHash) -> Result> { - Err(MeliError::new("melib is not built with any imap cache").set_kind(ErrorKind::Bug)) + Err(Error::new("melib is not built with any imap cache").set_kind(ErrorKind::Bug)) } fn clear( @@ -709,11 +709,11 @@ mod default_m { _mailbox_hash: MailboxHash, _select_response: &SelectResponse, ) -> Result<()> { - Err(MeliError::new("melib is not built with any imap cache").set_kind(ErrorKind::Bug)) + Err(Error::new("melib is not built with any imap cache").set_kind(ErrorKind::Bug)) } fn envelopes(&mut self, _mailbox_hash: MailboxHash) -> Result>> { - Err(MeliError::new("melib is not built with any imap cache").set_kind(ErrorKind::Bug)) + Err(Error::new("melib is not built with any imap cache").set_kind(ErrorKind::Bug)) } fn insert_envelopes( @@ -721,7 +721,7 @@ mod default_m { _mailbox_hash: MailboxHash, _fetches: &[FetchResponse<'_>], ) -> Result<()> { - Err(MeliError::new("melib is not built with any imap cache").set_kind(ErrorKind::Bug)) + Err(Error::new("melib is not built with any imap cache").set_kind(ErrorKind::Bug)) } fn update_mailbox( @@ -729,7 +729,7 @@ mod default_m { _mailbox_hash: MailboxHash, _select_response: &SelectResponse, ) -> Result<()> { - Err(MeliError::new("melib is not built with any imap cache").set_kind(ErrorKind::Bug)) + Err(Error::new("melib is not built with any imap cache").set_kind(ErrorKind::Bug)) } fn update( @@ -737,7 +737,7 @@ mod default_m { _mailbox_hash: MailboxHash, _refresh_events: &[(UID, RefreshEvent)], ) -> Result<()> { - Err(MeliError::new("melib is not built with any imap cache").set_kind(ErrorKind::Bug)) + Err(Error::new("melib is not built with any imap cache").set_kind(ErrorKind::Bug)) } fn find_envelope( @@ -745,7 +745,7 @@ mod default_m { _identifier: std::result::Result, _mailbox_hash: MailboxHash, ) -> Result> { - Err(MeliError::new("melib is not built with any imap cache").set_kind(ErrorKind::Bug)) + Err(Error::new("melib is not built with any imap cache").set_kind(ErrorKind::Bug)) } fn rfc822( @@ -753,7 +753,7 @@ mod default_m { _identifier: std::result::Result, _mailbox_hash: MailboxHash, ) -> Result>> { - Err(MeliError::new("melib is not built with any imap cache").set_kind(ErrorKind::Bug)) + Err(Error::new("melib is not built with any imap cache").set_kind(ErrorKind::Bug)) } } } diff --git a/melib/src/backends/imap/cache/sync.rs b/melib/src/backends/imap/cache/sync.rs index 65101612..2497d4ea 100644 --- a/melib/src/backends/imap/cache/sync.rs +++ b/melib/src/backends/imap/cache/sync.rs @@ -687,13 +687,13 @@ impl ImapConnection { let (_, status) = protocol_parser::status_response(response.as_slice())?; if let Some(uidnext) = status.uidnext { if uidnext == 0 { - return Err(MeliError::new( + return Err(Error::new( "IMAP server error: zero UIDNEXT with nonzero exists.", )); } select_response.uidnext = uidnext; } else { - return Err(MeliError::new("IMAP server did not reply with UIDNEXT")); + return Err(Error::new("IMAP server did not reply with UIDNEXT")); } } Ok(select_response) diff --git a/melib/src/backends/imap/connection.rs b/melib/src/backends/imap/connection.rs index d581e31d..7b697b76 100644 --- a/melib/src/backends/imap/connection.rs +++ b/melib/src/backends/imap/connection.rs @@ -199,7 +199,7 @@ impl ImapStream { } } if !broken { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Could not initiate STARTTLS negotiation to {}.", path ))); @@ -240,7 +240,7 @@ impl ImapStream { let addr = if let Ok(a) = lookup_ipv4(path, server_conf.server_port) { a } else { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Could not lookup address {}", &path ))); @@ -302,15 +302,15 @@ impl ImapStream { let capabilities: std::result::Result, _> = res .split_rn() .find(|l| l.starts_with(b"* CAPABILITY")) - .ok_or_else(|| MeliError::new("")) + .ok_or_else(|| Error::new("")) .and_then(|res| { protocol_parser::capabilities(res) - .map_err(|_| MeliError::new("")) + .map_err(|_| Error::new("")) .map(|(_, v)| v) }); if capabilities.is_err() { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Could not connect to {}: expected CAPABILITY response but got:{}", &server_conf.server_hostname, String::from_utf8_lossy(&res) @@ -323,7 +323,7 @@ impl ImapStream { .iter() .any(|cap| cap.eq_ignore_ascii_case(b"IMAP4rev1")) { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Could not connect to {}: server is not IMAP4rev1 compliant", &server_conf.server_hostname ))); @@ -331,7 +331,7 @@ impl ImapStream { .iter() .any(|cap| cap.eq_ignore_ascii_case(b"LOGINDISABLED")) { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Could not connect to {}: server does not accept logins [LOGINDISABLED]", &server_conf.server_hostname )) @@ -352,7 +352,7 @@ impl ImapStream { .iter() .any(|cap| cap.eq_ignore_ascii_case(b"AUTH=XOAUTH2")) { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Could not connect to {}: OAUTH2 is enabled but server did not return AUTH=XOAUTH2 capability. Returned capabilities were: {}", &server_conf.server_hostname, capabilities.iter().map(|capability| @@ -402,7 +402,7 @@ impl ImapStream { if l.starts_with(tag_start.as_bytes()) { if !l[tag_start.len()..].trim().starts_with(b"OK ") { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Could not connect. Server replied with '{}'", String::from_utf8_lossy(l[tag_start.len()..].trim()) )) @@ -456,7 +456,7 @@ impl ImapStream { ret.extend_from_slice(&buf[0..b]); if let Some(mut pos) = ret[last_line_idx..].rfind("\r\n") { if ret[last_line_idx..].starts_with(b"* BYE") { - return Err(MeliError::new("Disconnected")); + return Err(Error::new("Disconnected")); } if let Some(prev_line) = ret[last_line_idx..pos + last_line_idx].rfind(b"\r\n") @@ -480,7 +480,7 @@ impl ImapStream { } } Err(err) => { - return Err(MeliError::from(err)); + return Err(Error::from(err)); } } } @@ -555,7 +555,7 @@ impl ImapConnection { uid_store: Arc, ) -> ImapConnection { ImapConnection { - stream: Err(MeliError::new("Offline".to_string())), + stream: Err(Error::new("Offline".to_string())), server_conf: server_conf.clone(), sync_policy: if uid_store.keep_offline_cache { SyncPolicy::Basic @@ -572,7 +572,7 @@ impl ImapConnection { if SystemTime::now().duration_since(time).unwrap_or_default() >= IMAP_PROTOCOL_TIMEOUT { - let err = MeliError::new(format!( + let err = Error::new(format!( "Connection timed out after {} seconds", IMAP_PROTOCOL_TIMEOUT.as_secs() )) @@ -660,7 +660,7 @@ impl ImapConnection { protocol, current_mailbox, timeout, - } = std::mem::replace(&mut self.stream, Err(MeliError::new("")))?; + } = std::mem::replace(&mut self.stream, Err(Error::new("")))?; let stream = stream.into_inner()?; self.stream = Ok(ImapStream { cmd_id, @@ -696,7 +696,7 @@ impl ImapConnection { let r: ImapResponse = ImapResponse::try_from(response.as_slice())?; match r { ImapResponse::Bye(ref response_code) => { - self.stream = Err(MeliError::new(format!( + self.stream = Err(Error::new(format!( "Offline: received BYE: {:?}", response_code ))); @@ -847,7 +847,7 @@ impl ImapConnection { ) }; if no_select { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Trying to select a \\NoSelect mailbox: {}", &imap_path )) @@ -933,7 +933,7 @@ impl ImapConnection { (m.imap_path().to_string(), m.no_select) }; if no_select { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Trying to examine a \\NoSelect mailbox: {}", &imap_path )) @@ -1033,7 +1033,7 @@ pub struct ImapBlockingConnection { result: Vec, prev_res_length: usize, pub conn: ImapConnection, - err: Option, + err: Option, } impl From for ImapBlockingConnection { @@ -1053,7 +1053,7 @@ impl ImapBlockingConnection { self.conn } - pub fn err(&mut self) -> Option { + pub fn err(&mut self) -> Option { self.err.take() } @@ -1104,7 +1104,7 @@ async fn read( *prev_failure = None; } Err(_err) => { - *err = Some(Into::::into(_err)); + *err = Some(Into::::into(_err)); *break_flag = true; *prev_failure = Some(SystemTime::now()); } diff --git a/melib/src/backends/imap/managesieve.rs b/melib/src/backends/imap/managesieve.rs index d60f2238..e8620d04 100644 --- a/melib/src/backends/imap/managesieve.rs +++ b/melib/src/backends/imap/managesieve.rs @@ -22,7 +22,7 @@ use super::{ImapConnection, ImapProtocol, ImapServerConf, UIDStore}; use crate::conf::AccountSettings; use crate::email::parser::IResult; -use crate::error::{MeliError, Result}; +use crate::error::{Error, Result}; use crate::get_conf_val; use crate::imap::RequiredResponses; use nom::{ @@ -313,7 +313,7 @@ impl ManageSieveConnection { let uid_store = Arc::new(UIDStore { is_online: Arc::new(Mutex::new(( SystemTime::now(), - Err(MeliError::new("Account is uninitialised.")), + Err(Error::new("Account is uninitialised.")), ))), ..UIDStore::new( account_hash, diff --git a/melib/src/backends/imap/operations.rs b/melib/src/backends/imap/operations.rs index 1f858f02..ccb79ae4 100644 --- a/melib/src/backends/imap/operations.rs +++ b/melib/src/backends/imap/operations.rs @@ -23,7 +23,7 @@ use super::*; use crate::backends::*; use crate::email::*; -use crate::error::MeliError; +use crate::error::Error; use std::sync::Arc; /// `BackendOp` implementor for Imap @@ -82,7 +82,7 @@ impl BackendOp for ImapOp { ); let mut results = protocol_parser::fetch_responses(&response)?.1; if results.len() != 1 { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Invalid/unexpected response: {:?}", response )) @@ -141,13 +141,13 @@ impl BackendOp for ImapOp { ); let v = protocol_parser::uid_fetch_flags_responses(&response) .map(|(_, v)| v) - .map_err(MeliError::from)?; + .map_err(Error::from)?; if v.len() != 1 { debug!("responses len is {}", v.len()); debug!(String::from_utf8_lossy(&response)); /* TODO: Trigger cache invalidation here. */ debug!("message with UID {} was not found", uid); - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Invalid/unexpected response: {:?}", response )) diff --git a/melib/src/backends/imap/protocol_parser.rs b/melib/src/backends/imap/protocol_parser.rs index 38a4f415..edcfe98d 100644 --- a/melib/src/backends/imap/protocol_parser.rs +++ b/melib/src/backends/imap/protocol_parser.rs @@ -25,7 +25,7 @@ use crate::email::parser::{ generic::{byte_in_range, byte_in_slice}, BytesExt, IResult, }; -use crate::error::ResultIntoMeliError; +use crate::error::ResultIntoError; use nom::{ branch::{alt, permutation}, bytes::complete::{is_a, is_not, tag, take, take_until, take_while}, @@ -255,11 +255,11 @@ pub enum ImapResponse { } impl TryFrom<&'_ [u8]> for ImapResponse { - type Error = MeliError; + type Error = Error; fn try_from(val: &'_ [u8]) -> Result { let val: &[u8] = val.split_rn().last().unwrap_or(val); let mut val = val[val.find(b" ").ok_or_else(|| { - MeliError::new(format!( + Error::new(format!( "Expected tagged IMAP response (OK,NO,BAD, etc) but found {:?}", val )) @@ -268,7 +268,7 @@ impl TryFrom<&'_ [u8]> for ImapResponse { // M12 NO [CANNOT] Invalid mailbox name: Name must not have \'/\' characters (0.000 + 0.098 + 0.097 secs).\r\n if val.ends_with(b" secs).") { val = &val[..val.rfind(b"(").ok_or_else(|| { - MeliError::new(format!( + Error::new(format!( "Expected tagged IMAP response (OK,NO,BAD, etc) but found {:?}", val )) @@ -286,7 +286,7 @@ impl TryFrom<&'_ [u8]> for ImapResponse { } else if val.starts_with(b"BYE") { Self::Bye(ResponseCode::from(&val[b"BYE ".len()..])) } else { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Expected tagged IMAP response (OK,NO,BAD, etc) but found {:?}", val ))); @@ -299,11 +299,11 @@ impl Into> for ImapResponse { match self { Self::Ok(_) | Self::Preauth(_) | Self::Bye(_) => Ok(()), Self::No(ResponseCode::Alert(msg)) | Self::Bad(ResponseCode::Alert(msg)) => { - Err(MeliError::new(msg)) + Err(Error::new(msg)) } - Self::No(err) => Err(MeliError::new(format!("{:?}", err))) + Self::No(err) => Err(Error::new(format!("{:?}", err))) .chain_err_summary(|| "IMAP NO Response.".to_string()), - Self::Bad(err) => Err(MeliError::new(format!("{:?}", err))) + Self::Bad(err) => Err(Error::new(format!("{:?}", err))) .chain_err_summary(|| "IMAP BAD Response.".to_string()), } } @@ -514,7 +514,7 @@ pub fn fetch_response(input: &[u8]) -> ImapParseResult> { macro_rules! should_start_with { ($input:expr, $tag:literal) => { if !$input.starts_with($tag) { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Expected `{}` but got `{:.50}`", String::from_utf8_lossy($tag), String::from_utf8_lossy(&$input) @@ -528,7 +528,7 @@ pub fn fetch_response(input: &[u8]) -> ImapParseResult> { macro_rules! bounds { () => { if i == input.len() { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Expected more input. Got: `{:.50}`", String::from_utf8_lossy(&input) ))); @@ -592,7 +592,7 @@ pub fn fetch_response(input: &[u8]) -> ImapParseResult> { ret.uid = Some(UID::from_str(unsafe { std::str::from_utf8_unchecked(uid) }).unwrap()); } else { - return debug!(Err(MeliError::new(format!( + return debug!(Err(Error::new(format!( "Unexpected input while parsing UID FETCH response. Got: `{:.40}`", String::from_utf8_lossy(input) )))); @@ -603,7 +603,7 @@ pub fn fetch_response(input: &[u8]) -> ImapParseResult> { ret.flags = Some(flags); i += (input.len() - i - rest.len()) + 1; } else { - return debug!(Err(MeliError::new(format!( + return debug!(Err(Error::new(format!( "Unexpected input while parsing UID FETCH response. Could not parse FLAGS: {:.40}.", String::from_utf8_lossy(&input[i..]) )))); @@ -619,7 +619,7 @@ pub fn fetch_response(input: &[u8]) -> ImapParseResult> { .and_then(std::num::NonZeroU64::new) .map(ModSequence); } else { - return debug!(Err(MeliError::new(format!( + return debug!(Err(Error::new(format!( "Unexpected input while parsing MODSEQ in UID FETCH response. Got: `{:.40}`", String::from_utf8_lossy(input) )))); @@ -638,7 +638,7 @@ pub fn fetch_response(input: &[u8]) -> ImapParseResult> { ret.body = Some(body); i += input.len() - i - rest.len(); } else { - return debug!(Err(MeliError::new(format!( + return debug!(Err(Error::new(format!( "Unexpected input while parsing UID FETCH response. Could not parse RFC822: {:.40}", String::from_utf8_lossy(&input[i..]) )))); @@ -649,7 +649,7 @@ pub fn fetch_response(input: &[u8]) -> ImapParseResult> { ret.envelope = Some(envelope); i += input.len() - i - rest.len(); } else { - return debug!(Err(MeliError::new(format!( + return debug!(Err(Error::new(format!( "Unexpected input while parsing UID FETCH response. Could not parse ENVELOPE: {:.40}", String::from_utf8_lossy(&input[i..]) )))); @@ -671,7 +671,7 @@ pub fn fetch_response(input: &[u8]) -> ImapParseResult> { } i += input.len() - i - rest.len(); } else { - return debug!(Err(MeliError::new(format!( + return debug!(Err(Error::new(format!( "Unexpected input while parsing UID FETCH response. Could not parse BODY[HEADER.FIELDS (REFERENCES)]: {:.40}", String::from_utf8_lossy(&input[i..]) )))); @@ -687,7 +687,7 @@ pub fn fetch_response(input: &[u8]) -> ImapParseResult> { } i += input.len() - i - rest.len(); } else { - return debug!(Err(MeliError::new(format!( + return debug!(Err(Error::new(format!( "Unexpected input while parsing UID FETCH response. Could not parse BODY[HEADER.FIELDS (\"REFERENCES\"): {:.40}", String::from_utf8_lossy(&input[i..]) )))); @@ -700,7 +700,7 @@ pub fn fetch_response(input: &[u8]) -> ImapParseResult> { "Got unexpected token while parsing UID FETCH response:\n`{}`\n", String::from_utf8_lossy(input) ); - return debug!(Err(MeliError::new(format!( + return debug!(Err(Error::new(format!( "Got unexpected token while parsing UID FETCH response: `{:.40}`", String::from_utf8_lossy(&input[i..]) )))); @@ -735,7 +735,7 @@ pub fn fetch_responses(mut input: &[u8]) -> ImapParseResult { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Unexpected input while parsing UID FETCH responses: {} `{:.40}`", err, String::from_utf8_lossy(input), @@ -747,7 +747,7 @@ pub fn fetch_responses(mut input: &[u8]) -> ImapParseResult Result { } else { let ret = String::from_utf8_lossy(input).to_string(); debug!("BAD/NO response in select: {}", &ret); - Err(MeliError::new(ret)) + Err(Error::new(ret)) } } diff --git a/melib/src/backends/imap/untagged.rs b/melib/src/backends/imap/untagged.rs index 785a8610..5f80beb3 100644 --- a/melib/src/backends/imap/untagged.rs +++ b/melib/src/backends/imap/untagged.rs @@ -309,7 +309,7 @@ impl ImapConnection { ); match super::protocol_parser::search_results_raw(&response) .map(|(_, v)| v) - .map_err(MeliError::from) + .map_err(Error::from) { Ok(&[]) => { debug!("UID SEARCH RECENT returned no results"); diff --git a/melib/src/backends/imap/watch.rs b/melib/src/backends/imap/watch.rs index 37f682d2..46ae2a2a 100644 --- a/melib/src/backends/imap/watch.rs +++ b/melib/src/backends/imap/watch.rs @@ -70,7 +70,7 @@ pub async fn idle(kit: ImapWatchKit) -> Result<()> { { Some(mailbox) => mailbox, None => { - return Err(MeliError::new("INBOX mailbox not found in local mailbox index. meli may have not parsed the IMAP mailboxes correctly")); + return Err(Error::new("INBOX mailbox not found in local mailbox index. meli may have not parsed the IMAP mailboxes correctly")); } }; let mailbox_hash = mailbox.hash(); diff --git a/melib/src/backends/jmap.rs b/melib/src/backends/jmap.rs index 8c2fe37c..657e7af1 100644 --- a/melib/src/backends/jmap.rs +++ b/melib/src/backends/jmap.rs @@ -23,7 +23,7 @@ use crate::backends::*; use crate::conf::AccountSettings; use crate::connections::timeout; use crate::email::*; -use crate::error::{MeliError, Result}; +use crate::error::{Error, Result}; use crate::Collection; use futures::lock::Mutex as FutureMutex; use isahc::config::RedirectPolicy; @@ -96,7 +96,7 @@ pub struct JmapServerConf { macro_rules! get_conf_val { ($s:ident[$var:literal]) => { $s.extra.get($var).ok_or_else(|| { - MeliError::new(format!( + Error::new(format!( "Configuration error ({}): JMAP connection requires the field `{}` set", $s.name.as_str(), $var @@ -108,7 +108,7 @@ macro_rules! get_conf_val { .get($var) .map(|v| { <_>::from_str(v).map_err(|e| { - MeliError::new(format!( + Error::new(format!( "Configuration error ({}): Invalid value for field `{}`: {}\n{}", $s.name.as_str(), $var, @@ -399,7 +399,7 @@ impl MailBackend for JmapType { if let Some(mailbox) = mailboxes_lck.get(&mailbox_hash) { mailbox.id.clone() } else { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Mailbox with hash {} not found", mailbox_hash ))); @@ -409,7 +409,7 @@ impl MailBackend for JmapType { let upload_response: UploadResponse = match serde_json::from_str(&res_text) { Err(err) => { - let err = MeliError::new(format!("BUG: Could not deserialize {} server JSON response properly, please report this!\nReply from server: {}", &conn.server_conf.server_url, &res_text)).set_source(Some(Arc::new(err))).set_kind(ErrorKind::Bug); + let err = Error::new(format!("BUG: Could not deserialize {} server JSON response properly, please report this!\nReply from server: {}", &conn.server_conf.server_url, &res_text)).set_source(Some(Arc::new(err))).set_kind(ErrorKind::Bug); *conn.store.online_status.lock().await = (Instant::now(), Err(err.clone())); return Err(err); } @@ -440,7 +440,7 @@ impl MailBackend for JmapType { let mut v: MethodResponse = match serde_json::from_str(&res_text) { Err(err) => { - let err = MeliError::new(format!("BUG: Could not deserialize {} server JSON response properly, please report this!\nReply from server: {}", &conn.server_conf.server_url, &res_text)).set_source(Some(Arc::new(err))).set_kind(ErrorKind::Bug); + let err = Error::new(format!("BUG: Could not deserialize {} server JSON response properly, please report this!\nReply from server: {}", &conn.server_conf.server_url, &res_text)).set_source(Some(Arc::new(err))).set_kind(ErrorKind::Bug); *conn.store.online_status.lock().await = (Instant::now(), Err(err.clone())); return Err(err); } @@ -450,14 +450,14 @@ impl MailBackend for JmapType { let ierr: Result = serde_json::from_str(&res_text).map_err(|err| err.into()); if let Ok(err) = ierr { - Err(MeliError::new(format!("Could not save message: {:?}", err))) + Err(Error::new(format!("Could not save message: {:?}", err))) } else { Err(err.into()) } })?; if let Some(err) = m.not_created.get(&creation_id) { - return Err(MeliError::new(format!("Could not save message: {:?}", err))); + return Err(Error::new(format!("Could not save message: {:?}", err))); } Ok(()) })) @@ -521,7 +521,7 @@ impl MailBackend for JmapType { let res_text = res.text().await?; let mut v: MethodResponse = match serde_json::from_str(&res_text) { Err(err) => { - let err = MeliError::new(format!("BUG: Could not deserialize {} server JSON response properly, please report this!\nReply from server: {}", &conn.server_conf.server_url, &res_text)).set_source(Some(Arc::new(err))).set_kind(ErrorKind::Bug); + let err = Error::new(format!("BUG: Could not deserialize {} server JSON response properly, please report this!\nReply from server: {}", &conn.server_conf.server_url, &res_text)).set_source(Some(Arc::new(err))).set_kind(ErrorKind::Bug); *conn.store.online_status.lock().await = (Instant::now(), Err(err.clone())); return Err(err); } @@ -540,7 +540,7 @@ impl MailBackend for JmapType { _mailbox_hash: MailboxHash, _new_path: String, ) -> ResultFuture { - Err(MeliError::new( + Err(Error::new( "Renaming mailbox is currently unimplemented for the JMAP backend.", )) } @@ -549,7 +549,7 @@ impl MailBackend for JmapType { &mut self, _path: String, ) -> ResultFuture<(MailboxHash, HashMap)> { - Err(MeliError::new( + Err(Error::new( "Creating mailbox is currently unimplemented for the JMAP backend.", )) } @@ -558,7 +558,7 @@ impl MailBackend for JmapType { &mut self, _mailbox_hash: MailboxHash, ) -> ResultFuture> { - Err(MeliError::new( + Err(Error::new( "Deleting a mailbox is currently unimplemented for the JMAP backend.", )) } @@ -568,7 +568,7 @@ impl MailBackend for JmapType { _mailbox_hash: MailboxHash, _val: bool, ) -> ResultFuture<()> { - Err(MeliError::new( + Err(Error::new( "Setting mailbox subscription is currently unimplemented for the JMAP backend.", )) } @@ -578,7 +578,7 @@ impl MailBackend for JmapType { _mailbox_hash: MailboxHash, _val: MailboxPermissions, ) -> ResultFuture<()> { - Err(MeliError::new( + Err(Error::new( "Setting mailbox permissions is currently unimplemented for the JMAP backend.", )) } @@ -596,13 +596,13 @@ impl MailBackend for JmapType { let (source_mailbox_id, destination_mailbox_id) = { let mailboxes_lck = store.mailboxes.read().unwrap(); if !mailboxes_lck.contains_key(&source_mailbox_hash) { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Could not find source mailbox with hash {}", source_mailbox_hash ))); } if !mailboxes_lck.contains_key(&destination_mailbox_hash) { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Could not find destination mailbox with hash {}", destination_mailbox_hash ))); @@ -657,7 +657,7 @@ impl MailBackend for JmapType { let mut v: MethodResponse = match serde_json::from_str(&res_text) { Err(err) => { - let err = MeliError::new(format!("BUG: Could not deserialize {} server JSON response properly, please report this!\nReply from server: {}", &conn.server_conf.server_url, &res_text)).set_source(Some(Arc::new(err))).set_kind(ErrorKind::Bug); + let err = Error::new(format!("BUG: Could not deserialize {} server JSON response properly, please report this!\nReply from server: {}", &conn.server_conf.server_url, &res_text)).set_source(Some(Arc::new(err))).set_kind(ErrorKind::Bug); *conn.store.online_status.lock().await = (Instant::now(), Err(err.clone())); return Err(err); } @@ -667,7 +667,7 @@ impl MailBackend for JmapType { let m = SetResponse::::try_from(v.method_responses.remove(0))?; if let Some(ids) = m.not_updated { if !ids.is_empty() { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Could not update ids: {}", ids.into_iter() .map(|err| err.to_string()) @@ -769,7 +769,7 @@ impl MailBackend for JmapType { //debug!("res_text = {}", &res_text); let mut v: MethodResponse = match serde_json::from_str(&res_text) { Err(err) => { - let err = MeliError::new(format!("BUG: Could not deserialize {} server JSON response properly, please report this!\nReply from server: {}", &conn.server_conf.server_url, &res_text)).set_source(Some(Arc::new(err))).set_kind(ErrorKind::Bug); + let err = Error::new(format!("BUG: Could not deserialize {} server JSON response properly, please report this!\nReply from server: {}", &conn.server_conf.server_url, &res_text)).set_source(Some(Arc::new(err))).set_kind(ErrorKind::Bug); *conn.store.online_status.lock().await = (Instant::now(), Err(err.clone())); return Err(err); } @@ -778,7 +778,7 @@ impl MailBackend for JmapType { *store.online_status.lock().await = (std::time::Instant::now(), Ok(())); let m = SetResponse::::try_from(v.method_responses.remove(0))?; if let Some(ids) = m.not_updated { - return Err(MeliError::new( + return Err(Error::new( ids.into_iter() .map(|err| err.to_string()) .collect::>() @@ -847,7 +847,7 @@ impl MailBackend for JmapType { _env_hashes: EnvelopeHashBatch, _mailbox_hash: MailboxHash, ) -> ResultFuture<()> { - Err(MeliError::new( + Err(Error::new( "Deleting messages is currently unimplemented for the JMAP backend.", )) } @@ -861,7 +861,7 @@ impl JmapType { ) -> Result> { let online_status = Arc::new(FutureMutex::new(( std::time::Instant::now(), - Err(MeliError::new("Account is uninitialised.")), + Err(Error::new("Account is uninitialised.")), ))); let server_conf = JmapServerConf::new(s)?; @@ -898,7 +898,7 @@ impl JmapType { macro_rules! get_conf_val { ($s:ident[$var:literal]) => { $s.extra.remove($var).ok_or_else(|| { - MeliError::new(format!( + Error::new(format!( "Configuration error ({}): JMAP connection requires the field `{}` set", $s.name.as_str(), $var @@ -910,7 +910,7 @@ impl JmapType { .remove($var) .map(|v| { <_>::from_str(&v).map_err(|e| { - MeliError::new(format!( + Error::new(format!( "Configuration error ({}): Invalid value for field `{}`: {}\n{}", $s.name.as_str(), $var, diff --git a/melib/src/backends/jmap/connection.rs b/melib/src/backends/jmap/connection.rs index 56239e47..916e463f 100644 --- a/melib/src/backends/jmap/connection.rs +++ b/melib/src/backends/jmap/connection.rs @@ -61,7 +61,7 @@ impl JmapConnection { jmap_session_resource_url.push_str("/.well-known/jmap"); let mut req = self.client.get_async(&jmap_session_resource_url).await.map_err(|err| { - let err = MeliError::new(format!("Could not connect to JMAP server endpoint for {}. Is your server url setting correct? (i.e. \"jmap.mailserver.org\") (Note: only session resource discovery via /.well-known/jmap is supported. DNS SRV records are not suppported.)\nError connecting to server: {}", &self.server_conf.server_url, &err)).set_source(Some(Arc::new(err))); + let err = Error::new(format!("Could not connect to JMAP server endpoint for {}. Is your server url setting correct? (i.e. \"jmap.mailserver.org\") (Note: only session resource discovery via /.well-known/jmap is supported. DNS SRV records are not suppported.)\nError connecting to server: {}", &self.server_conf.server_url, &err)).set_source(Some(Arc::new(err))); //*self.store.online_status.lock().await = (Instant::now(), Err(err.clone())); err })?; @@ -69,7 +69,7 @@ impl JmapConnection { if !req.status().is_success() { let kind: crate::error::NetworkErrorKind = req.status().into(); let res_text = req.text().await.unwrap_or_default(); - let err = MeliError::new(format!( + let err = Error::new(format!( "Could not connect to JMAP server endpoint for {}. Reply from server: {}", &self.server_conf.server_url, res_text )) @@ -82,7 +82,7 @@ impl JmapConnection { let session: JmapSession = match serde_json::from_str(&res_text) { Err(err) => { - let err = MeliError::new(format!("Could not connect to JMAP server endpoint for {}. Is your server url setting correct? (i.e. \"jmap.mailserver.org\") (Note: only session resource discovery via /.well-known/jmap is supported. DNS SRV records are not suppported.)\nReply from server: {}", &self.server_conf.server_url, &res_text)).set_source(Some(Arc::new(err))); + let err = Error::new(format!("Could not connect to JMAP server endpoint for {}. Is your server url setting correct? (i.e. \"jmap.mailserver.org\") (Note: only session resource discovery via /.well-known/jmap is supported. DNS SRV records are not suppported.)\nReply from server: {}", &self.server_conf.server_url, &res_text)).set_source(Some(Arc::new(err))); *self.store.online_status.lock().await = (Instant::now(), Err(err.clone())); return Err(err); } @@ -92,7 +92,7 @@ impl JmapConnection { .capabilities .contains_key("urn:ietf:params:jmap:core") { - let err = MeliError::new(format!("Server {} did not return JMAP Core capability (urn:ietf:params:jmap:core). Returned capabilities were: {}", &self.server_conf.server_url, session.capabilities.keys().map(String::as_str).collect::>().join(", "))); + let err = Error::new(format!("Server {} did not return JMAP Core capability (urn:ietf:params:jmap:core). Returned capabilities were: {}", &self.server_conf.server_url, session.capabilities.keys().map(String::as_str).collect::>().join(", "))); *self.store.online_status.lock().await = (Instant::now(), Err(err.clone())); return Err(err); } @@ -100,7 +100,7 @@ impl JmapConnection { .capabilities .contains_key("urn:ietf:params:jmap:mail") { - let err = MeliError::new(format!("Server {} does not support JMAP Mail capability (urn:ietf:params:jmap:mail). Returned capabilities were: {}", &self.server_conf.server_url, session.capabilities.keys().map(String::as_str).collect::>().join(", "))); + let err = Error::new(format!("Server {} does not support JMAP Mail capability (urn:ietf:params:jmap:mail). Returned capabilities were: {}", &self.server_conf.server_url, session.capabilities.keys().map(String::as_str).collect::>().join(", "))); *self.store.online_status.lock().await = (Instant::now(), Err(err.clone())); return Err(err); } @@ -194,7 +194,7 @@ impl JmapConnection { debug!(&res_text); let mut v: MethodResponse = match serde_json::from_str(&res_text) { Err(err) => { - let err = MeliError::new(format!("BUG: Could not deserialize {} server JSON response properly, please report this!\nReply from server: {}", &self.server_conf.server_url, &res_text)).set_source(Some(Arc::new(err))).set_kind(ErrorKind::Bug); + let err = Error::new(format!("BUG: Could not deserialize {} server JSON response properly, please report this!\nReply from server: {}", &self.server_conf.server_url, &res_text)).set_source(Some(Arc::new(err))).set_kind(ErrorKind::Bug); *self.store.online_status.lock().await = (Instant::now(), Err(err.clone())); return Err(err); } diff --git a/melib/src/backends/jmap/objects/email.rs b/melib/src/backends/jmap/objects/email.rs index 2c83409f..032c259c 100644 --- a/melib/src/backends/jmap/objects/email.rs +++ b/melib/src/backends/jmap/objects/email.rs @@ -835,10 +835,10 @@ pub struct EmailQueryChangesResponse { } impl std::convert::TryFrom<&RawValue> for EmailQueryChangesResponse { - type Error = crate::error::MeliError; + type Error = crate::error::Error; fn try_from(t: &RawValue) -> Result { let res: (String, EmailQueryChangesResponse, String) = - serde_json::from_str(t.get()).map_err(|err| crate::error::MeliError::new(format!("BUG: Could not deserialize server JSON response properly, please report this!\nReply from server: {}", &t)).set_source(Some(Arc::new(err))).set_kind(ErrorKind::Bug))?; + serde_json::from_str(t.get()).map_err(|err| crate::error::Error::new(format!("BUG: Could not deserialize server JSON response properly, please report this!\nReply from server: {}", &t)).set_source(Some(Arc::new(err))).set_kind(ErrorKind::Bug))?; assert_eq!(&res.0, "Email/queryChanges"); Ok(res.1) } diff --git a/melib/src/backends/jmap/objects/email/import.rs b/melib/src/backends/jmap/objects/email/import.rs index 7c360526..dffff920 100644 --- a/melib/src/backends/jmap/objects/email/import.rs +++ b/melib/src/backends/jmap/objects/email/import.rs @@ -182,10 +182,10 @@ pub struct ImportResponse { } impl std::convert::TryFrom<&RawValue> for ImportResponse { - type Error = crate::error::MeliError; + type Error = crate::error::Error; fn try_from(t: &RawValue) -> Result { let res: (String, ImportResponse, String) = - serde_json::from_str(t.get()).map_err(|err| crate::error::MeliError::new(format!("BUG: Could not deserialize server JSON response properly, please report this!\nReply from server: {}", &t)).set_source(Some(Arc::new(err))).set_kind(ErrorKind::Bug))?; + serde_json::from_str(t.get()).map_err(|err| crate::error::Error::new(format!("BUG: Could not deserialize server JSON response properly, please report this!\nReply from server: {}", &t)).set_source(Some(Arc::new(err))).set_kind(ErrorKind::Bug))?; assert_eq!(&res.0, &ImportCall::NAME); Ok(res.1) } diff --git a/melib/src/backends/jmap/protocol.rs b/melib/src/backends/jmap/protocol.rs index 0e4db8c1..264ce633 100644 --- a/melib/src/backends/jmap/protocol.rs +++ b/melib/src/backends/jmap/protocol.rs @@ -97,7 +97,7 @@ pub async fn get_mailboxes(conn: &JmapConnection) -> Result { - let err = MeliError::new(format!("BUG: Could not deserialize {} server JSON response properly, please report this!\nReply from server: {}", &conn.server_conf.server_url, &res_text)).set_source(Some(Arc::new(err))).set_kind(ErrorKind::Bug); + let err = Error::new(format!("BUG: Could not deserialize {} server JSON response properly, please report this!\nReply from server: {}", &conn.server_conf.server_url, &res_text)).set_source(Some(Arc::new(err))).set_kind(ErrorKind::Bug); *conn.store.online_status.lock().await = (Instant::now(), Err(err.clone())); return Err(err); } @@ -204,7 +204,7 @@ pub async fn get_message_list( let res_text = res.text().await?; let mut v: MethodResponse = match serde_json::from_str(&res_text) { Err(err) => { - let err = MeliError::new(format!("BUG: Could not deserialize {} server JSON response properly, please report this!\nReply from server: {}", &conn.server_conf.server_url, &res_text)).set_source(Some(Arc::new(err))).set_kind(ErrorKind::Bug); + let err = Error::new(format!("BUG: Could not deserialize {} server JSON response properly, please report this!\nReply from server: {}", &conn.server_conf.server_url, &res_text)).set_source(Some(Arc::new(err))).set_kind(ErrorKind::Bug); *conn.store.online_status.lock().await = (Instant::now(), Err(err.clone())); return Err(err); } @@ -284,7 +284,7 @@ pub async fn fetch( let mut v: MethodResponse = match serde_json::from_str(&res_text) { Err(err) => { - let err = MeliError::new(format!("BUG: Could not deserialize {} server JSON response properly, please report this!\nReply from server: {}", &conn.server_conf.server_url, &res_text)).set_source(Some(Arc::new(err))).set_kind(ErrorKind::Bug); + let err = Error::new(format!("BUG: Could not deserialize {} server JSON response properly, please report this!\nReply from server: {}", &conn.server_conf.server_url, &res_text)).set_source(Some(Arc::new(err))).set_kind(ErrorKind::Bug); *conn.store.online_status.lock().await = (Instant::now(), Err(err.clone())); return Err(err); } diff --git a/melib/src/backends/jmap/rfc8620.rs b/melib/src/backends/jmap/rfc8620.rs index 5142435c..bc394f59 100644 --- a/melib/src/backends/jmap/rfc8620.rs +++ b/melib/src/backends/jmap/rfc8620.rs @@ -411,10 +411,10 @@ pub struct GetResponse { } impl std::convert::TryFrom<&RawValue> for GetResponse { - type Error = crate::error::MeliError; - fn try_from(t: &RawValue) -> Result, crate::error::MeliError> { + type Error = crate::error::Error; + fn try_from(t: &RawValue) -> Result, crate::error::Error> { let res: (String, GetResponse, String) = - serde_json::from_str(t.get()).map_err(|err| crate::error::MeliError::new(format!("BUG: Could not deserialize server JSON response properly, please report this!\nReply from server: {}", &t)).set_source(Some(Arc::new(err))).set_kind(crate::error::ErrorKind::Bug))?; + serde_json::from_str(t.get()).map_err(|err| crate::error::Error::new(format!("BUG: Could not deserialize server JSON response properly, please report this!\nReply from server: {}", &t)).set_source(Some(Arc::new(err))).set_kind(crate::error::ErrorKind::Bug))?; assert_eq!(&res.0, &format!("{}/get", OBJ::NAME)); Ok(res.1) } @@ -516,10 +516,10 @@ pub struct QueryResponse { } impl std::convert::TryFrom<&RawValue> for QueryResponse { - type Error = crate::error::MeliError; - fn try_from(t: &RawValue) -> Result, crate::error::MeliError> { + type Error = crate::error::Error; + fn try_from(t: &RawValue) -> Result, crate::error::Error> { let res: (String, QueryResponse, String) = - serde_json::from_str(t.get()).map_err(|err| crate::error::MeliError::new(format!("BUG: Could not deserialize server JSON response properly, please report this!\nReply from server: {}", &t)).set_source(Some(Arc::new(err))).set_kind(crate::error::ErrorKind::Bug))?; + serde_json::from_str(t.get()).map_err(|err| crate::error::Error::new(format!("BUG: Could not deserialize server JSON response properly, please report this!\nReply from server: {}", &t)).set_source(Some(Arc::new(err))).set_kind(crate::error::ErrorKind::Bug))?; assert_eq!(&res.0, &format!("{}/query", OBJ::NAME)); Ok(res.1) } @@ -651,10 +651,10 @@ pub struct ChangesResponse { } impl std::convert::TryFrom<&RawValue> for ChangesResponse { - type Error = crate::error::MeliError; - fn try_from(t: &RawValue) -> Result, crate::error::MeliError> { + type Error = crate::error::Error; + fn try_from(t: &RawValue) -> Result, crate::error::Error> { let res: (String, ChangesResponse, String) = - serde_json::from_str(t.get()).map_err(|err| crate::error::MeliError::new(format!("BUG: Could not deserialize server JSON response properly, please report this!\nReply from server: {}", &t)).set_source(Some(Arc::new(err))).set_kind(crate::error::ErrorKind::Bug))?; + serde_json::from_str(t.get()).map_err(|err| crate::error::Error::new(format!("BUG: Could not deserialize server JSON response properly, please report this!\nReply from server: {}", &t)).set_source(Some(Arc::new(err))).set_kind(crate::error::ErrorKind::Bug))?; assert_eq!(&res.0, &format!("{}/changes", OBJ::NAME)); Ok(res.1) } @@ -850,10 +850,10 @@ pub struct SetResponse { } impl std::convert::TryFrom<&RawValue> for SetResponse { - type Error = crate::error::MeliError; - fn try_from(t: &RawValue) -> Result, crate::error::MeliError> { + type Error = crate::error::Error; + fn try_from(t: &RawValue) -> Result, crate::error::Error> { let res: (String, SetResponse, String) = - serde_json::from_str(t.get()).map_err(|err| crate::error::MeliError::new(format!("BUG: Could not deserialize server JSON response properly, please report this!\nReply from server: {}", &t)).set_source(Some(Arc::new(err))).set_kind(crate::error::ErrorKind::Bug))?; + serde_json::from_str(t.get()).map_err(|err| crate::error::Error::new(format!("BUG: Could not deserialize server JSON response properly, please report this!\nReply from server: {}", &t)).set_source(Some(Arc::new(err))).set_kind(crate::error::ErrorKind::Bug))?; assert_eq!(&res.0, &format!("{}/set", OBJ::NAME)); Ok(res.1) } diff --git a/melib/src/backends/maildir.rs b/melib/src/backends/maildir.rs index da755944..234b6e98 100644 --- a/melib/src/backends/maildir.rs +++ b/melib/src/backends/maildir.rs @@ -28,7 +28,7 @@ pub use stream::*; use crate::backends::*; use crate::email::Flag; -use crate::error::{MeliError, Result}; +use crate::error::{Error, Result}; use crate::shellexpand::ShellExpandTrait; use futures::stream::Stream; use std::collections::hash_map::DefaultHasher; @@ -76,7 +76,7 @@ impl MaildirOp { for e in map.iter() { debug!("{:#?}", e); } - return Err(MeliError::new("File not found")); + return Err(Error::new("File not found")); } Ok(if let Some(modif) = &map[&self.hash].modified { @@ -196,7 +196,7 @@ impl MaildirMailbox { for d in &["cur", "new", "tmp"] { p.push(d); if !p.is_dir() { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "{} is not a valid maildir mailbox", path.display() ))); diff --git a/melib/src/backends/maildir/backend.rs b/melib/src/backends/maildir/backend.rs index 9c9d1822..26c71366 100644 --- a/melib/src/backends/maildir/backend.rs +++ b/melib/src/backends/maildir/backend.rs @@ -28,7 +28,7 @@ use super::{MaildirMailbox, MaildirOp, MaildirPathTrait}; use crate::backends::{RefreshEventKind::*, *}; use crate::conf::AccountSettings; use crate::email::{Envelope, EnvelopeHash, Flag}; -use crate::error::{ErrorKind, MeliError, Result}; +use crate::error::{ErrorKind, Error, Result}; use crate::shellexpand::ShellExpandTrait; use crate::Collection; use futures::prelude::Stream; @@ -838,7 +838,7 @@ impl MailBackend for MaildirType { ) -> ResultFuture<()> { let hash_index = self.hash_indexes.clone(); if flags.iter().any(|(f, _)| f.is_err()) { - return Err(MeliError::new("Maildir doesn't support tags.")); + return Err(Error::new("Maildir doesn't support tags.")); } Ok(Box::pin(async move { @@ -863,7 +863,7 @@ impl MailBackend for MaildirType { let path = _path.to_str().unwrap(); // Assume UTF-8 validity let idx: usize = path .rfind(":2,") - .ok_or_else(|| MeliError::new(format!("Invalid email filename: {:?}", path)))? + .ok_or_else(|| Error::new(format!("Invalid email filename: {:?}", path)))? + 3; let mut new_name: String = path[..idx].to_string(); for (f, value) in flags.iter() { @@ -940,9 +940,9 @@ impl MailBackend for MaildirType { ) -> ResultFuture<()> { let hash_index = self.hash_indexes.clone(); if !self.mailboxes.contains_key(&source_mailbox_hash) { - return Err(MeliError::new("Invalid source mailbox hash").set_kind(ErrorKind::Bug)); + return Err(Error::new("Invalid source mailbox hash").set_kind(ErrorKind::Bug)); } else if !self.mailboxes.contains_key(&destination_mailbox_hash) { - return Err(MeliError::new("Invalid destination mailbox hash").set_kind(ErrorKind::Bug)); + return Err(Error::new("Invalid destination mailbox hash").set_kind(ErrorKind::Bug)); } let mut dest_path: PathBuf = self.mailboxes[&destination_mailbox_hash].fs_path().into(); dest_path.push("cur"); @@ -996,7 +996,7 @@ impl MailBackend for MaildirType { let mut path = self.path.clone(); path.push(&new_path); if !path.starts_with(&self.path) { - return Err(MeliError::new(format!("Path given (`{}`) is absolute. Please provide a path relative to the account's root mailbox.", &new_path))); + return Err(Error::new(format!("Path given (`{}`) is absolute. Please provide a path relative to the account's root mailbox.", &new_path))); } std::fs::create_dir(&path)?; @@ -1039,7 +1039,7 @@ impl MailBackend for MaildirType { &mut self, _mailbox_hash: MailboxHash, ) -> ResultFuture> { - Err(MeliError::new( + Err(Error::new( "Deleting mailboxes is currently unimplemented for maildir backend.", )) } @@ -1049,7 +1049,7 @@ impl MailBackend for MaildirType { _mailbox_hash: MailboxHash, _val: bool, ) -> ResultFuture<()> { - Err(MeliError::new( + Err(Error::new( "Mailbox subscriptions are not possible for the maildir backend.", )) } @@ -1059,7 +1059,7 @@ impl MailBackend for MaildirType { _mailbox_hash: MailboxHash, _new_path: String, ) -> ResultFuture { - Err(MeliError::new( + Err(Error::new( "Renaming mailboxes is currently unimplemented for maildir backend.", )) } @@ -1069,7 +1069,7 @@ impl MailBackend for MaildirType { _mailbox_hash: MailboxHash, _val: crate::backends::MailboxPermissions, ) -> ResultFuture<()> { - Err(MeliError::new( + Err(Error::new( "Setting mailbox permissions is not possible for the maildir backend.", )) } @@ -1080,7 +1080,7 @@ impl MailBackend for MaildirType { _mailbox_hash: Option, ) -> ResultFuture> { Err( - MeliError::new("Search is unimplemented for the maildir backend.") + Error::new("Search is unimplemented for the maildir backend.") .set_kind(ErrorKind::NotImplemented), ) } @@ -1107,7 +1107,7 @@ impl MaildirType { p: P, ) -> Result> { if !p.as_ref().exists() || !p.as_ref().is_dir() { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Configuration error: Path \"{}\" {}", p.as_ref().display(), if !p.as_ref().exists() { @@ -1175,13 +1175,13 @@ impl MaildirType { } let root_mailbox = PathBuf::from(settings.root_mailbox()).expand(); if !root_mailbox.exists() { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Configuration error ({}): root_mailbox `{}` is not a valid directory.", settings.name(), settings.root_mailbox.as_str() ))); } else if !root_mailbox.is_dir() { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Configuration error ({}): root_mailbox `{}` is not a directory.", settings.name(), settings.root_mailbox.as_str() @@ -1255,7 +1255,7 @@ impl MaildirType { for d in &["cur", "new", "tmp"] { path.push(d); if !path.is_dir() { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "{} is not a valid maildir mailbox", path.display() ))); @@ -1323,13 +1323,13 @@ impl MaildirType { pub fn validate_config(s: &mut AccountSettings) -> Result<()> { let root_mailbox = PathBuf::from(s.root_mailbox()).expand(); if !root_mailbox.exists() { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Configuration error ({}): root_mailbox `{}` is not a valid directory.", s.name(), s.root_mailbox.as_str() ))); } else if !root_mailbox.is_dir() { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Configuration error ({}): root_mailbox `{}` is not a directory.", s.name(), s.root_mailbox.as_str() diff --git a/melib/src/backends/mbox.rs b/melib/src/backends/mbox.rs index d14e591b..b10102d6 100644 --- a/melib/src/backends/mbox.rs +++ b/melib/src/backends/mbox.rs @@ -118,7 +118,7 @@ //! false, //! )?; //! file.flush()?; -//! # Ok::<(), melib::MeliError>(()) +//! # Ok::<(), melib::Error>(()) //! ``` use crate::backends::*; @@ -126,7 +126,7 @@ use crate::collection::Collection; use crate::conf::AccountSettings; use crate::email::parser::BytesExt; use crate::email::*; -use crate::error::{ErrorKind, MeliError, Result}; +use crate::error::{ErrorKind, Error, Result}; use crate::get_path_hash; use crate::shellexpand::ShellExpandTrait; use nom::bytes::complete::tag; @@ -174,7 +174,7 @@ fn get_rw_lock_blocking(f: &File, path: &Path) -> Result<()> { let ret_val = unsafe { libc::fcntl(fd, F_OFD_SETLKW, ptr as *mut libc::c_void) }; if ret_val == -1 { let err = nix::errno::Errno::from_i32(nix::errno::errno()); - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Could not lock {}: fcntl() returned {}", path.display(), err.desc() @@ -962,7 +962,7 @@ impl MailBackend for MboxType { } fn refresh(&mut self, _mailbox_hash: MailboxHash) -> ResultFuture<()> { - Err(MeliError::new( + Err(Error::new( "Refreshing is currently unimplemented for mbox backend.", )) } @@ -972,12 +972,12 @@ impl MailBackend for MboxType { let (tx, rx) = channel(); let mut watcher = watcher(tx, std::time::Duration::from_secs(10)) .map_err(|e| e.to_string()) - .map_err(MeliError::new)?; + .map_err(Error::new)?; for f in self.mailboxes.lock().unwrap().values() { watcher .watch(&f.fs_path, RecursiveMode::Recursive) .map_err(|e| e.to_string()) - .map_err(MeliError::new)?; + .map_err(Error::new)?; debug!("watching {:?}", f.fs_path.as_path()); } let account_hash = AccountHash::from_bytes(self.account_name.as_bytes()); @@ -1068,7 +1068,7 @@ impl MailBackend for MboxType { BackendEvent::Refresh(RefreshEvent { account_hash, mailbox_hash, - kind: RefreshEventKind::Failure(MeliError::new(format!( + kind: RefreshEventKind::Failure(Error::new(format!( "mbox mailbox {} was removed.", pathbuf.display() ))), @@ -1085,7 +1085,7 @@ impl MailBackend for MboxType { BackendEvent::Refresh(RefreshEvent { account_hash, mailbox_hash, - kind: RefreshEventKind::Failure(MeliError::new(format!( + kind: RefreshEventKind::Failure(Error::new(format!( "mbox mailbox {} was renamed to {}.", src.display(), dest.display() @@ -1151,7 +1151,7 @@ impl MailBackend for MboxType { _destination_mailbox_hash: MailboxHash, _move_: bool, ) -> ResultFuture<()> { - Err(MeliError::new( + Err(Error::new( "Copying messages is currently unimplemented for mbox backend", )) } @@ -1162,7 +1162,7 @@ impl MailBackend for MboxType { _mailbox_hash: MailboxHash, _flags: SmallVec<[(std::result::Result, bool); 8]>, ) -> ResultFuture<()> { - Err(MeliError::new( + Err(Error::new( "Settings flags is currently unimplemented for mbox backend", )) } @@ -1172,7 +1172,7 @@ impl MailBackend for MboxType { _env_hashes: EnvelopeHashBatch, _mailbox_hash: MailboxHash, ) -> ResultFuture<()> { - Err(MeliError::new( + Err(Error::new( "Deleting messages is currently unimplemented for mbox backend", )) } @@ -1183,7 +1183,7 @@ impl MailBackend for MboxType { _mailbox_hash: MailboxHash, _flags: Option, ) -> ResultFuture<()> { - Err(MeliError::new( + Err(Error::new( "Saving messages is currently unimplemented for mbox backend", )) } @@ -1204,7 +1204,7 @@ impl MailBackend for MboxType { &mut self, _mailbox_hash: MailboxHash, ) -> ResultFuture> { - Err(MeliError::new( + Err(Error::new( "Deleting mailboxes is currently unimplemented for mbox backend.", )) } @@ -1214,7 +1214,7 @@ impl MailBackend for MboxType { _mailbox_hash: MailboxHash, _val: bool, ) -> ResultFuture<()> { - Err(MeliError::new( + Err(Error::new( "Mailbox subscriptions are not possible for the mbox backend.", )) } @@ -1224,7 +1224,7 @@ impl MailBackend for MboxType { _mailbox_hash: MailboxHash, _new_path: String, ) -> ResultFuture { - Err(MeliError::new( + Err(Error::new( "Renaming mailboxes is currently unimplemented for mbox backend.", )) } @@ -1234,7 +1234,7 @@ impl MailBackend for MboxType { _mailbox_hash: MailboxHash, _val: crate::backends::MailboxPermissions, ) -> ResultFuture<()> { - Err(MeliError::new( + Err(Error::new( "Setting mailbox permissions is not possible for the mbox backend.", )) } @@ -1245,7 +1245,7 @@ impl MailBackend for MboxType { _mailbox_hash: Option, ) -> ResultFuture> { Err( - MeliError::new("Search is unimplemented for the mbox backend.") + Error::new("Search is unimplemented for the mbox backend.") .set_kind(ErrorKind::NotImplemented), ) } @@ -1255,7 +1255,7 @@ impl MailBackend for MboxType { _new_path: String, ) -> ResultFuture<(MailboxHash, HashMap)> { Err( - MeliError::new("Creating mailboxes is unimplemented for the mbox backend.") + Error::new("Creating mailboxes is unimplemented for the mbox backend.") .set_kind(ErrorKind::NotImplemented), ) } @@ -1264,7 +1264,7 @@ impl MailBackend for MboxType { macro_rules! get_conf_val { ($s:ident[$var:literal]) => { $s.extra.get($var).ok_or_else(|| { - MeliError::new(format!( + Error::new(format!( "Configuration error ({}): mbox backend requires the field `{}` set", $s.name.as_str(), $var @@ -1276,7 +1276,7 @@ macro_rules! get_conf_val { .get($var) .map(|v| { <_>::from_str(v).map_err(|e| { - MeliError::new(format!( + Error::new(format!( "Configuration error ({}): Invalid value for field `{}`: {}\n{}", $s.name.as_str(), $var, @@ -1297,7 +1297,7 @@ impl MboxType { ) -> Result> { let path = Path::new(s.root_mailbox.as_str()).expand(); if !path.exists() { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "\"root_mailbox\" {} for account {} is not a valid path.", s.root_mailbox.as_str(), s.name() @@ -1315,7 +1315,7 @@ impl MboxType { "mboxcl" => Some(MboxFormat::MboxCl), "mboxcl2" => Some(MboxFormat::MboxCl2), _ => { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "{} invalid `prefer_mbox_type` value: `{}`", s.name(), prefer_mbox_type, @@ -1372,7 +1372,7 @@ impl MboxType { let hash = MailboxHash(get_path_hash!(path_str)); let pathbuf: PathBuf = path_str.into(); if !pathbuf.exists() || pathbuf.is_dir() { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "mbox mailbox configuration entry \"{}\" path value {} is not a file.", k, path_str ))); @@ -1411,7 +1411,7 @@ impl MboxType { }, ); } else { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "mbox mailbox configuration entry \"{}\" should have a \"path\" value set pointing to an mbox file.", k ))); @@ -1424,7 +1424,7 @@ impl MboxType { macro_rules! get_conf_val { ($s:ident[$var:literal]) => { $s.extra.remove($var).ok_or_else(|| { - MeliError::new(format!( + Error::new(format!( "Configuration error ({}): mbox backend requires the field `{}` set", $s.name.as_str(), $var @@ -1436,7 +1436,7 @@ impl MboxType { .remove($var) .map(|v| { <_>::from_str(&v).map_err(|e| { - MeliError::new(format!( + Error::new(format!( "Configuration error ({}): Invalid value for field `{}`: {}\n{}", $s.name.as_str(), $var, @@ -1450,7 +1450,7 @@ impl MboxType { } let path = Path::new(s.root_mailbox.as_str()).expand(); if !path.exists() { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "\"root_mailbox\" {} for account {} is not a valid path.", s.root_mailbox.as_str(), s.name() diff --git a/melib/src/backends/mbox/write.rs b/melib/src/backends/mbox/write.rs index 4565fcad..b156055a 100644 --- a/melib/src/backends/mbox/write.rs +++ b/melib/src/backends/mbox/write.rs @@ -34,7 +34,7 @@ impl MboxFormat { crlf: bool, ) -> Result<()> { if tags.iter().any(|t| t.contains(' ')) { - return Err(MeliError::new("mbox tags/keywords can't contain spaces")); + return Err(Error::new("mbox tags/keywords can't contain spaces")); } let line_ending: &'static [u8] = if crlf { &b"\r\n"[..] } else { &b"\n"[..] }; if !is_empty { @@ -91,7 +91,7 @@ impl MboxFormat { } } } - Ok::<(), MeliError>(()) + Ok::<(), Error>(()) }; let write_metadata_fn = |writer: &mut dyn std::io::Write| match metadata_format { MboxMetadata::CClient => { @@ -133,7 +133,7 @@ impl MboxFormat { writer.write_all(v.as_bytes())?; writer.write_all(line_ending)?; } - Ok::<(), MeliError>(()) + Ok::<(), Error>(()) } MboxMetadata::None => Ok(()), }; @@ -152,7 +152,7 @@ impl MboxFormat { }; match self { - MboxFormat::MboxO | MboxFormat::MboxRd => Err(MeliError::new("Unimplemented.")), + MboxFormat::MboxO | MboxFormat::MboxRd => Err(Error::new("Unimplemented.")), MboxFormat::MboxCl => { let len = (body_len + body diff --git a/melib/src/backends/nntp.rs b/melib/src/backends/nntp.rs index c8d17a21..4615bc9b 100644 --- a/melib/src/backends/nntp.rs +++ b/melib/src/backends/nntp.rs @@ -42,7 +42,7 @@ pub use connection::*; use crate::conf::AccountSettings; use crate::connections::timeout; use crate::email::*; -use crate::error::{MeliError, Result, ResultIntoMeliError}; +use crate::error::{Error, Result, ResultIntoError}; use crate::{backends::*, Collection}; use futures::lock::Mutex as FutureMutex; use futures::stream::Stream; @@ -57,7 +57,7 @@ pub type UID = usize; macro_rules! get_conf_val { ($s:ident[$var:literal]) => { $s.extra.get($var).ok_or_else(|| { - MeliError::new(format!( + Error::new(format!( "Configuration error ({}): NNTP connection requires the field `{}` set", $s.name.as_str(), $var @@ -69,7 +69,7 @@ macro_rules! get_conf_val { .get($var) .map(|v| { <_>::from_str(v).map_err(|e| { - MeliError::new(format!( + Error::new(format!( "Configuration error ({}) NNTP: Invalid value for field `{}`: {}\n{}", $s.name.as_str(), $var, @@ -144,7 +144,7 @@ impl UIDStore { collection: Collection::new(), is_online: Arc::new(Mutex::new(( Instant::now(), - Err(MeliError::new("Account is uninitialised.")), + Err(Error::new("Account is uninitialised.")), ))), } } @@ -255,7 +255,7 @@ impl MailBackend for NntpType { Ok(Box::pin(async move { /* To get updates, either issue NEWNEWS if it's supported by the server, and fallback * to OVER otherwise */ - let mbox: NntpMailbox = uid_store.mailboxes.lock().await.get(&mailbox_hash).map(std::clone::Clone::clone).ok_or_else(|| MeliError::new(format!("Mailbox with hash {} not found in NNTP connection, this could possibly be a bug or it was deleted.", mailbox_hash)))?; + let mbox: NntpMailbox = uid_store.mailboxes.lock().await.get(&mailbox_hash).map(std::clone::Clone::clone).ok_or_else(|| Error::new(format!("Mailbox with hash {} not found in NNTP connection, this could possibly be a bug or it was deleted.", mailbox_hash)))?; let latest_article: Option = *mbox.latest_article.lock().unwrap(); let (over_msgid_support, newnews_support): (bool, bool) = { let caps = uid_store.capabilities.lock().unwrap(); @@ -368,7 +368,7 @@ impl MailBackend for NntpType { fn watch(&self) -> ResultFuture<()> { Err( - MeliError::new("Watching is currently uniplemented for nntp backend") + Error::new("Watching is currently uniplemented for nntp backend") .set_kind(ErrorKind::NotImplemented), ) } @@ -379,7 +379,7 @@ impl MailBackend for NntpType { { *v } else { - return Err(MeliError::new( + return Err(Error::new( "Message not found in local cache, it might have been deleted before you requested it." )); }; @@ -397,7 +397,7 @@ impl MailBackend for NntpType { _mailbox_hash: MailboxHash, _flags: Option, ) -> ResultFuture<()> { - Err(MeliError::new("NNTP doesn't support saving.")) + Err(Error::new("NNTP doesn't support saving.")) } fn copy_messages( @@ -407,7 +407,7 @@ impl MailBackend for NntpType { _destination_mailbox_hash: MailboxHash, _move_: bool, ) -> ResultFuture<()> { - Err(MeliError::new("NNTP doesn't support copying/moving.")) + Err(Error::new("NNTP doesn't support copying/moving.")) } fn set_flags( @@ -416,7 +416,7 @@ impl MailBackend for NntpType { _mailbox_hash: MailboxHash, _flags: SmallVec<[(std::result::Result, bool); 8]>, ) -> ResultFuture<()> { - Err(MeliError::new("NNTP doesn't support flags.")) + Err(Error::new("NNTP doesn't support flags.")) } fn delete_messages( @@ -424,7 +424,7 @@ impl MailBackend for NntpType { _env_hashes: EnvelopeHashBatch, _mailbox_hash: MailboxHash, ) -> ResultFuture<()> { - Err(MeliError::new("NNTP doesn't support deletion.")) + Err(Error::new("NNTP doesn't support deletion.")) } fn as_any(&self) -> &dyn Any { @@ -443,7 +443,7 @@ impl MailBackend for NntpType { &mut self, _path: String, ) -> ResultFuture<(MailboxHash, HashMap)> { - Err(MeliError::new( + Err(Error::new( "Creating mailbox is currently unimplemented for nntp backend.", )) } @@ -452,7 +452,7 @@ impl MailBackend for NntpType { &mut self, _mailbox_hash: MailboxHash, ) -> ResultFuture> { - Err(MeliError::new( + Err(Error::new( "Deleting a mailbox is currently unimplemented for nntp backend.", )) } @@ -462,7 +462,7 @@ impl MailBackend for NntpType { _mailbox_hash: MailboxHash, _new_val: bool, ) -> ResultFuture<()> { - Err(MeliError::new( + Err(Error::new( "Setting mailbox description is currently unimplemented for nntp backend.", )) } @@ -472,7 +472,7 @@ impl MailBackend for NntpType { _mailbox_hash: MailboxHash, _new_path: String, ) -> ResultFuture { - Err(MeliError::new( + Err(Error::new( "Renaming mailbox is currently unimplemented for nntp backend.", )) } @@ -482,7 +482,7 @@ impl MailBackend for NntpType { _mailbox_hash: MailboxHash, _val: crate::backends::MailboxPermissions, ) -> ResultFuture<()> { - Err(MeliError::new( + Err(Error::new( "Setting mailbox permissions is currently unimplemented for nntp backend.", )) } @@ -492,7 +492,7 @@ impl MailBackend for NntpType { _query: crate::search::Query, _mailbox_hash: Option, ) -> ResultFuture> { - Err(MeliError::new( + Err(Error::new( "Searching is currently unimplemented for nntp backend.", )) } @@ -510,7 +510,7 @@ impl MailBackend for NntpType { match &conn.stream { Ok(stream) => { if !stream.supports_submission { - return Err(MeliError::new("Server prohibits posting.")); + return Err(Error::new("Server prohibits posting.")); } } Err(err) => return Err(err.clone()), @@ -550,7 +550,7 @@ impl NntpType { .stderr(std::process::Stdio::piped()) .output()?; if !output.status.success() { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "({}) server_password_command `{}` returned {}: {}", s.name, get_conf_val!(s["server_password_command"])?, @@ -608,7 +608,7 @@ impl NntpType { ); } if mailboxes.is_empty() { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "{} has no newsgroups configured.", account_name ))); @@ -674,7 +674,7 @@ impl NntpType { ($s:ident[$var:literal]) => {{ keys.insert($var); $s.extra.remove($var).ok_or_else(|| { - MeliError::new(format!( + Error::new(format!( "Configuration error ({}): NNTP connection requires the field `{}` set", $s.name.as_str(), $var @@ -687,7 +687,7 @@ impl NntpType { .remove($var) .map(|v| { <_>::from_str(&v).map_err(|e| { - MeliError::new(format!( + Error::new(format!( "Configuration error ({}) NNTP: Invalid value for field `{}`: {}\n{}", $s.name.as_str(), $var, @@ -705,7 +705,7 @@ impl NntpType { if !s.extra.contains_key("server_password_command") { get_conf_val!(s["server_password"], String::new())?; } else if s.extra.contains_key("server_password") { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Configuration error ({}): both server_password and server_password_command are set, cannot choose", s.name.as_str(), ))); @@ -715,7 +715,7 @@ impl NntpType { let use_tls = get_conf_val!(s["use_tls"], server_port == 563)?; let use_starttls = get_conf_val!(s["use_starttls"], server_port != 563)?; if !use_tls && use_starttls { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Configuration error ({}): incompatible use_tls and use_starttls values: use_tls = false, use_starttls = true", s.name.as_str(), ))); @@ -724,7 +724,7 @@ impl NntpType { get_conf_val!(s["use_deflate"], false)?; #[cfg(not(feature = "deflate_compression"))] if s.extra.contains_key("use_deflate") { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Configuration error ({}): setting `use_deflate` is set but this version of meli isn't compiled with DEFLATE support.", s.name.as_str(), ))); @@ -737,7 +737,7 @@ impl NntpType { .collect::>(); let diff = extra_keys.difference(&keys).collect::>(); if !diff.is_empty() { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Configuration error ({}) NNTP: the following flags are set but are not recognized: {:?}.", s.name.as_str(), diff ))); @@ -788,7 +788,7 @@ impl FetchState { .name() .to_string(); if s.len() != 5 { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "{} Could not select newsgroup {}: expected GROUP response but got: {}", &uid_store.account_name, path, res ))); diff --git a/melib/src/backends/nntp/connection.rs b/melib/src/backends/nntp/connection.rs index ee76ccc0..21d10fd4 100644 --- a/melib/src/backends/nntp/connection.rs +++ b/melib/src/backends/nntp/connection.rs @@ -119,7 +119,7 @@ impl NntpStream { ret.read_response(&mut res, true, command_to_replycodes("CAPABILITIES")) .await?; if !res.starts_with("101 ") { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Could not connect to {}: expected CAPABILITIES response but got:{}", &server_conf.server_hostname, res ))); @@ -130,7 +130,7 @@ impl NntpStream { .iter() .any(|cap| cap.eq_ignore_ascii_case("VERSION 2")) { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Could not connect to {}: server is not NNTP VERSION 2 compliant", &server_conf.server_hostname ))); @@ -139,7 +139,7 @@ impl NntpStream { .iter() .any(|cap| cap.eq_ignore_ascii_case("STARTTLS")) { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Could not connect to {}: server does not support STARTTLS", &server_conf.server_hostname ))); @@ -149,7 +149,7 @@ impl NntpStream { ret.read_response(&mut res, false, command_to_replycodes("STARTTLS")) .await?; if !res.starts_with("382 ") { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Could not connect to {}: could not begin TLS negotiation, got: {}", &server_conf.server_hostname, res ))); @@ -213,7 +213,7 @@ impl NntpStream { ret.read_response(&mut res, true, command_to_replycodes("CAPABILITIES")) .await?; if !res.starts_with("101 ") { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Could not connect to {}: expected CAPABILITIES response but got:{}", &server_conf.server_hostname, res ))); @@ -224,7 +224,7 @@ impl NntpStream { .iter() .any(|cap| cap.eq_ignore_ascii_case("VERSION 2")) { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Could not connect to {}: server is not NNTP compliant", &server_conf.server_hostname ))); @@ -257,7 +257,7 @@ impl NntpStream { .chain_err_kind(ErrorKind::Authentication)?; } } else { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Could not connect: no supported auth mechanisms in server capabilities: {:?}", capabilities )) @@ -324,20 +324,20 @@ impl NntpStream { ret.push_str(unsafe { std::str::from_utf8_unchecked(&buf[0..b]) }); if ret.len() > 4 { if ret.starts_with("205 ") { - return Err(MeliError::new(format!("Disconnected: {}", ret))); + return Err(Error::new(format!("Disconnected: {}", ret))); } else if ret.starts_with("501 ") || ret.starts_with("500 ") { - return Err(MeliError::new(format!("Syntax error: {}", ret))); + return Err(Error::new(format!("Syntax error: {}", ret))); } else if ret.starts_with("403 ") { - return Err(MeliError::new(format!("Internal error: {}", ret))); + return Err(Error::new(format!("Internal error: {}", ret))); } else if ret.starts_with("502 ") || ret.starts_with("480 ") || ret.starts_with("483 ") || ret.starts_with("401 ") { - return Err(MeliError::new(format!("Connection state error: {}", ret)) + return Err(Error::new(format!("Connection state error: {}", ret)) .set_err_kind(ErrorKind::Authentication)); } else if !expected_reply_code.iter().any(|r| ret.starts_with(r)) { - return Err(MeliError::new(format!("Unexpected reply code: {}", ret))); + return Err(Error::new(format!("Unexpected reply code: {}", ret))); } } if let Some(mut pos) = ret[last_line_idx..].rfind("\r\n") { @@ -357,7 +357,7 @@ impl NntpStream { } } Err(err) => { - return Err(MeliError::from(err)); + return Err(Error::from(err)); } } } @@ -429,7 +429,7 @@ impl NntpConnection { uid_store: Arc, ) -> NntpConnection { NntpConnection { - stream: Err(MeliError::new("Offline".to_string())), + stream: Err(Error::new("Offline".to_string())), server_conf: server_conf.clone(), uid_store, } @@ -439,8 +439,8 @@ impl NntpConnection { Box::pin(async move { if let (instant, ref mut status @ Ok(())) = *self.uid_store.is_online.lock().unwrap() { if Instant::now().duration_since(instant) >= std::time::Duration::new(60 * 30, 0) { - *status = Err(MeliError::new("Connection timed out")); - self.stream = Err(MeliError::new("Connection timed out")); + *status = Err(Error::new("Connection timed out")); + self.stream = Err(Error::new("Connection timed out")); } } if self.stream.is_ok() { diff --git a/melib/src/backends/nntp/mailbox.rs b/melib/src/backends/nntp/mailbox.rs index e85778ef..bb42ab65 100644 --- a/melib/src/backends/nntp/mailbox.rs +++ b/melib/src/backends/nntp/mailbox.rs @@ -87,11 +87,11 @@ impl BackendMailbox for NntpMailbox { } fn set_is_subscribed(&mut self, _new_val: bool) -> Result<()> { - Err(MeliError::new("Cannot set subscription in NNTP.")) + Err(Error::new("Cannot set subscription in NNTP.")) } fn set_special_usage(&mut self, _new_val: SpecialUsageMailbox) -> Result<()> { - Err(MeliError::new("Cannot set special usage in NNTP.")) + Err(Error::new("Cannot set special usage in NNTP.")) } fn count(&self) -> Result<(usize, usize)> { diff --git a/melib/src/backends/nntp/operations.rs b/melib/src/backends/nntp/operations.rs index 61895e0e..6bff3637 100644 --- a/melib/src/backends/nntp/operations.rs +++ b/melib/src/backends/nntp/operations.rs @@ -23,7 +23,7 @@ use super::*; use crate::backends::*; use crate::email::*; -use crate::error::MeliError; +use crate::error::Error; use std::sync::Arc; /// `BackendOp` implementor for Nntp @@ -67,7 +67,7 @@ impl BackendOp for NntpOp { .await?; conn.read_response(&mut res, false, &["211 "]).await?; if !res.starts_with("211 ") { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "{} Could not select newsgroup {}: expected GROUP response but got: {}", &uid_store.account_name, path, res ))); @@ -76,7 +76,7 @@ impl BackendOp for NntpOp { .await?; conn.read_response(&mut res, true, &["220 "]).await?; if !res.starts_with("220 ") { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "{} Could not select article {}: expected ARTICLE response but got: {}", &uid_store.account_name, path, res ))); diff --git a/melib/src/backends/notmuch.rs b/melib/src/backends/notmuch.rs index 69ac6f66..e33c8756 100644 --- a/melib/src/backends/notmuch.rs +++ b/melib/src/backends/notmuch.rs @@ -21,12 +21,11 @@ use crate::conf::AccountSettings; use crate::email::{Envelope, EnvelopeHash, Flag}; -use crate::error::{MeliError, Result}; +use crate::error::{Error, Result}; use crate::shellexpand::ShellExpandTrait; use crate::{backends::*, Collection}; use smallvec::SmallVec; use std::collections::{hash_map::HashMap, BTreeMap}; -use std::error::Error; use std::ffi::{CStr, CString, OsStr}; use std::io::Read; use std::os::unix::ffi::OsStrExt; @@ -186,8 +185,8 @@ impl std::fmt::Display for NotmuchError { } } -impl Error for NotmuchError { - fn source(&self) -> Option<&(dyn Error + 'static)> { +impl std::error::Error for NotmuchError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { None } } @@ -319,11 +318,11 @@ impl NotmuchDb { Ok(l) => l, Err(err) => { if custom_dlpath { - return Err(MeliError::new(format!("Notmuch `library_file_path` setting value `{}` for account {} does not exist or is a directory or not a valid library file.",dlpath, s.name())) + return Err(Error::new(format!("Notmuch `library_file_path` setting value `{}` for account {} does not exist or is a directory or not a valid library file.",dlpath, s.name())) .set_kind(ErrorKind::Configuration) .set_source(Some(Arc::new(err)))); } else { - return Err(MeliError::new("Could not load libnotmuch!") + return Err(Error::new("Could not load libnotmuch!") .set_details(super::NOTMUCH_ERROR_DETAILS) .set_source(Some(Arc::new(err)))); } @@ -332,7 +331,7 @@ impl NotmuchDb { }); let mut path = Path::new(s.root_mailbox.as_str()).expand(); if !path.exists() { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Notmuch `root_mailbox` {} for account {} does not exist.", s.root_mailbox.as_str(), s.name() @@ -340,7 +339,7 @@ impl NotmuchDb { .set_kind(ErrorKind::Configuration)); } if !path.is_dir() { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Notmuch `root_mailbox` {} for account {} is not a directory.", s.root_mailbox.as_str(), s.name() @@ -349,7 +348,7 @@ impl NotmuchDb { } path.push(".notmuch"); if !path.exists() || !path.is_dir() { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Notmuch `root_mailbox` {} for account {} does not contain a `.notmuch` subdirectory.", s.root_mailbox.as_str(), s.name() @@ -376,7 +375,7 @@ impl NotmuchDb { }, ); } else { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "notmuch mailbox configuration entry `{}` for account {} should have a `query` value set.", k, s.name(), @@ -405,7 +404,7 @@ impl NotmuchDb { pub fn validate_config(s: &mut AccountSettings) -> Result<()> { let mut path = Path::new(s.root_mailbox.as_str()).expand(); if !path.exists() { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Notmuch `root_mailbox` {} for account {} does not exist.", s.root_mailbox.as_str(), s.name() @@ -413,7 +412,7 @@ impl NotmuchDb { .set_kind(ErrorKind::Configuration)); } if !path.is_dir() { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Notmuch `root_mailbox` {} for account {} is not a directory.", s.root_mailbox.as_str(), s.name() @@ -422,7 +421,7 @@ impl NotmuchDb { } path.push(".notmuch"); if !path.exists() || !path.is_dir() { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Notmuch `root_mailbox` {} for account {} does not contain a `.notmuch` subdirectory.", s.root_mailbox.as_str(), s.name() @@ -433,7 +432,7 @@ impl NotmuchDb { let account_name = s.name().to_string(); if let Some(lib_path) = s.extra.remove("library_file_path") { if !Path::new(&lib_path).exists() || Path::new(&lib_path).is_dir() { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Notmuch `library_file_path` setting value `{}` for account {} does not exist or is a directory.", &lib_path, s.name() @@ -442,7 +441,7 @@ impl NotmuchDb { } for (k, f) in s.mailboxes.iter_mut() { if f.extra.remove("query").is_none() { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "notmuch mailbox configuration entry `{}` for account {} should have a `query` value set.", k, account_name, @@ -474,7 +473,7 @@ impl NotmuchDb { ) }; if status != 0 { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Could not open notmuch database at path {}. notmuch_database_open returned {}.", path.display(), status @@ -742,7 +741,7 @@ impl MailBackend for NotmuchDb { _destination_mailbox_hash: MailboxHash, _move_: bool, ) -> ResultFuture<()> { - Err(MeliError::new( + Err(Error::new( "Copying messages is currently unimplemented for notmuch backend", )) } @@ -864,7 +863,7 @@ impl MailBackend for NotmuchDb { _env_hashes: EnvelopeHashBatch, _mailbox_hash: MailboxHash, ) -> ResultFuture<()> { - Err(MeliError::new( + Err(Error::new( "Deleting messages is currently unimplemented for notmuch backend", )) } @@ -889,7 +888,7 @@ impl MailBackend for NotmuchDb { s.push(' '); s } else { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Mailbox with hash {} not found!", mailbox_hash )) @@ -925,7 +924,7 @@ impl MailBackend for NotmuchDb { &mut self, _mailbox_hash: MailboxHash, ) -> ResultFuture> { - Err(MeliError::new( + Err(Error::new( "Deleting mailboxes is currently unimplemented for notmuch backend.", )) } @@ -935,7 +934,7 @@ impl MailBackend for NotmuchDb { _mailbox_hash: MailboxHash, _val: bool, ) -> ResultFuture<()> { - Err(MeliError::new( + Err(Error::new( "Mailbox subscriptions are not possible for the notmuch backend.", )) } @@ -945,7 +944,7 @@ impl MailBackend for NotmuchDb { _mailbox_hash: MailboxHash, _new_path: String, ) -> ResultFuture { - Err(MeliError::new( + Err(Error::new( "Renaming mailboxes is currently unimplemented for notmuch backend.", )) } @@ -955,7 +954,7 @@ impl MailBackend for NotmuchDb { _mailbox_hash: MailboxHash, _val: crate::backends::MailboxPermissions, ) -> ResultFuture<()> { - Err(MeliError::new( + Err(Error::new( "Setting mailbox permissions is not possible for the notmuch backend.", )) } @@ -965,7 +964,7 @@ impl MailBackend for NotmuchDb { _new_path: String, ) -> ResultFuture<(MailboxHash, HashMap)> { Err( - MeliError::new("Creating mailboxes is unimplemented for the notmuch backend.") + Error::new("Creating mailboxes is unimplemented for the notmuch backend.") .set_kind(ErrorKind::NotImplemented), ) } @@ -1016,7 +1015,7 @@ impl<'s> Query<'s> { call!(lib, notmuch_query_create)(*database.inner.read().unwrap(), query_cstr.as_ptr()) }; if query.is_null() { - return Err(MeliError::new("Could not create query. Out of memory?")); + return Err(Error::new("Could not create query. Out of memory?")); } Ok(Query { lib, @@ -1043,7 +1042,7 @@ impl<'s> Query<'s> { call!(self.lib, notmuch_query_search_messages)(self.ptr, &mut messages as *mut _) }; if status != 0 { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Search for {} returned {}", self.query_str, status, ))); diff --git a/melib/src/backends/notmuch/message.rs b/melib/src/backends/notmuch/message.rs index 8e503c2f..e03c61af 100644 --- a/melib/src/backends/notmuch/message.rs +++ b/melib/src/backends/notmuch/message.rs @@ -42,7 +42,7 @@ impl<'m> Message<'m> { ) }; if message.is_null() { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Message with message id {:?} not found in notmuch database.", msg_id ))); @@ -205,7 +205,7 @@ impl<'m> Message<'m> { call!(self.lib, notmuch_message_add_tag)(self.message, tag.as_ptr()) ) } { - return Err(MeliError::new("Could not set tag.").set_source(Some(Arc::new(err)))); + return Err(Error::new("Could not set tag.").set_source(Some(Arc::new(err)))); } Ok(()) } @@ -217,7 +217,7 @@ impl<'m> Message<'m> { call!(self.lib, notmuch_message_remove_tag)(self.message, tag.as_ptr()) ) } { - return Err(MeliError::new("Could not set tag.").set_source(Some(Arc::new(err)))); + return Err(Error::new("Could not set tag.").set_source(Some(Arc::new(err)))); } Ok(()) } @@ -233,7 +233,7 @@ impl<'m> Message<'m> { call!(self.lib, notmuch_message_tags_to_maildir_flags)(self.message) ) } { - return Err(MeliError::new("Could not set flags.").set_source(Some(Arc::new(err)))); + return Err(Error::new("Could not set flags.").set_source(Some(Arc::new(err)))); } Ok(()) } diff --git a/melib/src/connections.rs b/melib/src/connections.rs index f1a2f8e3..105f4ea7 100644 --- a/melib/src/connections.rs +++ b/melib/src/connections.rs @@ -270,7 +270,7 @@ pub fn lookup_ipv4(host: &str, port: u16) -> crate::Result } Err( - crate::error::MeliError::new(format!("Could not lookup address {}:{}", host, port)) + crate::error::Error::new(format!("Could not lookup address {}:{}", host, port)) .set_kind(crate::error::ErrorKind::Network( crate::error::NetworkErrorKind::HostLookupFailed, )), @@ -284,7 +284,7 @@ pub async fn timeout(dur: Option, f: impl Future) -> cr if let Some(dur) = dur { match future::select(f, smol::Timer::after(dur)).await { Either::Left((out, _)) => Ok(out), - Either::Right(_) => Err(crate::error::MeliError::new("Timed out.") + Either::Right(_) => Err(crate::error::Error::new("Timed out.") .set_kind(crate::error::ErrorKind::Timeout)), } } else { diff --git a/melib/src/datetime.rs b/melib/src/datetime.rs index 8a9dbdb7..73a3ae91 100644 --- a/melib/src/datetime.rs +++ b/melib/src/datetime.rs @@ -37,7 +37,7 @@ //! let s = timestamp_to_string(timestamp, Some("%Y-%m-%d"), true); //! assert_eq!(s, "2020-01-08"); //! ``` -use crate::error::{Result, ResultIntoMeliError}; +use crate::error::{Result, ResultIntoError}; use std::borrow::Cow; use std::convert::TryInto; use std::ffi::{CStr, CString}; diff --git a/melib/src/email.rs b/melib/src/email.rs index 6da7c5ab..23b2d8d0 100644 --- a/melib/src/email.rs +++ b/melib/src/email.rs @@ -106,7 +106,7 @@ pub use headers::*; pub use mailto::*; use crate::datetime::UnixTimestamp; -use crate::error::{MeliError, Result}; +use crate::error::{Error, Result}; use crate::parser::BytesExt; use crate::thread::ThreadNodeHash; use crate::TagHash; @@ -283,7 +283,7 @@ impl Envelope { } return Ok(e); } - Err(MeliError::new("Couldn't parse mail.")) + Err(Error::new("Couldn't parse mail.")) } pub fn hash(&self) -> EnvelopeHash { @@ -302,7 +302,7 @@ impl Envelope { Err(e) => { debug!("error in parsing mail\n{:?}\n", e); let error_msg = String::from("Mail cannot be shown because of errors."); - return Err(MeliError::new(error_msg)); + return Err(Error::new(error_msg)); } }; for (name, value) in headers { diff --git a/melib/src/email/address.rs b/melib/src/email/address.rs index a9c7d078..4c22c43c 100644 --- a/melib/src/email/address.rs +++ b/melib/src/email/address.rs @@ -262,7 +262,7 @@ impl Address { let email = self.get_email(); let (local_part, domain) = match super::parser::address::addr_spec_raw(email.as_bytes()) - .map_err(Into::::into) + .map_err(Into::::into) .and_then(|(_, (l, d))| { Ok((String::from_utf8(l.into())?, String::from_utf8(d.into())?)) }) { @@ -368,7 +368,7 @@ impl core::fmt::Debug for Address { } impl TryFrom<&str> for Address { - type Error = MeliError; + type Error = Error; fn try_from(val: &str) -> Result
{ Ok(parser::address::address(val.as_bytes())?.1) } diff --git a/melib/src/email/compose.rs b/melib/src/email/compose.rs index 1454ece3..41585515 100644 --- a/melib/src/email/compose.rs +++ b/melib/src/email/compose.rs @@ -77,10 +77,10 @@ impl Default for Draft { } impl FromStr for Draft { - type Err = MeliError; + type Err = Error; fn from_str(s: &str) -> Result { if s.is_empty() { - return Err(MeliError::new("Empty input in Draft::from_str")); + return Err(Error::new("Empty input in Draft::from_str")); } let (headers, _) = parser::mail(s.as_bytes())?; @@ -560,7 +560,7 @@ where { let path: PathBuf = Path::new(path).expand(); if !path.is_file() { - return Err(MeliError::new(format!("{} is not a file", path.display()))); + return Err(Error::new(format!("{} is not a file", path.display()))); } let mut file = std::fs::File::open(&path)?; diff --git a/melib/src/email/headers.rs b/melib/src/email/headers.rs index 1568fe4f..f7486690 100644 --- a/melib/src/email/headers.rs +++ b/melib/src/email/headers.rs @@ -20,7 +20,7 @@ */ /*! Wrapper type `HeaderName` for case-insensitive comparisons */ -use crate::error::MeliError; +use crate::error::Error; use indexmap::IndexMap; use smallvec::SmallVec; use std::borrow::Borrow; @@ -83,13 +83,13 @@ impl> Hash for HeaderNameType { } impl TryFrom<&[u8]> for HeaderName { - type Error = MeliError; + type Error = Error; fn try_from(value: &[u8]) -> Result { if value.is_ascii() { Ok(HeaderNameType(value.into())) } else { - Err(MeliError::new(format!( + Err(Error::new(format!( "Header value is not ascii: {:?}", value ))) @@ -98,13 +98,13 @@ impl TryFrom<&[u8]> for HeaderName { } impl TryFrom<&str> for HeaderName { - type Error = MeliError; + type Error = Error; fn try_from(value: &str) -> Result { if value.is_ascii() { Ok(HeaderNameType(value.as_bytes().into())) } else { - Err(MeliError::new(format!( + Err(Error::new(format!( "Header value is not ascii: {:?}", value ))) diff --git a/melib/src/email/parser.rs b/melib/src/email/parser.rs index 41794f18..72f64885 100644 --- a/melib/src/email/parser.rs +++ b/melib/src/email/parser.rs @@ -20,7 +20,7 @@ */ /*! Parsers for email. See submodules */ -use crate::error::{MeliError, Result, ResultIntoMeliError}; +use crate::error::{Error, Result, ResultIntoError}; use nom::{ branch::alt, bytes::complete::{is_a, is_not, tag, take, take_until, take_while, take_while1}, @@ -132,9 +132,9 @@ impl nom::error::FromExternalError for ParsingError { impl nom::error::ContextError for ParsingError {} -impl<'i> From> for MeliError { - fn from(val: ParsingError<&'i [u8]>) -> MeliError { - MeliError::new("Parsing error").set_summary(format!( +impl<'i> From> for Error { + fn from(val: ParsingError<&'i [u8]>) -> Error { + Error::new("Parsing error").set_summary(format!( r#"In input: "{}...", Error: {}"#, String::from_utf8_lossy(val.input) @@ -146,9 +146,9 @@ Error: {}"#, } } -impl<'i> From> for MeliError { - fn from(val: ParsingError<&'i str>) -> MeliError { - MeliError::new("Parsing error").set_summary(format!( +impl<'i> From> for Error { + fn from(val: ParsingError<&'i str>) -> Error { + Error::new("Parsing error").set_summary(format!( r#"In input: "{}...", Error: {}"#, val.input.chars().take(30).collect::(), @@ -157,29 +157,29 @@ Error: {}"#, } } -impl<'i> From>> for MeliError { - fn from(val: nom::Err>) -> MeliError { +impl<'i> From>> for Error { + fn from(val: nom::Err>) -> Error { match val { - nom::Err::Incomplete(_) => MeliError::new("Parsing Error: Incomplete"), + nom::Err::Incomplete(_) => Error::new("Parsing Error: Incomplete"), nom::Err::Error(err) | nom::Err::Failure(err) => err.into(), } } } -impl<'i> From>> for MeliError { - fn from(val: nom::Err>) -> MeliError { +impl<'i> From>> for Error { + fn from(val: nom::Err>) -> Error { match val { - nom::Err::Incomplete(_) => MeliError::new("Parsing Error: Incomplete"), + nom::Err::Incomplete(_) => Error::new("Parsing Error: Incomplete"), nom::Err::Error(err) | nom::Err::Failure(err) => err.into(), } } } -impl From>> for MeliError { - fn from(val: nom::Err>) -> MeliError { +impl From>> for Error { + fn from(val: nom::Err>) -> Error { match val { - nom::Err::Incomplete(_) => MeliError::new("Parsing Error: Incomplete"), - nom::Err::Error(_) | nom::Err::Failure(_) => MeliError::new("Parsing Error"), + nom::Err::Incomplete(_) => Error::new("Parsing Error: Incomplete"), + nom::Err::Error(_) | nom::Err::Failure(_) => Error::new("Parsing Error"), } } } @@ -304,7 +304,7 @@ pub fn mail(input: &[u8]) -> Result<(Vec<(&[u8], &[u8])>, &[u8])> { .chain_err_summary(|| "Could not parse mail")?; if !rest.is_empty() { - return Err(MeliError::new("Got leftover bytes after parsing mail")); + return Err(Error::new("Got leftover bytes after parsing mail")); } Ok(result) @@ -895,7 +895,7 @@ pub mod generic { ret_s.extend_from_slice(&rest_wsp); let ret_s = String::from_utf8_lossy(&ret_s).into_owned(); if !input.is_empty() { - Err(MeliError::from(format!( + Err(Error::from(format!( "unstructured(): unmatched input: {} while result is {}", to_str!(input), ret_s diff --git a/melib/src/email/pgp.rs b/melib/src/email/pgp.rs index 4f569053..c28ac0b9 100644 --- a/melib/src/email/pgp.rs +++ b/melib/src/email/pgp.rs @@ -24,7 +24,7 @@ use crate::email::{ attachment_types::{ContentType, MultipartType}, attachments::Attachment, }; -use crate::{MeliError, Result}; +use crate::{Error, Result}; /// Convert raw attachment to the form needed for signature verification ([rfc3156](https://tools.ietf.org/html/rfc3156)) /// @@ -95,7 +95,7 @@ pub fn verify_signature(a: &Attachment) -> Result<(Vec, &Attachment)> { boundary: _, } => { if parts.len() != 2 { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Illegal number of parts in multipart/signed. Expected 2 got {}", parts.len() ))); @@ -114,7 +114,7 @@ pub fn verify_signature(a: &Attachment) -> Result<(Vec, &Attachment)> { { v } else { - return Err(MeliError::new( + return Err(Error::new( "multipart/signed attachment without a signed part".to_string(), )); }; @@ -124,13 +124,13 @@ pub fn verify_signature(a: &Attachment) -> Result<(Vec, &Attachment)> { }) { sig } else { - return Err(MeliError::new( + return Err(Error::new( "multipart/signed attachment without a signature part".to_string(), )); }; Ok((signed_part, signature)) } - _ => Err(MeliError::new( + _ => Err(Error::new( "Should not give non-signed attachments to this function", )), } diff --git a/melib/src/error.rs b/melib/src/error.rs index 40a98550..8e576640 100644 --- a/melib/src/error.rs +++ b/melib/src/error.rs @@ -24,7 +24,6 @@ */ use std::borrow::Cow; -use std::error::Error; use std::fmt; use std::io; use std::result; @@ -32,7 +31,7 @@ use std::str; use std::string; use std::sync::Arc; -pub type Result = result::Result; +pub type Result = result::Result; #[derive(Debug, Copy, PartialEq, Eq, Clone)] pub enum NetworkErrorKind { @@ -362,25 +361,25 @@ impl ErrorKind { } #[derive(Debug, Clone)] -pub struct MeliError { +pub struct Error { pub summary: Cow<'static, str>, pub details: Option>, - pub source: Option>, + pub source: Option>, pub kind: ErrorKind, } -pub trait IntoMeliError { - fn set_err_summary(self, msg: M) -> MeliError +pub trait IntoError { + fn set_err_summary(self, msg: M) -> Error where M: Into>; - fn set_err_details(self, msg: M) -> MeliError + fn set_err_details(self, msg: M) -> Error where M: Into>; - fn set_err_kind(self, kind: ErrorKind) -> MeliError; + fn set_err_kind(self, kind: ErrorKind) -> Error; } -pub trait ResultIntoMeliError { +pub trait ResultIntoError { fn chain_err_summary(self, msg_fn: F) -> Result where F: Fn() -> M, @@ -389,33 +388,33 @@ pub trait ResultIntoMeliError { fn chain_err_kind(self, kind: ErrorKind) -> Result; } -impl> IntoMeliError for I { +impl> IntoError for I { #[inline] - fn set_err_summary(self, msg: M) -> MeliError + fn set_err_summary(self, msg: M) -> Error where M: Into>, { - let err: MeliError = self.into(); + let err: Error = self.into(); err.set_summary(msg) } #[inline] - fn set_err_details(self, msg: M) -> MeliError + fn set_err_details(self, msg: M) -> Error where M: Into>, { - let err: MeliError = self.into(); + let err: Error = self.into(); err.set_details(msg) } #[inline] - fn set_err_kind(self, kind: ErrorKind) -> MeliError { - let err: MeliError = self.into(); + fn set_err_kind(self, kind: ErrorKind) -> Error { + let err: Error = self.into(); err.set_kind(kind) } } -impl> ResultIntoMeliError for std::result::Result { +impl> ResultIntoError for std::result::Result { #[inline] fn chain_err_summary(self, msg_fn: F) -> Result where @@ -431,12 +430,12 @@ impl> ResultIntoMeliError for std::result::Result } } -impl MeliError { - pub fn new(msg: M) -> MeliError +impl Error { + pub fn new(msg: M) -> Error where M: Into>, { - MeliError { + Error { summary: msg.into(), details: None, source: None, @@ -444,7 +443,7 @@ impl MeliError { } } - pub fn set_details(mut self, details: M) -> MeliError + pub fn set_details(mut self, details: M) -> Error where M: Into>, { @@ -456,7 +455,7 @@ impl MeliError { self } - pub fn set_summary(mut self, summary: M) -> MeliError + pub fn set_summary(mut self, summary: M) -> Error where M: Into>, { @@ -470,19 +469,19 @@ impl MeliError { pub fn set_source( mut self, - new_val: Option>, - ) -> MeliError { + new_val: Option>, + ) -> Error { self.source = new_val; self } - pub fn set_kind(mut self, new_val: ErrorKind) -> MeliError { + pub fn set_kind(mut self, new_val: ErrorKind) -> Error { self.kind = new_val; self } } -impl fmt::Display for MeliError { +impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { writeln!(f, "{}", self.summary)?; if let Some(details) = self.details.as_ref() { @@ -498,83 +497,81 @@ impl fmt::Display for MeliError { } } -impl Error for MeliError { - fn source(&self) -> Option<&(dyn Error + 'static)> { +impl std::error::Error for Error { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { self.source.as_ref().map(|s| &(*(*s)) as _) } } -impl From for MeliError { +impl From for Error { #[inline] - fn from(kind: io::Error) -> MeliError { - MeliError::new(kind.to_string()) + fn from(kind: io::Error) -> Error { + Error::new(kind.to_string()) .set_details(kind.kind().to_string()) .set_source(Some(Arc::new(kind))) .set_kind(ErrorKind::OSError) } } -impl<'a> From> for MeliError { +impl<'a> From> for Error { #[inline] - fn from(kind: Cow<'_, str>) -> MeliError { - MeliError::new(kind.to_string()) + fn from(kind: Cow<'_, str>) -> Error { + Error::new(kind.to_string()) } } -impl From for MeliError { +impl From for Error { #[inline] - fn from(kind: string::FromUtf8Error) -> MeliError { - MeliError::new(kind.to_string()).set_source(Some(Arc::new(kind))) + fn from(kind: string::FromUtf8Error) -> Error { + Error::new(kind.to_string()).set_source(Some(Arc::new(kind))) } } -impl From for MeliError { +impl From for Error { #[inline] - fn from(kind: str::Utf8Error) -> MeliError { - MeliError::new(kind.to_string()).set_source(Some(Arc::new(kind))) + fn from(kind: str::Utf8Error) -> Error { + Error::new(kind.to_string()).set_source(Some(Arc::new(kind))) } } //use std::option; -//impl From for MeliError { +//impl From for Error { // #[inline] -// fn from(kind: option::NoneError) -> MeliError { -// MeliError::new(format!("{:?}", kind)) +// fn from(kind: option::NoneError) -> Error { +// Error::new(format!("{:?}", kind)) // } //} -impl From> for MeliError { +impl From> for Error { #[inline] - fn from(kind: std::sync::PoisonError) -> MeliError { - MeliError::new(kind.to_string()).set_kind(ErrorKind::Bug) + fn from(kind: std::sync::PoisonError) -> Error { + Error::new(kind.to_string()).set_kind(ErrorKind::Bug) } } #[cfg(feature = "tls")] -impl From> - for MeliError -{ +impl From> for Error { #[inline] - fn from(kind: native_tls::HandshakeError) -> MeliError { - MeliError::new(kind.to_string()) + fn from(kind: native_tls::HandshakeError) -> Error { + Error::new(kind.to_string()) .set_source(Some(Arc::new(kind))) .set_kind(ErrorKind::Network(NetworkErrorKind::InvalidTLSConnection)) } } #[cfg(feature = "tls")] -impl From for MeliError { +impl From for Error { #[inline] - fn from(kind: native_tls::Error) -> MeliError { - MeliError::new(kind.to_string()) + fn from(kind: native_tls::Error) -> Error { + Error::new(kind.to_string()) .set_source(Some(Arc::new(kind))) .set_kind(ErrorKind::Network(NetworkErrorKind::InvalidTLSConnection)) } } -impl From for MeliError { +impl From for Error { #[inline] - fn from(kind: std::num::ParseIntError) -> MeliError { - MeliError::new(kind.to_string()).set_source(Some(Arc::new(kind))) + fn from(kind: std::num::ParseIntError) -> Error { + Error::new(kind.to_string()).set_source(Some(Arc::new(kind))) } } @@ -611,105 +608,105 @@ impl From for ErrorKind { } #[cfg(feature = "http")] -impl From for MeliError { +impl From for Error { #[inline] - fn from(val: isahc::Error) -> MeliError { + fn from(val: isahc::Error) -> Error { let kind: NetworkErrorKind = val.kind().into(); - MeliError::new(val.to_string()) + Error::new(val.to_string()) .set_source(Some(Arc::new(val))) .set_kind(ErrorKind::Network(kind)) } } #[cfg(feature = "jmap_backend")] -impl From for MeliError { +impl From for Error { #[inline] - fn from(kind: serde_json::error::Error) -> MeliError { - MeliError::new(kind.to_string()).set_source(Some(Arc::new(kind))) + fn from(kind: serde_json::error::Error) -> Error { + Error::new(kind.to_string()).set_source(Some(Arc::new(kind))) } } -impl From> for MeliError { +impl From> for Error { #[inline] - fn from(kind: Box) -> MeliError { - MeliError::new(kind.to_string()).set_source(Some(kind.into())) + fn from(kind: Box) -> Error { + Error::new(kind.to_string()).set_source(Some(kind.into())) } } -impl From for MeliError { +impl From for Error { #[inline] - fn from(kind: std::ffi::NulError) -> MeliError { - MeliError::new(kind.to_string()).set_source(Some(Arc::new(kind))) + fn from(kind: std::ffi::NulError) -> Error { + Error::new(kind.to_string()).set_source(Some(Arc::new(kind))) } } -impl From> for MeliError { +impl From> for Error { #[inline] - fn from(kind: Box) -> MeliError { - MeliError::new(kind.to_string()).set_source(Some(Arc::new(kind))) + fn from(kind: Box) -> Error { + Error::new(kind.to_string()).set_source(Some(Arc::new(kind))) } } -impl From for MeliError { +impl From for Error { #[inline] - fn from(kind: nix::Error) -> MeliError { - MeliError::new(kind.to_string()).set_source(Some(Arc::new(kind))) + fn from(kind: nix::Error) -> Error { + Error::new(kind.to_string()).set_source(Some(Arc::new(kind))) } } #[cfg(feature = "sqlite3")] -impl From for MeliError { +impl From for Error { #[inline] - fn from(kind: rusqlite::Error) -> MeliError { - MeliError::new(kind.to_string()).set_source(Some(Arc::new(kind))) + fn from(kind: rusqlite::Error) -> Error { + Error::new(kind.to_string()).set_source(Some(Arc::new(kind))) } } -impl From for MeliError { +impl From for Error { #[inline] - fn from(kind: libloading::Error) -> MeliError { - MeliError::new(kind.to_string()).set_source(Some(Arc::new(kind))) + fn from(kind: libloading::Error) -> Error { + Error::new(kind.to_string()).set_source(Some(Arc::new(kind))) } } -impl From<&str> for MeliError { +impl From<&str> for Error { #[inline] - fn from(kind: &str) -> MeliError { - MeliError::new(kind.to_string()) + fn from(kind: &str) -> Error { + Error::new(kind.to_string()) } } -impl From for MeliError { +impl From for Error { #[inline] - fn from(kind: String) -> MeliError { - MeliError::new(kind) + fn from(kind: String) -> Error { + Error::new(kind) } } -impl From> for MeliError { +impl From> for Error { #[inline] - fn from(kind: nom::Err<(&[u8], nom::error::ErrorKind)>) -> MeliError { - MeliError::new("Parsing error").set_source(Some(Arc::new(MeliError::new(kind.to_string())))) + fn from(kind: nom::Err<(&[u8], nom::error::ErrorKind)>) -> Error { + Error::new("Parsing error").set_source(Some(Arc::new(Error::new(kind.to_string())))) } } -impl From> for MeliError { +impl From> for Error { #[inline] - fn from(kind: nom::Err<(&str, nom::error::ErrorKind)>) -> MeliError { - MeliError::new("Parsing error").set_details(kind.to_string()) + fn from(kind: nom::Err<(&str, nom::error::ErrorKind)>) -> Error { + Error::new("Parsing error").set_details(kind.to_string()) } } -impl<'a> From<&'a mut MeliError> for MeliError { +impl<'a> From<&'a mut Error> for Error { #[inline] - fn from(kind: &'a mut MeliError) -> MeliError { + fn from(kind: &'a mut Error) -> Error { kind.clone() } } -impl<'a> From<&'a MeliError> for MeliError { +impl<'a> From<&'a Error> for Error { #[inline] - fn from(kind: &'a MeliError) -> MeliError { + fn from(kind: &'a Error) -> Error { kind.clone() } } diff --git a/melib/src/gpgme/mod.rs b/melib/src/gpgme/mod.rs index 4a5926b0..e7da22f8 100644 --- a/melib/src/gpgme/mod.rs +++ b/melib/src/gpgme/mod.rs @@ -23,7 +23,7 @@ use crate::email::{ pgp::{DecryptionMetadata, Recipient}, Address, }; -use crate::error::{ErrorKind, IntoMeliError, MeliError, Result, ResultIntoMeliError}; +use crate::error::{ErrorKind, IntoError, Error, Result, ResultIntoError}; use futures::FutureExt; use serde::{ de::{self, Deserialize}, @@ -218,7 +218,7 @@ impl Context { if unsafe { call!(&lib, gpgme_check_version)(GPGME_VERSION.as_bytes().as_ptr() as *mut _) } .is_null() { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Could not use libgpgme: requested version compatible with {} but got {}", GPGME_VERSION, unsafe { @@ -260,7 +260,7 @@ impl Context { let ret = Context { inner: Arc::new(ContextInner { inner: core::ptr::NonNull::new(ptr).ok_or_else(|| { - MeliError::new("Could not use libgpgme").set_kind(ErrorKind::Bug) + Error::new("Could not use libgpgme").set_kind(ErrorKind::Bug) })?, lib, }), @@ -420,7 +420,7 @@ impl Context { lib: self.inner.lib.clone(), kind: DataKind::Memory, inner: core::ptr::NonNull::new(ptr).ok_or_else(|| { - MeliError::new("Could not create libgpgme data").set_kind(ErrorKind::Bug) + Error::new("Could not create libgpgme data").set_kind(ErrorKind::Bug) })?, }) } @@ -428,7 +428,7 @@ impl Context { pub fn new_data_file>(&self, r: P) -> Result { let path: &Path = r.as_ref(); if !path.exists() { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "File `{}` doesn't exist.", path.display() ))); @@ -449,7 +449,7 @@ impl Context { lib: self.inner.lib.clone(), kind: DataKind::Memory, inner: core::ptr::NonNull::new(ptr).ok_or_else(|| { - MeliError::new("Could not create libgpgme data").set_kind(ErrorKind::Bug) + Error::new("Could not create libgpgme data").set_kind(ErrorKind::Bug) })?, }) } @@ -541,7 +541,7 @@ impl Context { let verify_result: gpgme_verify_result_t = unsafe { call!(&ctx.lib, gpgme_op_verify_result)(ctx.inner.as_ptr()) }; if verify_result.is_null() { - return Err(MeliError::new( + return Err(Error::new( "Unspecified libgpgme error: gpgme_op_verify_result returned NULL.", ) .set_err_kind(ErrorKind::External)); @@ -554,7 +554,7 @@ impl Context { .lock() .unwrap() .take() - .unwrap_or_else(|| Err(MeliError::new("Unspecified libgpgme error"))); + .unwrap_or_else(|| Err(Error::new("Unspecified libgpgme error"))); ret }) } @@ -662,7 +662,7 @@ impl Context { .lock() .unwrap() .take() - .unwrap_or_else(|| Err(MeliError::new("Unspecified libgpgme error")))?; + .unwrap_or_else(|| Err(Error::new("Unspecified libgpgme error")))?; let mut keys = vec![]; while let Ok(inner) = key_receiver.try_recv() { let key = Key::new(inner, ctx.lib.clone()); @@ -679,7 +679,7 @@ impl Context { ) -> Result>>> { if sign_keys.is_empty() { return Err( - MeliError::new("gpgme: Call to sign() with zero keys.").set_kind(ErrorKind::Bug) + Error::new("gpgme: Call to sign() with zero keys.").set_kind(ErrorKind::Bug) ); } let mut sig: gpgme_data_t = std::ptr::null_mut(); @@ -715,7 +715,7 @@ impl Context { lib: self.inner.lib.clone(), kind: DataKind::Memory, inner: core::ptr::NonNull::new(sig).ok_or_else(|| { - MeliError::new("internal libgpgme error").set_kind(ErrorKind::Bug) + Error::new("internal libgpgme error").set_kind(ErrorKind::Bug) })?, }; @@ -787,7 +787,7 @@ impl Context { .lock() .unwrap() .take() - .unwrap_or_else(|| Err(MeliError::new("Unspecified libgpgme error")))?; + .unwrap_or_else(|| Err(Error::new("Unspecified libgpgme error")))?; sig.seek(std::io::SeekFrom::Start(0)) .chain_err_summary(|| { "libgpgme error: could not perform seek on signature data object" @@ -819,7 +819,7 @@ impl Context { lib: self.inner.lib.clone(), kind: DataKind::Memory, inner: core::ptr::NonNull::new(plain).ok_or_else(|| { - MeliError::new("internal libgpgme error").set_kind(ErrorKind::Bug) + Error::new("internal libgpgme error").set_kind(ErrorKind::Bug) })?, }; @@ -893,12 +893,12 @@ impl Context { .lock() .unwrap() .take() - .unwrap_or_else(|| Err(MeliError::new("Unspecified libgpgme error")))?; + .unwrap_or_else(|| Err(Error::new("Unspecified libgpgme error")))?; let decrypt_result = unsafe { call!(&ctx.lib, gpgme_op_decrypt_result)(ctx.inner.as_ptr()) }; if decrypt_result.is_null() { - return Err(MeliError::new( + return Err(Error::new( "Unspecified libgpgme error: gpgme_op_decrypt_result returned NULL.", ) .set_err_kind(ErrorKind::External)); @@ -968,7 +968,7 @@ impl Context { ) -> Result>> + Send> { if encrypt_keys.is_empty() { return Err( - MeliError::new("gpgme: Call to encrypt() with zero keys.").set_kind(ErrorKind::Bug) + Error::new("gpgme: Call to encrypt() with zero keys.").set_kind(ErrorKind::Bug) ); } unsafe { @@ -1031,7 +1031,7 @@ impl Context { lib: self.inner.lib.clone(), kind: DataKind::Memory, inner: core::ptr::NonNull::new(cipher).ok_or_else(|| { - MeliError::new("internal libgpgme error").set_kind(ErrorKind::Bug) + Error::new("internal libgpgme error").set_kind(ErrorKind::Bug) })?, }; @@ -1104,12 +1104,12 @@ impl Context { .lock() .unwrap() .take() - .unwrap_or_else(|| Err(MeliError::new("Unspecified libgpgme error")))?; + .unwrap_or_else(|| Err(Error::new("Unspecified libgpgme error")))?; let encrypt_result = unsafe { call!(&ctx.lib, gpgme_op_encrypt_result)(ctx.inner.as_ptr()) }; if encrypt_result.is_null() { - return Err(MeliError::new( + return Err(Error::new( "Unspecified libgpgme error: gpgme_op_encrypt_result returned NULL.", ) .set_err_kind(ErrorKind::External)); @@ -1139,7 +1139,7 @@ fn gpgme_error_try(lib: &libloading::Library, error_code: GpgmeError) -> Result< while buf.ends_with(&b"\0"[..]) { buf.pop(); } - Err(MeliError::from( + Err(Error::from( String::from_utf8(buf) .unwrap_or_else(|err| String::from_utf8_lossy(&err.into_bytes()).to_string()), ) diff --git a/melib/src/search.rs b/melib/src/search.rs index cc84b73b..467d7b02 100644 --- a/melib/src/search.rs +++ b/melib/src/search.rs @@ -92,7 +92,7 @@ impl QueryTrait for crate::Envelope { } impl TryFrom<&str> for Query { - type Error = crate::error::MeliError; + type Error = crate::error::Error; fn try_from(t: &str) -> crate::error::Result { query() .parse_complete(t) diff --git a/melib/src/smtp.rs b/melib/src/smtp.rs index 589bdfaa..43219b23 100644 --- a/melib/src/smtp.rs +++ b/melib/src/smtp.rs @@ -76,7 +76,7 @@ use crate::connections::{lookup_ipv4, Connection}; use crate::email::{parser::BytesExt, Address, Envelope}; -use crate::error::{MeliError, Result, ResultIntoMeliError}; +use crate::error::{Error, Result, ResultIntoError}; use futures::io::{AsyncReadExt, AsyncWriteExt}; use native_tls::TlsConnector; use smallvec::SmallVec; @@ -294,7 +294,7 @@ impl SmtpConnection { danger_accept_invalid_certs, }; } else { - return Err(MeliError::new("Please specify what SMTP security transport to use explicitly instead of `auto`.")); + return Err(Error::new("Please specify what SMTP security transport to use explicitly instead of `auto`.")); } } socket.write_all(b"EHLO meli.delivery\r\n").await?; @@ -369,7 +369,7 @@ impl SmtpConnection { let result: Result = reply.into(); result?; if code != ReplyCode::_220 { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "SMTP Server didn't reply with a 220 greeting: {:?}", Reply::new(&res, code) ))); @@ -395,7 +395,7 @@ impl SmtpConnection { .iter() .any(|l| l.starts_with("AUTH")) { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "SMTP Server doesn't advertise Authentication support. Server response was: {:?}", pre_auth_extensions_reply )).set_kind(crate::error::ErrorKind::Authentication)); @@ -448,7 +448,7 @@ impl SmtpConnection { }) .await?; if !output.status.success() { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "SMTP password evaluation command `{}` returned {}: {}", command, output.status, @@ -511,7 +511,7 @@ impl SmtpConnection { }) .await?; if !output.status.success() { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "SMTP XOAUTH2 token evaluation command `{}` returned {}: {}", &token_command, output.status, @@ -600,7 +600,7 @@ impl SmtpConnection { .chain_err_summary(|| "SMTP submission was aborted")?; let tos = tos.unwrap_or_else(|| envelope.to()); if tos.is_empty() && envelope.cc().is_empty() && envelope.bcc().is_empty() { - return Err(MeliError::new("SMTP submission was aborted because there was no e-mail address found in the To: header field. Consider adding recipients.")); + return Err(Error::new("SMTP submission was aborted because there was no e-mail address found in the To: header field. Consider adding recipients.")); } let mut current_command: SmallVec<[&[u8]; 16]> = SmallVec::new(); //first step in the procedure is the MAIL command. @@ -610,9 +610,9 @@ impl SmtpConnection { current_command.push(envelope_from.trim().as_bytes()); } else { if envelope.from().is_empty() { - return Err(MeliError::new("SMTP submission was aborted because there was no e-mail address found in the From: header field. Consider adding a valid value or setting `envelope_from` in SMTP client settings")); + return Err(Error::new("SMTP submission was aborted because there was no e-mail address found in the From: header field. Consider adding a valid value or setting `envelope_from` in SMTP client settings")); } else if envelope.from().len() != 1 { - return Err(MeliError::new("SMTP submission was aborted because there was more than one e-mail address found in the From: header field. Consider setting `envelope_from` in SMTP client settings")); + return Err(Error::new("SMTP submission was aborted because there was more than one e-mail address found in the From: header field. Consider setting `envelope_from` in SMTP client settings")); } current_command.push(envelope.from()[0].address_spec_raw().trim()); } @@ -885,7 +885,7 @@ impl ReplyCode { } impl TryFrom<&'_ str> for ReplyCode { - type Error = MeliError; + type Error = Error; fn try_from(val: &'_ str) -> Result { if val.len() != 3 { debug!("{}", val); @@ -920,7 +920,7 @@ impl TryFrom<&'_ str> for ReplyCode { "553" => Ok(_553), "554" => Ok(_554), "555" => Ok(_555), - _ => Err(MeliError::new(format!("Unknown SMTP reply code: {}", val))), + _ => Err(Error::new(format!("Unknown SMTP reply code: {}", val))), } } } @@ -935,7 +935,7 @@ pub struct Reply<'s> { impl<'s> Into> for Reply<'s> { fn into(self: Reply<'s>) -> Result { if self.code.is_err() { - Err(MeliError::new(self.lines.join("\n")).set_summary(self.code.as_str())) + Err(Error::new(self.lines.join("\n")).set_summary(self.code.as_str())) } else { Ok(self.code) } @@ -971,13 +971,13 @@ async fn read_lines<'r>( .take(3) .all(|c| c.is_ascii_digit()) { - return Err(MeliError::new(format!("Invalid SMTP reply: {}", ret))); + return Err(Error::new(format!("Invalid SMTP reply: {}", ret))); } if let Some(ref returned_code) = returned_code { if ReplyCode::try_from(ret[last_line_idx..].get(..3).unwrap())? != *returned_code { buffer.extend(ret.drain(last_line_idx..)); if ret.lines().last().unwrap().chars().nth(4).unwrap() != ' ' { - return Err(MeliError::new(format!("Invalid SMTP reply: {}", ret))); + return Err(Error::new(format!("Invalid SMTP reply: {}", ret))); } break 'read_loop; } @@ -1000,12 +1000,12 @@ async fn read_lines<'r>( ret.push_str(unsafe { std::str::from_utf8_unchecked(&buf[0..b]) }); } Err(err) => { - return Err(MeliError::from(err)); + return Err(Error::from(err)); } } } if ret.len() < 3 { - return Err(MeliError::new(format!("Invalid SMTP reply: {}", ret))); + return Err(Error::new(format!("Invalid SMTP reply: {}", ret))); } let code = ReplyCode::try_from(&ret[..3])?; let reply = Reply::new(ret, code); @@ -1016,7 +1016,7 @@ async fn read_lines<'r>( { let result: Result = reply.clone().into(); result?; - return Err(MeliError::new(format!( + return Err(Error::new(format!( "SMTP Server didn't reply with expected greeting code {:?}: {:?}", expected_reply_code.unwrap(), reply diff --git a/melib/src/sqlite3.rs b/melib/src/sqlite3.rs index 17a7b67f..a8177d49 100644 --- a/melib/src/sqlite3.rs +++ b/melib/src/sqlite3.rs @@ -33,17 +33,17 @@ pub struct DatabaseDescription { pub fn db_path(name: &str) -> Result { let data_dir = - xdg::BaseDirectories::with_prefix("meli").map_err(|e| MeliError::new(e.to_string()))?; + xdg::BaseDirectories::with_prefix("meli").map_err(|e| Error::new(e.to_string()))?; data_dir .place_data_file(name) - .map_err(|err| MeliError::new(err.to_string())) + .map_err(|err| Error::new(err.to_string())) } pub fn open_db(db_path: PathBuf) -> Result { if !db_path.exists() { - return Err(MeliError::new("Database doesn't exist")); + return Err(Error::new("Database doesn't exist")); } - Connection::open(&db_path).map_err(|e| MeliError::new(e.to_string())) + Connection::open(&db_path).map_err(|e| Error::new(e.to_string())) } pub fn open_or_create_db( @@ -69,7 +69,7 @@ pub fn open_or_create_db( ); set_mode = true; } - let conn = Connection::open(&db_path).map_err(|e| MeliError::new(e.to_string()))?; + let conn = Connection::open(&db_path).map_err(|e| Error::new(e.to_string()))?; if set_mode { use std::os::unix::fs::PermissionsExt; let file = std::fs::File::open(&db_path)?; @@ -89,7 +89,7 @@ pub fn open_or_create_db( crate::INFO, ); if second_try { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Database version mismatch, is {} but expected {}. Could not recreate database.", version, description.version ))); @@ -104,7 +104,7 @@ pub fn open_or_create_db( } if let Some(s) = description.init_script { conn.execute_batch(s) - .map_err(|e| MeliError::new(e.to_string()))?; + .map_err(|e| Error::new(e.to_string()))?; } return Ok(conn); @@ -137,7 +137,7 @@ impl ToSql for Envelope { fn to_sql(&self) -> rusqlite::Result { let v: Vec = bincode::Options::serialize(bincode::config::DefaultOptions::new(), self) .map_err(|e| { - rusqlite::Error::ToSqlConversionFailure(Box::new(MeliError::new(e.to_string()))) + rusqlite::Error::ToSqlConversionFailure(Box::new(Error::new(e.to_string()))) })?; Ok(ToSqlOutput::from(v)) } diff --git a/src/command.rs b/src/command.rs index 525d69f5..ea376922 100644 --- a/src/command.rs +++ b/src/command.rs @@ -34,7 +34,7 @@ use melib::nom::{ IResult, }; pub use melib::thread::{SortField, SortOrder}; -use melib::MeliError; +use melib::Error; pub mod actions; use actions::MailboxOperation; use std::collections::HashSet; @@ -952,7 +952,7 @@ fn view(input: &[u8]) -> IResult<&[u8], Action> { ))(input) } -pub fn parse_command(input: &[u8]) -> Result { +pub fn parse_command(input: &[u8]) -> Result { alt(( goto, listing_action, diff --git a/src/components/mail/compose.rs b/src/components/mail/compose.rs index 7cd5f615..b2362964 100644 --- a/src/components/mail/compose.rs +++ b/src/components/mail/compose.rs @@ -1253,7 +1253,7 @@ impl Component for Composer { .chan .try_recv() .map_err(|_: futures::channel::oneshot::Canceled| { - MeliError::new("Job was canceled") + Error::new("Job was canceled") }) { Err(err) | Ok(Some(Err(err))) => { self.mode = ViewMode::Edit; @@ -1540,7 +1540,7 @@ impl Component for Composer { match melib::email::parser::address::rfc2822address_list( self.form.values()["From"].as_str().as_bytes(), ) - .map_err(|_err| -> MeliError { "No valid sender address in `From:`".into() }) + .map_err(|_err| -> Error { "No valid sender address in `From:`".into() }) .and_then(|(_, list)| { list.get(0) .cloned() @@ -1580,7 +1580,7 @@ impl Component for Composer { match melib::email::parser::address::rfc2822address_list( self.form.values()["To"].as_str().as_bytes(), ) - .map_err(|_err| -> MeliError { "No valid recipient addresses in `To:`".into() }) + .map_err(|_err| -> Error { "No valid recipient addresses in `To:`".into() }) .and_then(|(_, list)| { list.get(0) .cloned() @@ -2217,7 +2217,7 @@ pub fn save_draft( account_hash: AccountHash, ) { match context.accounts[&account_hash].save_special(bytes, mailbox_type, flags) { - Err(MeliError { + Err(Error { summary, details, kind, diff --git a/src/components/mail/compose/gpg.rs b/src/components/mail/compose/gpg.rs index eaba98f7..f79b3a1a 100644 --- a/src/components/mail/compose/gpg.rs +++ b/src/components/mail/compose/gpg.rs @@ -33,7 +33,7 @@ pub enum KeySelection { }, Error { id: ComponentId, - err: MeliError, + err: Error, }, Loaded { widget: Box>, @@ -140,7 +140,7 @@ impl Component for KeySelection { } } else if !*local && allow_remote_lookup.is_ask() { *self = KeySelection::Error { - err: MeliError::new(format!( + err: Error::new(format!( "No keys found for {}, perform remote lookup?", pattern )), @@ -148,7 +148,7 @@ impl Component for KeySelection { } } else { *self = KeySelection::Error { - err: MeliError::new(format!( + err: Error::new(format!( "No keys found for {}.", pattern )), diff --git a/src/components/mail/view.rs b/src/components/mail/view.rs index 7ccd352d..84e56228 100644 --- a/src/components/mail/view.rs +++ b/src/components/mail/view.rs @@ -114,7 +114,7 @@ pub enum AttachmentDisplay { SignedFailed { inner: Box, display: Vec, - error: MeliError, + error: Error, }, SignedUnverified { inner: Box, @@ -131,7 +131,7 @@ pub enum AttachmentDisplay { }, EncryptedFailed { inner: Box, - error: MeliError, + error: Error, }, EncryptedSuccess { inner: Box, @@ -184,7 +184,7 @@ enum MailViewState { pending_action: Option, }, Error { - err: MeliError, + err: Error, }, Loaded { bytes: Vec, @@ -893,7 +893,7 @@ impl MailView { { acc.push(AttachmentDisplay::EncryptedFailed { inner: Box::new(a.clone()), - error: MeliError::new("Cannot decrypt: meli must be compiled with libgpgme support."), + error: Error::new("Cannot decrypt: meli must be compiled with libgpgme support."), }); } #[cfg(feature = "gpgme")] @@ -916,7 +916,7 @@ impl MailView { } else { acc.push(AttachmentDisplay::EncryptedFailed { inner: Box::new(a.clone()), - error: MeliError::new("Undecrypted."), + error: Error::new("Undecrypted."), }); } } @@ -1528,7 +1528,7 @@ impl Component for MailView { .join(&b"\n"[..])) }) .map(|v| String::from_utf8_lossy(&v).into_owned()) - .unwrap_or_else(|err: MeliError| err.to_string()); + .unwrap_or_else(|err: Error| err.to_string()); if !ret.ends_with("\n\n") { ret.push_str("\n\n"); } diff --git a/src/conf.rs b/src/conf.rs index 10a55f97..08d31085 100644 --- a/src/conf.rs +++ b/src/conf.rs @@ -285,7 +285,7 @@ impl From for AccountConf { pub fn get_config_file() -> Result { let xdg_dirs = xdg::BaseDirectories::with_prefix("meli").map_err(|err| { - MeliError::new(format!( + Error::new(format!( "Could not detect XDG directories for user: {}", err )) @@ -344,7 +344,7 @@ impl FileSettings { if !config_path.exists() { let path_string = config_path.display().to_string(); if path_string.is_empty() { - return Err(MeliError::new("No configuration found.")); + return Err(Error::new("No configuration found.")); } #[cfg(not(test))] let ask = Ask { @@ -356,13 +356,13 @@ impl FileSettings { #[cfg(not(test))] if ask.run() { create_config_file(&config_path)?; - return Err(MeliError::new( + return Err(Error::new( "Edit the sample configuration and relaunch meli.", )); } #[cfg(test)] return Ok(FileSettings::default()); - return Err(MeliError::new("No configuration file found.")); + return Err(Error::new("No configuration file found.")); } FileSettings::validate(config_path, true, false) @@ -372,7 +372,7 @@ impl FileSettings { let s = pp::pp(&path)?; let map: toml::map::Map = toml::from_str(&s).map_err(|err| { - MeliError::new(format!( + Error::new(format!( "{}:\nConfig file is invalid TOML: {}", path.display(), err @@ -401,7 +401,7 @@ This is required so that you don't accidentally start meli and find out later th let mut file = OpenOptions::new().append(true).open(&path)?; file.write_all("[composing]\nsend_mail = 'false'\n".as_bytes()) .map_err(|err| { - MeliError::new(format!( + Error::new(format!( "Could not append to {}: {}", path.display(), err @@ -410,14 +410,14 @@ This is required so that you don't accidentally start meli and find out later th return FileSettings::validate(path, interactive, clear_extras); } } - return Err(MeliError::new(format!( + return Err(Error::new(format!( "{}\n\nEdit the {} and relaunch meli.", if interactive { "" } else { err_msg }, path.display() ))); } let mut s: FileSettings = toml::from_str(&s).map_err(|err| { - MeliError::new(format!( + Error::new(format!( "{}:\nConfig file contains errors: {}", path.display(), err @@ -450,7 +450,7 @@ This is required so that you don't accidentally start meli and find out later th "dark" | "light" => {} t if s.terminal.themes.other_themes.contains_key(t) => {} t => { - return Err(MeliError::new(format!("Theme `{}` was not found.", t))); + return Err(Error::new(format!("Theme `{}` was not found.", t))); } } @@ -493,7 +493,7 @@ This is required so that you don't accidentally start meli and find out later th }; backends.validate_config(&lowercase_format, &mut s)?; if !s.extra.is_empty() { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Unrecognised configuration values: {:?}", s.extra ))); @@ -793,7 +793,7 @@ pub fn create_config_file(p: &Path) -> Result<()> { mod pp { //! Preprocess configuration files by unfolding `include` macros. use melib::{ - error::{MeliError, Result}, + error::{Error, Result}, parsec::*, ShellExpandTrait, }; @@ -860,7 +860,7 @@ mod pp { /// Expands `include` macros in path. fn pp_helper(path: &Path, level: u8) -> Result { if level > 7 { - return Err(MeliError::new(format!("Maximum recursion limit reached while unfolding include directives in {}. Have you included a config file within itself?", path.display()))); + return Err(Error::new(format!("Maximum recursion limit reached while unfolding include directives in {}. Have you included a config file within itself?", path.display()))); } let mut contents = String::new(); let mut file = std::fs::File::open(path)?; @@ -869,7 +869,7 @@ mod pp { for (i, l) in contents.lines().enumerate() { if let (_, Some(sub_path)) = include_directive().parse(l).map_err(|l| { - MeliError::new(format!( + Error::new(format!( "Malformed include directive in line {} of file {}: {}\nConfiguration uses the standard m4 macro include(`filename`).", i, path.display(), @@ -936,7 +936,7 @@ mod dotaddressable { pub trait DotAddressable: Serialize { fn lookup(&self, parent_field: &str, path: &[&str]) -> Result { if !path.is_empty() { - Err(MeliError::new(format!( + Err(Error::new(format!( "{} has no fields, it is of type {}", parent_field, std::any::type_name::() @@ -986,7 +986,7 @@ mod dotaddressable { "log_file" => self.log_file.lookup(field, tail), "maximum_level" => self.maximum_level.lookup(field, tail), - other => Err(MeliError::new(format!( + other => Err(Error::new(format!( "{} has no field named {}", parent_field, other ))), @@ -1008,13 +1008,13 @@ mod dotaddressable { "listing" => self.listing.lookup(field, tail), "notifications" => self.notifications.lookup(field, tail), "shortcuts" => self.shortcuts.lookup(field, tail), - "tags" => Err(MeliError::new("unimplemented")), - "composing" => Err(MeliError::new("unimplemented")), - "pgp" => Err(MeliError::new("unimplemented")), + "tags" => Err(Error::new("unimplemented")), + "composing" => Err(Error::new("unimplemented")), + "pgp" => Err(Error::new("unimplemented")), "terminal" => self.terminal.lookup(field, tail), "log" => self.log.lookup(field, tail), - other => Err(MeliError::new(format!( + other => Err(Error::new(format!( "{} has no field named {}", parent_field, other ))), @@ -1035,7 +1035,7 @@ mod dotaddressable { "conf" => self.conf.lookup(field, tail), "conf_override" => self.conf_override.lookup(field, tail), "mailbox_confs" => self.mailbox_confs.lookup(field, tail), - other => Err(MeliError::new(format!( + other => Err(Error::new(format!( "{} has no field named {}", parent_field, other ))), @@ -1052,17 +1052,17 @@ mod dotaddressable { Some(field) => { let _tail = &path[1..]; match *field { - "pager" => Err(MeliError::new("unimplemented")), //self.pager.lookup(field, tail), - "listing" => Err(MeliError::new("unimplemented")), // self.listing.lookup(field, tail), - "notifications" => Err(MeliError::new("unimplemented")), // self.notifications.lookup(field, tail), - "shortcuts" => Err(MeliError::new("unimplemented")), //self.shortcuts.lookup(field, tail), - "composing" => Err(MeliError::new("unimplemented")), //self.composing.lookup(field, tail), - "identity" => Err(MeliError::new("unimplemented")), //self.identity.lookup(field, tail), - "tags" => Err(MeliError::new("unimplemented")), //self.tags.lookup(field, tail), - "themes" => Err(MeliError::new("unimplemented")), //self.themes.lookup(field, tail), - "pgp" => Err(MeliError::new("unimplemented")), //self.pgp.lookup(field, tail), + "pager" => Err(Error::new("unimplemented")), //self.pager.lookup(field, tail), + "listing" => Err(Error::new("unimplemented")), // self.listing.lookup(field, tail), + "notifications" => Err(Error::new("unimplemented")), // self.notifications.lookup(field, tail), + "shortcuts" => Err(Error::new("unimplemented")), //self.shortcuts.lookup(field, tail), + "composing" => Err(Error::new("unimplemented")), //self.composing.lookup(field, tail), + "identity" => Err(Error::new("unimplemented")), //self.identity.lookup(field, tail), + "tags" => Err(Error::new("unimplemented")), //self.tags.lookup(field, tail), + "themes" => Err(Error::new("unimplemented")), //self.themes.lookup(field, tail), + "pgp" => Err(Error::new("unimplemented")), //self.pgp.lookup(field, tail), - other => Err(MeliError::new(format!( + other => Err(Error::new(format!( "{} has no field named {}", parent_field, other ))), @@ -1081,7 +1081,7 @@ mod dotaddressable { match *field { "conf_override" => self.conf_override.lookup(field, tail), "mailbox_conf" => self.mailbox_conf.lookup(field, tail), - other => Err(MeliError::new(format!( + other => Err(Error::new(format!( "{} has no field named {}", parent_field, other ))), @@ -1111,7 +1111,7 @@ mod dotaddressable { "conf_override" => self.conf_override.lookup(field, tail), "extra" => self.extra.lookup(field, tail), "order" => self.order.lookup(field, tail), - other => Err(MeliError::new(format!( + other => Err(Error::new(format!( "{} has no field named {}", parent_field, other ))), @@ -1138,7 +1138,7 @@ mod dotaddressable { "mailboxes" => self.mailboxes.lookup(field, tail), "manual_refresh" => self.manual_refresh.lookup(field, tail), "extra" => self.extra.lookup(field, tail), - other => Err(MeliError::new(format!( + other => Err(Error::new(format!( "{} has no field named {}", parent_field, other ))), @@ -1161,7 +1161,7 @@ mod dotaddressable { "ignore" => self.ignore.lookup(field, tail), "usage" => self.usage.lookup(field, tail), "extra" => self.extra.lookup(field, tail), - other => Err(MeliError::new(format!( + other => Err(Error::new(format!( "{} has no field named {}", parent_field, other ))), diff --git a/src/conf/accounts.rs b/src/conf/accounts.rs index 067a0c3d..ba0640c9 100644 --- a/src/conf/accounts.rs +++ b/src/conf/accounts.rs @@ -28,7 +28,7 @@ use crate::jobs::{JobExecutor, JobId, JoinHandle}; use indexmap::IndexMap; use melib::backends::*; use melib::email::*; -use melib::error::{ErrorKind, MeliError, Result}; +use melib::error::{ErrorKind, Error, Result}; use melib::text_processing::GlobMatch; use melib::thread::{SortField, SortOrder, Threads}; use melib::AddressBook; @@ -63,7 +63,7 @@ macro_rules! try_recv_timeout { let now = std::time::Instant::now(); let mut res = Ok(None); while now + _3_MS >= std::time::Instant::now() { - res = $oneshot.try_recv().map_err(|_| MeliError::new("canceled")); + res = $oneshot.try_recv().map_err(|_| Error::new("canceled")); if res.as_ref().map(|r| r.is_some()).unwrap_or(false) || res.is_err() { break; } @@ -75,7 +75,7 @@ macro_rules! try_recv_timeout { #[derive(Debug, Clone)] pub enum MailboxStatus { Available, - Failed(MeliError), + Failed(Error), /// first argument is done work, and second is total work Parsing(usize, usize), None, @@ -502,7 +502,7 @@ impl Account { is_online: if !backend.capabilities().is_remote { Ok(()) } else { - Err(MeliError::new("Attempting connection.")) + Err(Error::new("Attempting connection.")) }, mailbox_entries: Default::default(), mailboxes_order: Default::default(), @@ -1220,7 +1220,7 @@ impl Account { ), melib::INFO, ); - Err(MeliError::new(format!( + Err(Error::new(format!( "Message was stored in {} so that you can restore it manually.", file.path.display() )) @@ -1235,7 +1235,7 @@ impl Account { flags: Option, ) -> Result<()> { if self.settings.account.read_only() { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Account {} is read-only.", self.name.as_str() ))); @@ -1275,7 +1275,7 @@ impl Account { match send_mail { SendMail::ShellCommand(ref command) => { if command.is_empty() { - return Err(MeliError::new( + return Err(Error::new( "send_mail shell command configuration value is empty", )); } @@ -1307,7 +1307,7 @@ impl Account { ) }; melib::log(&error_message, melib::LoggingLevel::ERROR); - return Err(MeliError::new(error_message).set_summary("Message not sent.")); + return Err(Error::new(error_message).set_summary("Message not sent.")); } Ok(None) } @@ -1342,7 +1342,7 @@ impl Account { self.insert_job(handle.job_id, JobRequest::SendMessageBackground { handle }); return Ok(None); } - Err(MeliError::new("Server does not support submission.") + Err(Error::new("Server does not support submission.") .set_summary("Message not sent.")) } } @@ -1362,7 +1362,7 @@ impl Account { match send_mail { SendMail::ShellCommand(ref command) => { if command.is_empty() { - return Err(MeliError::new( + return Err(Error::new( "send_mail shell command configuration value is empty", )); } @@ -1395,7 +1395,7 @@ impl Account { }; melib::log(&error_message, melib::LoggingLevel::ERROR); return Err( - MeliError::new(error_message).set_summary("Message not sent.") + Error::new(error_message).set_summary("Message not sent.") ); } Ok(()) @@ -1418,7 +1418,7 @@ impl Account { fut.await?; return Ok(()); } - Err(MeliError::new("Server does not support submission.") + Err(Error::new("Server does not support submission.") .set_summary("Message not sent.")) } } @@ -1444,7 +1444,7 @@ impl Account { ) -> Result<()> { use crate::command::actions::MailboxOperation; if self.settings.account.read_only() { - return Err(MeliError::new("Account is read-only.")); + return Err(Error::new("Account is read-only.")); } match op { MailboxOperation::Create(path) => { @@ -1463,7 +1463,7 @@ impl Account { } MailboxOperation::Delete(path) => { if self.mailbox_entries.len() == 1 { - return Err(MeliError::new("Cannot delete only mailbox.")); + return Err(Error::new("Cannot delete only mailbox.")); } let mailbox_hash = self.mailbox_by_path(&path)?; @@ -1526,8 +1526,8 @@ impl Account { ); Ok(()) } - MailboxOperation::Rename(_, _) => Err(MeliError::new("Not implemented.")), - MailboxOperation::SetPermissions(_) => Err(MeliError::new("Not implemented.")), + MailboxOperation::Rename(_, _) => Err(Error::new("Not implemented.")), + MailboxOperation::SetPermissions(_) => Err(Error::new("Not implemented.")), } } @@ -1614,7 +1614,7 @@ impl Account { { Ok(*mailbox_hash) } else { - Err(MeliError::new("Mailbox with that path not found.")) + Err(Error::new("Mailbox with that path not found.")) } } diff --git a/src/conf/listing.rs b/src/conf/listing.rs index 39951b20..2bf4b3db 100644 --- a/src/conf/listing.rs +++ b/src/conf/listing.rs @@ -21,7 +21,7 @@ use super::{default_vals::*, DotAddressable, IndexStyle}; use melib::search::Query; -use melib::{MeliError, Result}; +use melib::{Error, Result}; /// Settings for mail listings /// @@ -200,7 +200,7 @@ impl DotAddressable for ListingSettings { "selected_flag" => self.selected_flag.lookup(field, tail), "attachment_flag" => self.attachment_flag.lookup(field, tail), "thread_subject_pack" => self.thread_subject_pack.lookup(field, tail), - other => Err(MeliError::new(format!( + other => Err(Error::new(format!( "{} has no field named {}", parent_field, other ))), diff --git a/src/conf/notifications.rs b/src/conf/notifications.rs index d4c0bb3b..ea68a477 100644 --- a/src/conf/notifications.rs +++ b/src/conf/notifications.rs @@ -21,7 +21,7 @@ use super::default_vals::{internal_value_false, none, true_val}; use super::DotAddressable; -use melib::{MeliError, Result, ToggleFlag}; +use melib::{Error, Result, ToggleFlag}; /// Settings for the notifications function. #[derive(Debug, Serialize, Deserialize, Clone)] @@ -79,7 +79,7 @@ impl DotAddressable for NotificationsSettings { "xbiff_file_path" => self.xbiff_file_path.lookup(field, tail), "play_sound" => self.play_sound.lookup(field, tail), "sound_file" => self.sound_file.lookup(field, tail), - other => Err(MeliError::new(format!( + other => Err(Error::new(format!( "{} has no field named {}", parent_field, other ))), diff --git a/src/conf/pager.rs b/src/conf/pager.rs index cce1dd45..38efeace 100644 --- a/src/conf/pager.rs +++ b/src/conf/pager.rs @@ -24,7 +24,7 @@ use super::default_vals::*; use super::deserializers::*; use super::DotAddressable; -use melib::{MeliError, Result, ToggleFlag}; +use melib::{Error, Result, ToggleFlag}; /// Settings for the pager function. #[derive(Debug, Deserialize, Clone, Serialize)] @@ -149,7 +149,7 @@ impl DotAddressable for PagerSettings { } "show_date_in_my_timezone" => self.show_date_in_my_timezone.lookup(field, tail), "url_launcher" => self.html_filter.lookup(field, tail), - other => Err(MeliError::new(format!( + other => Err(Error::new(format!( "{} has no field named {}", parent_field, other ))), diff --git a/src/conf/shortcuts.rs b/src/conf/shortcuts.rs index fd23f871..4a3e8fdb 100644 --- a/src/conf/shortcuts.rs +++ b/src/conf/shortcuts.rs @@ -22,7 +22,7 @@ use super::DotAddressable; use crate::terminal::Key; use indexmap::IndexMap; -use melib::{MeliError, Result}; +use melib::{Error, Result}; #[macro_export] macro_rules! shortcut { @@ -76,7 +76,7 @@ impl DotAddressable for Shortcuts { "envelope_view" | "envelope-view" => self.envelope_view.lookup(field, tail), "thread_view" | "thread-view" => self.thread_view.lookup(field, tail), "pager" => self.pager.lookup(field, tail), - other => Err(MeliError::new(format!( + other => Err(Error::new(format!( "{} has no field named {}", parent_field, other ))), @@ -133,7 +133,7 @@ macro_rules! shortcut_key_values { let tail = &path[1..]; match *field { $(stringify!($fname) => self.$fname.lookup(field, tail),)* - other => Err(MeliError::new(format!( + other => Err(Error::new(format!( "{} has no field named {}", parent_field, other ))), diff --git a/src/conf/tags.rs b/src/conf/tags.rs index 728e17af..58559cdf 100644 --- a/src/conf/tags.rs +++ b/src/conf/tags.rs @@ -23,7 +23,7 @@ use super::DotAddressable; use crate::terminal::Color; -use melib::{MeliError, Result, TagHash}; +use melib::{Error, Result, TagHash}; use serde::{Deserialize, Deserializer}; use std::collections::{HashMap, HashSet}; @@ -85,7 +85,7 @@ impl DotAddressable for TagsSettings { match *field { "colors" => self.colors.lookup(field, tail), "ignore_tags" => self.ignore_tags.lookup(field, tail), - other => Err(MeliError::new(format!( + other => Err(Error::new(format!( "{} has no field named {}", parent_field, other ))), diff --git a/src/conf/terminal.rs b/src/conf/terminal.rs index 21c2b31b..57faafe6 100644 --- a/src/conf/terminal.rs +++ b/src/conf/terminal.rs @@ -24,7 +24,7 @@ use super::deserializers::non_empty_string; use super::DotAddressable; use super::Themes; -use melib::{MeliError, Result, ToggleFlag}; +use melib::{Error, Result, ToggleFlag}; /// Settings for terminal display #[derive(Debug, Deserialize, Clone, Serialize)] @@ -89,7 +89,7 @@ impl DotAddressable for TerminalSettings { let tail = &path[1..]; match *field { "theme" => self.theme.lookup(field, tail), - "themes" => Err(MeliError::new("unimplemented")), + "themes" => Err(Error::new("unimplemented")), "ascii_drawing" => self.ascii_drawing.lookup(field, tail), "use_color" => self.use_color.lookup(field, tail), "use_mouse" => self.use_mouse.lookup(field, tail), @@ -99,7 +99,7 @@ impl DotAddressable for TerminalSettings { "progress_spinner_sequence" => { self.progress_spinner_sequence.lookup(field, tail) } - other => Err(MeliError::new(format!( + other => Err(Error::new(format!( "{} has no field named {}", parent_field, other ))), diff --git a/src/conf/themes.rs b/src/conf/themes.rs index 7c6da737..905b2293 100644 --- a/src/conf/themes.rs +++ b/src/conf/themes.rs @@ -31,7 +31,7 @@ use crate::terminal::{Attr, Color}; use crate::Context; use indexmap::IndexMap; -use melib::{MeliError, Result}; +use melib::{Error, Result}; use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; use smallvec::SmallVec; use std::borrow::Cow; @@ -1212,20 +1212,20 @@ impl Themes { Themes::validate_keys(name, t, &hash_set)?; } if let Err(err) = is_cyclic(&self.light) { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "light theme contains a cycle: {}", err ))); } if let Err(err) = is_cyclic(&self.dark) { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "dark theme contains a cycle: {}", err ))); } for (k, t) in self.other_themes.iter() { if let Err(err) = is_cyclic(t) { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "{} theme contains a cycle: {}", k, err ))); diff --git a/src/mailcap.rs b/src/mailcap.rs index c3caa55f..62a3552e 100644 --- a/src/mailcap.rs +++ b/src/mailcap.rs @@ -26,7 +26,7 @@ use crate::state::Context; use crate::types::{create_temp_file, ForkType, UIEvent}; use melib::text_processing::GlobMatch; -use melib::{email::Attachment, MeliError, Result}; +use melib::{email::Attachment, Error, Result}; use std::collections::HashMap; use std::io::Read; use std::io::Write; @@ -45,13 +45,13 @@ impl MailcapEntry { * $XDG_CONFIG_HOME/meli/mailcap:$XDG_CONFIG_HOME/.mailcap:$HOME/.mailcap:/etc/mailcap:/usr/etc/mailcap:/usr/local/etc/mailcap */ let xdg_dirs = - xdg::BaseDirectories::with_prefix("meli").map_err(|e| MeliError::new(e.to_string()))?; + xdg::BaseDirectories::with_prefix("meli").map_err(|e| Error::new(e.to_string()))?; let mut mailcap_path = xdg_dirs .place_config_file("mailcap") - .map_err(|e| MeliError::new(e.to_string()))?; + .map_err(|e| Error::new(e.to_string()))?; if !mailcap_path.exists() { mailcap_path = xdg::BaseDirectories::new() - .map_err(|e| MeliError::new(e.to_string()))? + .map_err(|e| Error::new(e.to_string()))? .place_config_file("mailcap")?; if !mailcap_path.exists() { if let Ok(home) = std::env::var("HOME") { @@ -65,7 +65,7 @@ impl MailcapEntry { mailcap_path = PathBuf::from("/usr/local/etc/mailcap"); } if !mailcap_path.exists() { - return Err(MeliError::new("No mailcap file found.")); + return Err(Error::new("No mailcap file found.")); } } } @@ -140,7 +140,7 @@ impl MailcapEntry { } match result { - None => Err(MeliError::new("Not found")), + None => Err(Error::new("Not found")), Some(MailcapEntry { command, copiousoutput, diff --git a/src/main.rs b/src/main.rs index 1423802f..8fbceeb8 100644 --- a/src/main.rs +++ b/src/main.rs @@ -78,7 +78,7 @@ fn parse_manpage(src: &str) -> Result { "meli.7" | "guide" => Ok(ManPages::Guide), "meli.conf" | "meli.conf.5" | "conf" | "config" | "configuration" => Ok(ManPages::Conf), "meli-themes" | "meli-themes.5" | "themes" | "theming" | "theme" => Ok(ManPages::Themes), - _ => Err(MeliError::new(format!( + _ => Err(Error::new(format!( "Invalid documentation page: {}", src ))), @@ -188,7 +188,7 @@ fn run_app(opt: Opt) -> Result<()> { crate::conf::get_config_file()? }; if config_path.exists() { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "File `{}` already exists.\nMaybe you meant to specify another path?", config_path.display() ))); @@ -247,7 +247,7 @@ fn run_app(opt: Opt) -> Result<()> { } #[cfg(not(feature = "cli-docs"))] Some(SubCommand::Man(_manopt)) => { - return Err(MeliError::new("error: this version of meli was not build with embedded documentation (cargo feature `cli-docs`). You might have it installed as manpages (eg `man meli`), otherwise check https://meli.delivery")); + return Err(Error::new("error: this version of meli was not build with embedded documentation (cargo feature `cli-docs`). You might have it installed as manpages (eg `man meli`), otherwise check https://meli.delivery")); } Some(SubCommand::CompiledWith) => { #[cfg(feature = "notmuch")] @@ -279,12 +279,12 @@ fn run_app(opt: Opt) -> Result<()> { } Some(SubCommand::View { ref path }) => { if !path.exists() { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "`{}` is not a valid path", path.display() ))); } else if !path.is_file() { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "`{}` is a directory", path.display() ))); diff --git a/src/plugins.rs b/src/plugins.rs index c0bbdae0..6fb0b98d 100644 --- a/src/plugins.rs +++ b/src/plugins.rs @@ -21,7 +21,7 @@ /*! Plugins are executed by meli and communication is done by `messagepack` IPC. */ -use melib::error::{MeliError, Result}; +use melib::error::{Error, Result}; use std::collections::HashMap; use std::io::Write; use std::os::unix::net::{UnixListener, UnixStream}; @@ -276,7 +276,7 @@ impl PluginManager { } } } - Err(MeliError::new("no listeners for this hook")) + Err(Error::new("no listeners for this hook")) } pub fn listener(&self) -> UnixListener { diff --git a/src/plugins/backend.rs b/src/plugins/backend.rs index bdc69574..8efa90fe 100644 --- a/src/plugins/backend.rs +++ b/src/plugins/backend.rs @@ -24,7 +24,7 @@ use melib::async_workers::{Async, AsyncBuilder, AsyncStatus, WorkContext}; use melib::backends::*; use melib::conf::AccountSettings; use melib::email::{Envelope, EnvelopeHash, Flag}; -use melib::error::{MeliError, Result}; +use melib::error::{Error, Result}; use std::collections::BTreeMap; use std::collections::HashMap; use std::sync::{Arc, Mutex, RwLock}; @@ -90,7 +90,7 @@ impl MailBackend for PluginBackend { } is_online.1.clone() } else { - Err(MeliError::new("busy")) + Err(Error::new("busy")) } } @@ -201,13 +201,13 @@ impl MailBackend for PluginBackend { _mailbox_hash: MailboxHash, _flags: Option, ) -> ResultFuture<()> { - Err(MeliError::new("Saving is currently unimplemented for plugins")) + Err(Error::new("Saving is currently unimplemented for plugins")) } fn create_mailbox( &mut self, _name: String, ) -> ResultFuture<(MailboxHash, HashMap)> { - Err(MeliError::new("Creating a mailbox is currently unimplemented for plugins")) + Err(Error::new("Creating a mailbox is currently unimplemented for plugins")) } fn collection(&self) -> melib::Collection { self.collection.clone() @@ -226,7 +226,7 @@ impl PluginBackend { _ev: melib::backends::BackendEventConsumer, ) -> Result> { if plugin.kind != PluginKind::Backend { - return Err(MeliError::new(format!( + return Err(Error::new(format!( "Error: Plugin `{}` is not a mail backend plugin, it's `{:?}`", &plugin.name, &plugin.kind ))); @@ -248,7 +248,7 @@ impl PluginBackend { plugin, channel: Arc::new(Mutex::new(channel)), collection: Default::default(), - is_online: Arc::new(Mutex::new((now, Err(MeliError::new("Unitialized"))))), + is_online: Arc::new(Mutex::new((now, Err(Error::new("Unitialized"))))), })) } @@ -294,12 +294,12 @@ impl BackendOp for PluginOp { .and_then(std::convert::identity)? .into_bytes()) } else { - Err(MeliError::new("busy")) + Err(Error::new("busy")) } })) } fn fetch_flags(&self) -> ResultFuture { - Err(MeliError::new("Unimplemented.")) + Err(Error::new("Unimplemented.")) } } diff --git a/src/plugins/rpc.rs b/src/plugins/rpc.rs index 1195dfc6..bf2e045d 100644 --- a/src/plugins/rpc.rs +++ b/src/plugins/rpc.rs @@ -40,7 +40,7 @@ impl RpcChannel { session: *session, }; let greeting: PluginGreeting = ret.from_read().map_err(|err| { - MeliError::new(format!("Could not get correct plugin greeting: {}", err)) + Error::new(format!("Could not get correct plugin greeting: {}", err)) })?; debug!(&greeting); //if greeting.version != "dev" { @@ -54,11 +54,11 @@ impl RpcChannel { pub fn expect_ack(&mut self) -> Result<()> { debug!("expect_ack()"); let ack: u32 = debug!(rmp_serde::decode::from_read(&mut self.stream)) - .map_err(|_| MeliError::new("Plugin did not return ACK."))?; + .map_err(|_| Error::new("Plugin did not return ACK."))?; if 0x6 == ack { Ok(()) } else { - Err(MeliError::new("Plugin did not return ACK.")) + Err(Error::new("Plugin did not return ACK.")) } } @@ -68,7 +68,7 @@ impl RpcChannel { &mut self.stream, &rmpv::ValueRef::Integer(0x6.into()) )) - .map_err(|err| MeliError::new(err.to_string()))?; + .map_err(|err| Error::new(err.to_string()))?; let _ = self.stream.flush(); Ok(()) } @@ -76,7 +76,7 @@ impl RpcChannel { pub fn write_ref(&mut self, value_ref: &rmpv::ValueRef) -> Result<()> { debug!("write_ref() {:?}", value_ref); debug!(rmpv::encode::write_value_ref(&mut self.stream, value_ref)) - .map_err(|err| MeliError::new(err.to_string()))?; + .map_err(|err| Error::new(err.to_string()))?; let _ = self.stream.flush(); Ok(()) } @@ -84,7 +84,7 @@ impl RpcChannel { pub fn read(&mut self) -> Result { debug!("read()"); let ret: RpcResult = debug!(rmp_serde::decode::from_read(&mut self.stream)) - .map_err(|err| MeliError::new(err.to_string()))?; + .map_err(|err| Error::new(err.to_string()))?; let _ = self.stream.flush(); self.ack()?; debug!("read() ret={:?}", &ret); @@ -97,7 +97,7 @@ impl RpcChannel { { debug!("from_read()"); let ret: Result = debug!(rmp_serde::decode::from_read(&mut self.stream)) - .map_err(|err| MeliError::new(err.to_string())); + .map_err(|err| Error::new(err.to_string())); let _ = self.stream.flush(); self.ack()?; debug!("read() ret={:?}", &ret); @@ -117,7 +117,7 @@ impl RpcResult { fn into(self) -> Result { match self { RpcResult::Ok(v) => Ok(v), - RpcResult::Err(err) => Err(MeliError::new(err)), + RpcResult::Err(err) => Err(Error::new(err)), } } } @@ -136,7 +136,7 @@ impl Result { match self { PluginResult::Ok(v) => Ok(v), - PluginResult::Err(err) => Err(MeliError::new(err)), + PluginResult::Err(err) => Err(Error::new(err)), } } } diff --git a/src/sqlite3.rs b/src/sqlite3.rs index deecf295..4348cd15 100644 --- a/src/sqlite3.rs +++ b/src/sqlite3.rs @@ -21,7 +21,7 @@ /*! Use an sqlite3 database for fast searching. */ -use crate::melib::ResultIntoMeliError; +use crate::melib::ResultIntoError; use melib::search::{ escape_double_quote, Query::{self, *}, @@ -32,7 +32,7 @@ use melib::{ log, sqlite3::{self as melib_sqlite3, rusqlite::params, DatabaseDescription}, thread::{SortField, SortOrder}, - MeliError, Result, ERROR, + Error, Result, ERROR, }; use smallvec::SmallVec; @@ -142,7 +142,7 @@ pub async fn insert( ) -> Result<()> { let db_path = db_path()?; if !db_path.exists() { - return Err(MeliError::new( + return Err(Error::new( "Database hasn't been initialised. Run `reindex` command", )); } @@ -195,7 +195,7 @@ pub async fn insert( ), ERROR, ); - return Err(MeliError::new(err.to_string())); + return Err(Error::new(err.to_string())); } let account_id: i32 = { let mut stmt = conn @@ -214,7 +214,7 @@ pub async fn insert( VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15)", params![account_id, envelope.hash().to_be_bytes().to_vec(), envelope.date_as_str(), envelope.field_from_to_string(), envelope.field_to_to_string(), envelope.field_cc_to_string(), envelope.field_bcc_to_string(), envelope.subject().into_owned().trim_end_matches('\u{0}'), envelope.message_id_display().to_string(), envelope.in_reply_to_display().map(|f| f.to_string()).unwrap_or_default(), envelope.field_references_to_string(), i64::from(envelope.flags().bits()), if envelope.has_attachments() { 1 } else { 0 }, body, envelope.date().to_be_bytes().to_vec()], ) - .map_err(|e| MeliError::new(e.to_string())) { + .map_err(|e| Error::new(e.to_string())) { debug!( "Failed to insert envelope {}: {}", envelope.message_id_display(), @@ -235,7 +235,7 @@ pub async fn insert( pub fn remove(env_hash: EnvelopeHash) -> Result<()> { let db_path = db_path()?; if !db_path.exists() { - return Err(MeliError::new( + return Err(Error::new( "Database hasn't been initialised. Run `reindex` command", )); } @@ -246,7 +246,7 @@ pub fn remove(env_hash: EnvelopeHash) -> Result<()> { "DELETE FROM envelopes WHERE hash = ?", params![env_hash.to_be_bytes().to_vec(),], ) - .map_err(|e| MeliError::new(e.to_string())) + .map_err(|e| Error::new(e.to_string())) { debug!("Failed to remove envelope {}: {}", env_hash, err); log( @@ -332,7 +332,7 @@ pub fn search( ) -> ResultFuture> { let db_path = db_path()?; if !db_path.exists() { - return Err(MeliError::new( + return Err(Error::new( "Database hasn't been initialised. Run `reindex` command", )); } @@ -359,12 +359,12 @@ pub fn search( )) .as_str(), ) - .map_err(|e| MeliError::new(e.to_string()))?; + .map_err(|e| Error::new(e.to_string()))?; let results = stmt .query_map([], |row| row.get::<_, EnvelopeHash>(0)) - .map_err(MeliError::from)? - .map(|item| item.map_err(MeliError::from)) + .map_err(Error::from)? + .map(|item| item.map_err(Error::from)) .collect::>>(); Ok(Box::pin(async { results })) } diff --git a/src/state.rs b/src/state.rs index 856c7906..b9e7aefb 100644 --- a/src/state.rs +++ b/src/state.rs @@ -421,7 +421,7 @@ impl State { s.context.accounts[i].watch(); } if s.context.is_online_idx(i).is_ok() && s.context.accounts[i].is_empty() { - //return Err(MeliError::new(format!( + //return Err(Error::new(format!( // "Account {} has no mailboxes configured.", // s.context.accounts[i].name() //))); diff --git a/src/terminal/embed/grid.rs b/src/terminal/embed/grid.rs index baa63fdb..1e5cfc87 100644 --- a/src/terminal/embed/grid.rs +++ b/src/terminal/embed/grid.rs @@ -21,7 +21,7 @@ use super::*; use crate::terminal::{cells::*, Color}; -use melib::error::{MeliError, Result}; +use melib::error::{Error, Result}; use melib::text_processing::wcwidth; use nix::sys::wait::WaitStatus; use nix::sys::wait::{waitpid, WaitPidFlag}; @@ -164,7 +164,7 @@ impl EmbedTerminal { pub fn is_active(&self) -> Result { debug!(waitpid(self.child_pid, Some(WaitPidFlag::WNOHANG),)) - .map_err(|e| MeliError::new(e.to_string())) + .map_err(|e| Error::new(e.to_string())) } pub fn process_byte(&mut self, byte: u8) {