Fix clippy lints

memfd
Manos Pitsidianakis 2020-07-05 15:28:55 +03:00
parent bbedeed3e3
commit a7e177586a
Signed by: Manos Pitsidianakis
GPG Key ID: 73627C2F690DF710
60 changed files with 359 additions and 437 deletions

1
Cargo.lock generated
View File

@ -943,7 +943,6 @@ dependencies = [
"nix",
"nom",
"notify",
"pin-utils",
"reqwest",
"rusqlite",
"serde",

View File

@ -84,7 +84,7 @@ fn main() -> Result<(), std::io::Error> {
.unwrap();
file.write_all(b"use crate::types::LineBreakClass;\n\n")
.unwrap();
file.write_all(b"const line_break_rules: &'static [(u32, u32, LineBreakClass)] = &[\n")
file.write_all(b"const LINE_BREAK_RULES: &[(u32, u32, LineBreakClass)] = &[\n")
.unwrap();
for l in &line_break_table {
file.write_all(format!(" (0x{:X}, 0x{:X}, {:?}),\n", l.0, l.1, l.2).as_bytes())

View File

@ -45,8 +45,8 @@ impl VCardVersion for VCardVersion3 {}
pub struct CardDeserializer;
static HEADER: &'static str = "BEGIN:VCARD\r\n"; //VERSION:4.0\r\n";
static FOOTER: &'static str = "END:VCARD\r\n";
static HEADER: &str = "BEGIN:VCARD\r\n"; //VERSION:4.0\r\n";
static FOOTER: &str = "END:VCARD\r\n";
#[derive(Debug)]
pub struct VCard<T: VCardVersion>(

View File

@ -206,21 +206,21 @@ where
recv(rx) -> r => {
match r {
Ok(p @ AsyncStatus::Payload(_)) => {
return Ok(p);
Ok(p)
},
Ok(f @ AsyncStatus::Finished) => {
self.active = false;
return Ok(f);
Ok(f)
},
Ok(a) => {
return Ok(a);
Ok(a)
}
Err(_) => {
return Err(());
Err(())
},
}
},
};
}
}
/// Polls worker thread and returns result.
pub fn poll(&mut self) -> Result<AsyncStatus<T>, ()> {
@ -231,25 +231,25 @@ where
let rx = &self.rx;
select! {
default => {
return Ok(AsyncStatus::NoUpdate);
Ok(AsyncStatus::NoUpdate)
},
recv(rx) -> r => {
match r {
Ok(p @ AsyncStatus::Payload(_)) => {
return Ok(p);
Ok(p)
},
Ok(f @ AsyncStatus::Finished) => {
self.active = false;
return Ok(f);
Ok(f)
},
Ok(a) => {
return Ok(a);
Ok(a)
}
Err(_) => {
return Err(());
Err(())
},
}
},
};
}
}
}

View File

@ -72,7 +72,6 @@ pub use futures::stream::Stream;
use std::future::Future;
pub use std::pin::Pin;
use std;
use std::collections::HashMap;
#[macro_export]
@ -111,10 +110,10 @@ impl Default for Backends {
}
#[cfg(feature = "notmuch_backend")]
pub const NOTMUCH_ERROR_MSG: &'static str =
pub const NOTMUCH_ERROR_MSG: &str =
"libnotmuch5 was not found in your system. Make sure it is installed and in the library paths.\n";
#[cfg(not(feature = "notmuch_backend"))]
pub const NOTMUCH_ERROR_MSG: &'static str = "this version of meli is not compiled with notmuch support. Use an appropriate version and make sure libnotmuch5 is installed and in the library paths.\n";
pub const NOTMUCH_ERROR_MSG: &str = "this version of meli is not compiled with notmuch support. Use an appropriate version and make sure libnotmuch5 is installed and in the library paths.\n";
impl Backends {
pub fn new() -> Self {
@ -306,7 +305,7 @@ pub trait MailBackend: ::std::fmt::Debug + Send + Sync {
fn get(&mut self, mailbox: &Mailbox) -> Async<Result<Vec<Envelope>>>;
fn get_async(
&mut self,
mailbox: &Mailbox,
_mailbox: &Mailbox,
) -> Result<Pin<Box<dyn Stream<Item = Result<Vec<Envelope>>> + Send + 'static>>> {
Err(MeliError::new("Unimplemented."))
}
@ -329,7 +328,7 @@ pub trait MailBackend: ::std::fmt::Debug + Send + Sync {
sender: RefreshEventConsumer,
work_context: WorkContext,
) -> Result<std::thread::ThreadId>;
fn watch_async(&self, sender: RefreshEventConsumer) -> ResultFuture<()> {
fn watch_async(&self, _sender: RefreshEventConsumer) -> ResultFuture<()> {
Err(MeliError::new("Unimplemented."))
}
fn mailboxes(&self) -> Result<HashMap<MailboxHash, Mailbox>>;
@ -524,9 +523,7 @@ impl SpecialUsageMailbox {
Some(SpecialUsageMailbox::Archive)
} else if name.eq_ignore_ascii_case("drafts") {
Some(SpecialUsageMailbox::Drafts)
} else if name.eq_ignore_ascii_case("junk") {
Some(SpecialUsageMailbox::Junk)
} else if name.eq_ignore_ascii_case("spam") {
} else if name.eq_ignore_ascii_case("junk") || name.eq_ignore_ascii_case("spam") {
Some(SpecialUsageMailbox::Junk)
} else if name.eq_ignore_ascii_case("sent") {
Some(SpecialUsageMailbox::Sent)

View File

@ -52,7 +52,7 @@ use std::sync::{Arc, Mutex, RwLock};
use std::time::Instant;
pub type UID = usize;
pub static SUPPORTED_CAPABILITIES: &'static [&'static str] =
pub static SUPPORTED_CAPABILITIES: &[&str] =
&["IDLE", "LOGIN", "LOGINDISABLED", "ENABLE", "IMAP4REV1"];
#[derive(Debug, Default)]
@ -412,7 +412,7 @@ impl MailBackend for ImapType {
debug!(
"fetch response is {} bytes and {} lines",
response.len(),
response.lines().collect::<Vec<&str>>().len()
response.lines().count()
);
let (_, v, _) = protocol_parser::uid_fetch_responses(&response)?;
debug!("responses len is {}", v.len());
@ -552,7 +552,7 @@ impl MailBackend for ImapType {
.send(RefreshEvent {
account_hash: uid_store.account_hash,
mailbox_hash,
kind: RefreshEventKind::Failure(err.clone()),
kind: RefreshEventKind::Failure(err),
});
return;
@ -655,9 +655,6 @@ impl MailBackend for ImapType {
};
Ok(Box::new(ImapOp::new(
uid,
self.uid_store.mailboxes.read().unwrap()[&mailbox_hash]
.imap_path()
.to_string(),
mailbox_hash,
self.connection.clone(),
self.uid_store.clone(),
@ -673,10 +670,9 @@ impl MailBackend for ImapType {
let path = {
let mailboxes = self.uid_store.mailboxes.read().unwrap();
let mailbox = mailboxes.get(&mailbox_hash).ok_or(MeliError::new(format!(
"Mailbox with hash {} not found.",
mailbox_hash
)))?;
let mailbox = mailboxes.get(&mailbox_hash).ok_or_else(|| {
MeliError::new(format!("Mailbox with hash {} not found.", mailbox_hash))
})?;
if !mailbox.permissions.lock().unwrap().create_messages {
return Err(MeliError::new(format!(
"You are not allowed to create messages in mailbox {}",
@ -688,7 +684,7 @@ impl MailBackend for ImapType {
};
let mut response = String::with_capacity(8 * 1024);
let mut conn = try_lock(&self.connection, Some(std::time::Duration::new(5, 0)))?;
let flags = flags.unwrap_or(Flag::empty());
let flags = flags.unwrap_or_else(Flag::empty);
conn.send_command(
format!(
"APPEND \"{}\" ({}) {{{}}}",

View File

@ -35,8 +35,8 @@ pub use sqlite3_m::*;
mod sqlite3_m {
use super::*;
use crate::sqlite3;
const DB_NAME: &'static str = "header_cache.db";
const INIT_SCRIPT: &'static str = "PRAGMA foreign_keys = true;
const DB_NAME: &str = "header_cache.db";
const INIT_SCRIPT: &str = "PRAGMA foreign_keys = true;
PRAGMA encoding = 'UTF-8';
CREATE TABLE IF NOT EXISTS envelopes (

View File

@ -274,7 +274,9 @@ impl ImapStream {
}
}
if capabilities.is_none() {
if let Some(capabilities) = capabilities {
Ok((capabilities, ret))
} else {
/* sending CAPABILITY after LOGIN automatically is an RFC recommendation, so check
* for lazy servers */
drop(capabilities);
@ -283,9 +285,6 @@ impl ImapStream {
let capabilities = protocol_parser::capabilities(res.as_bytes())?.1;
let capabilities = HashSet::from_iter(capabilities.into_iter().map(|s| s.to_vec()));
Ok((capabilities, ret))
} else {
let capabilities = capabilities.unwrap();
Ok((capabilities, ret))
}
}
@ -523,7 +522,7 @@ impl ImapConnection {
}
}
if let Ok(ref mut stream) = self.stream {
if let Ok(_) = action(stream) {
if action(stream).is_ok() {
self.uid_store.is_online.lock().unwrap().0 = Instant::now();
return Ok(());
}

View File

@ -37,7 +37,6 @@ pub struct ImapOp {
impl ImapOp {
pub fn new(
uid: usize,
mailbox_path: String,
mailbox_hash: MailboxHash,
connection: Arc<Mutex<ImapConnection>>,
uid_store: Arc<UIDStore>,
@ -66,7 +65,7 @@ impl BackendOp for ImapOp {
debug!(
"fetch response is {} bytes and {} lines",
response.len(),
response.lines().collect::<Vec<&str>>().len()
response.lines().count()
);
let UidFetchResponse {
uid, flags, body, ..
@ -105,7 +104,7 @@ impl BackendOp for ImapOp {
debug!(
"fetch response is {} bytes and {} lines",
response.len(),
response.lines().collect::<Vec<&str>>().len()
response.lines().count()
);
let v = protocol_parser::uid_fetch_flags_response(response.as_bytes())
.map(|(_, v)| v)
@ -131,8 +130,7 @@ impl BackendOp for ImapOp {
let val = {
let mut bytes_cache = uid_store.byte_cache.lock()?;
let cache = bytes_cache.entry(uid).or_default();
let val = cache.flags;
val
cache.flags
};
Ok(val.unwrap())
}
@ -174,11 +172,13 @@ impl BackendOp for ImapOp {
Ok(v) => {
if v.len() == 1 {
debug!("responses len is {}", v.len());
let (uid, (flags, _)) = v[0];
let (uid, (_flags, _)) = v[0];
assert_eq!(uid, uid);
}
}
Err(e) => Err(e)?,
Err(e) => {
return Err(e);
}
}
let mut bytes_cache = uid_store.byte_cache.lock()?;
let cache = bytes_cache.entry(uid).or_default();

View File

@ -190,7 +190,7 @@ ReadWrite => write!(fmt, "This mailbox is selected with read-write permissions."
impl ResponseCode {
fn from(val: &str) -> ResponseCode {
use ResponseCode::*;
if !val.starts_with("[") {
if !val.starts_with('[') {
let msg = val.trim();
return Alert(msg.to_string());
}
@ -235,7 +235,8 @@ pub enum ImapResponse {
impl<T: AsRef<str>> From<T> for ImapResponse {
fn from(val: T) -> ImapResponse {
let val: &str = val.as_ref().split_rn().last().unwrap_or(val.as_ref());
let val_ref = val.as_ref();
let val: &str = val_ref.split_rn().last().unwrap_or(val_ref);
debug!(&val);
let mut val = val[val.as_bytes().find(b" ").unwrap() + 1..].trim();
// M12 NO [CANNOT] Invalid mailbox name: Name must not have \'/\' characters (0.000 + 0.098 + 0.097 secs).\r\n
@ -616,7 +617,7 @@ pub fn uid_fetch_responses(mut input: &str) -> ImapParseResult<Vec<UidFetchRespo
if let Some(el_alert) = el_alert {
match &mut alert {
Some(Alert(ref mut alert)) => {
alert.extend(el_alert.0.chars());
alert.push_str(&el_alert.0);
}
a @ None => *a = Some(el_alert),
}
@ -994,13 +995,13 @@ pub fn flags(input: &str) -> IResult<&str, (Flag, Vec<String>)> {
let mut keywords = Vec::new();
let mut input = input;
while !input.starts_with(")") && !input.is_empty() {
if input.starts_with("\\") {
while !input.starts_with(')') && !input.is_empty() {
if input.starts_with('\\') {
input = &input[1..];
}
let mut match_end = 0;
while match_end < input.len() {
if input[match_end..].starts_with(" ") || input[match_end..].starts_with(")") {
if input[match_end..].starts_with(' ') || input[match_end..].starts_with(')') {
break;
}
match_end += 1;
@ -1337,13 +1338,13 @@ pub fn quoted(input: &[u8]) -> IResult<&[u8], Vec<u8>> {
i += 1;
}
return Err(nom::Err::Error(
Err(nom::Err::Error(
(input, "quoted(): not a quoted phrase").into(),
));
))
}
pub fn quoted_or_nil(input: &[u8]) -> IResult<&[u8], Option<Vec<u8>>> {
alt((map(tag("NIL"), |_| None), map(quoted, |v| Some(v))))(input.ltrim())
alt((map(tag("NIL"), |_| None), map(quoted, Some)))(input.ltrim())
/*
alt_complete!(map!(ws!(tag!("NIL")), |_| None) | map!(quoted, |v| Some(v))));
*/
@ -1508,9 +1509,9 @@ fn string_token(input: &[u8]) -> IResult<&[u8], &[u8]> {
i += 1;
}
return Err(nom::Err::Error(
Err(nom::Err::Error(
(input, "string_token(): not a quoted phrase").into(),
));
))
}
// ASTRING-CHAR = ATOM-CHAR / resp-specials

View File

@ -56,7 +56,7 @@ use std::sync::{Arc, Mutex, RwLock};
use std::time::Instant;
pub type UID = usize;
pub static SUPPORTED_CAPABILITIES: &'static [&'static str] =
pub static SUPPORTED_CAPABILITIES: &[&str] =
&["IDLE", "LOGIN", "LOGINDISABLED", "ENABLE", "IMAP4REV1"];
#[derive(Debug, Default)]
@ -387,10 +387,9 @@ impl MailBackend for ImapType {
let path = {
let mailboxes = uid_store.mailboxes.lock().await;
let mailbox = mailboxes.get(&mailbox_hash).ok_or(MeliError::new(format!(
"Mailbox with hash {} not found.",
mailbox_hash
)))?;
let mailbox = mailboxes.get(&mailbox_hash).ok_or_else(|| {
MeliError::new(format!("Mailbox with hash {} not found.", mailbox_hash))
})?;
if !mailbox.permissions.lock().unwrap().create_messages {
return Err(MeliError::new(format!(
"You are not allowed to create messages in mailbox {}",
@ -402,7 +401,7 @@ impl MailBackend for ImapType {
};
let mut response = String::with_capacity(8 * 1024);
let mut conn = connection.lock().await;
let flags = flags.unwrap_or(Flag::empty());
let flags = flags.unwrap_or_else(Flag::empty);
conn.send_command(
format!(
"APPEND \"{}\" ({}) {{{}}}",
@ -658,10 +657,10 @@ impl MailBackend for ImapType {
fn set_mailbox_permissions(
&mut self,
mailbox_hash: MailboxHash,
val: crate::backends::MailboxPermissions,
_val: crate::backends::MailboxPermissions,
) -> ResultFuture<()> {
let uid_store = self.uid_store.clone();
let connection = self.connection.clone();
//let connection = self.connection.clone();
Ok(Box::pin(async move {
let mailboxes = uid_store.mailboxes.lock().await;
let permissions = mailboxes[&mailbox_hash].permissions();
@ -746,7 +745,7 @@ impl MailBackend for ImapType {
}
keyword => {
s.push_str(" KEYWORD ");
s.extend(keyword.chars());
s.push_str(keyword);
s.push_str(" ");
}
}
@ -798,7 +797,7 @@ impl MailBackend for ImapType {
.map(usize::from_str)
.filter_map(std::result::Result::ok)
.filter_map(|uid| uid_index.get(&(mailbox_hash, uid)))
.map(|env_hash_ref| *env_hash_ref),
.copied(),
));
}
}
@ -1210,7 +1209,7 @@ async fn get_hlpr(
debug!(
"fetch response is {} bytes and {} lines",
response.len(),
response.lines().collect::<Vec<&str>>().len()
response.lines().count()
);
let (_, v, _) = protocol_parser::uid_fetch_responses(&response)?;
debug!("responses len is {}", v.len());

View File

@ -35,8 +35,8 @@ pub use sqlite3_m::*;
mod sqlite3_m {
use super::*;
use crate::sqlite3;
const DB_NAME: &'static str = "header_cache.db";
const INIT_SCRIPT: &'static str = "PRAGMA foreign_keys = true;
const DB_NAME: &str = "header_cache.db";
const INIT_SCRIPT: &str = "PRAGMA foreign_keys = true;
PRAGMA encoding = 'UTF-8';
CREATE TABLE IF NOT EXISTS envelopes (

View File

@ -422,11 +422,6 @@ impl ImapStream {
self.stream.write_all(b"\r\n").await?;
Ok(())
}
pub async fn set_nonblocking(&mut self, val: bool) -> Result<()> {
//self.stream.set_nonblocking(val).await?;
Ok(())
}
}
impl ImapConnection {
@ -552,11 +547,6 @@ impl ImapConnection {
Ok(())
}
pub async fn set_nonblocking(&mut self, val: bool) -> Result<()> {
self.stream.as_mut()?.set_nonblocking(val).await?;
Ok(())
}
pub async fn select_mailbox(
&mut self,
mailbox_hash: MailboxHash,
@ -699,7 +689,7 @@ impl ImapBlockingConnection {
self.err.as_ref().map(String::as_str)
}
pub fn into_stream<'a>(&'a mut self) -> impl Future<Output = Option<Vec<u8>>> + 'a {
pub fn as_stream<'a>(&'a mut self) -> impl Future<Output = Option<Vec<u8>>> + 'a {
self.result.drain(0..self.prev_res_length);
self.prev_res_length = 0;
let mut break_flag = false;

View File

@ -53,7 +53,6 @@ impl ImapOp {
impl BackendOp for ImapOp {
fn as_bytes(&mut self) -> ResultFuture<Vec<u8>> {
let mut response = String::with_capacity(8 * 1024);
let connection = self.connection.clone();
let mailbox_hash = self.mailbox_hash;
let uid = self.uid;
@ -154,8 +153,7 @@ impl BackendOp for ImapOp {
let val = {
let mut bytes_cache = uid_store.byte_cache.lock()?;
let cache = bytes_cache.entry(uid).or_default();
let val = cache.flags;
val
cache.flags
};
Ok(val.unwrap())
}
@ -200,7 +198,7 @@ impl BackendOp for ImapOp {
Ok(v) => {
if v.len() == 1 {
debug!("responses len is {}", v.len());
let (_uid, (flags, _)) = v[0];
let (_uid, (_flags, _)) = v[0];
assert_eq!(_uid, uid);
}
}

View File

@ -1358,9 +1358,9 @@ pub fn quoted(input: &[u8]) -> IResult<&[u8], Vec<u8>> {
i += 1;
}
return Err(nom::Err::Error(
Err(nom::Err::Error(
(input, "quoted(): not a quoted phrase").into(),
));
))
}
pub fn quoted_or_nil(input: &[u8]) -> IResult<&[u8], Option<Vec<u8>>> {
@ -1529,9 +1529,9 @@ fn string_token(input: &[u8]) -> IResult<&[u8], &[u8]> {
i += 1;
}
return Err(nom::Err::Error(
Err(nom::Err::Error(
(input, "string_token(): not a quoted phrase").into(),
));
))
}
// ASTRING-CHAR = ATOM-CHAR / resp-specials

View File

@ -304,7 +304,7 @@ impl ImapConnection {
Ok(mut v) => {
if let Some(uid) = v.pop() {
let lck = self.uid_store.uid_index.lock().unwrap();
let env_hash = lck.get(&(mailbox_hash, uid)).map(|&h| h);
let env_hash = lck.get(&(mailbox_hash, uid)).copied();
drop(lck);
if let Some(env_hash) = env_hash {
if !flags.0.intersects(crate::email::Flag::SEEN) {

View File

@ -170,7 +170,7 @@ pub async fn idle(kit: ImapWatchKit) -> Result<()> {
const _26_MINS: std::time::Duration = std::time::Duration::from_secs(26 * 60);
/* duration interval to check other mailboxes for changes */
const _5_MINS: std::time::Duration = std::time::Duration::from_secs(5 * 60);
while let Some(line) = blockn.into_stream().await {
while let Some(line) = blockn.as_stream().await {
let now = std::time::Instant::now();
if now.duration_since(beat) >= _26_MINS {
let mut main_conn_lck = main_conn.lock().await;
@ -203,7 +203,7 @@ pub async fn idle(kit: ImapWatchKit) -> Result<()> {
.map(|(_, v)| v)
.map_err(MeliError::from)
{
Ok(Some(Recent(r))) => {
Ok(Some(Recent(_r))) => {
let mut conn = main_conn.lock().await;
/* UID SEARCH RECENT */
exit_on_error!(

View File

@ -195,12 +195,11 @@ impl MailBackend for JmapType {
}
fn connect(&mut self) {
if self.is_online().is_err() {
if Instant::now().duration_since(self.online.lock().unwrap().0)
if self.is_online().is_err()
&& Instant::now().duration_since(self.online.lock().unwrap().0)
>= std::time::Duration::new(2, 0)
{
let _ = self.mailboxes();
}
{
let _ = self.mailboxes();
}
}

View File

@ -58,7 +58,7 @@ impl JmapConnection {
};
if server_conf.server_port != 443 {
jmap_session_resource_url.push(':');
jmap_session_resource_url.extend(server_conf.server_port.to_string().chars());
jmap_session_resource_url.push_str(&server_conf.server_port.to_string());
}
jmap_session_resource_url.push_str("/.well-known/jmap");

View File

@ -64,7 +64,7 @@ pub trait Method<OBJ: Object>: Serialize {
const NAME: &'static str;
}
static USING: &'static [&'static str] = &["urn:ietf:params:jmap:core", "urn:ietf:params:jmap:mail"];
static USING: &[&str] = &["urn:ietf:params:jmap:core", "urn:ietf:params:jmap:mail"];
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
@ -208,9 +208,7 @@ pub fn get_message_list(conn: &JmapConnection, mailbox: &JmapMailbox) -> Result<
pub fn get_message(conn: &JmapConnection, ids: &[String]) -> Result<Vec<Envelope>> {
let email_call: EmailGet = EmailGet::new(
Get::new()
.ids(Some(JmapArgument::value(
ids.iter().cloned().collect::<Vec<String>>(),
)))
.ids(Some(JmapArgument::value(ids.to_vec())))
.account_id(conn.mail_account_id().to_string()),
);

View File

@ -166,10 +166,10 @@ impl<OBJ: Object + Serialize + std::fmt::Debug> Serialize for Get<OBJ> {
if !self.account_id.is_empty() {
fields_no += 1;
}
if !self.ids.is_none() {
if self.ids.is_some() {
fields_no += 1;
}
if !self.properties.is_none() {
if self.properties.is_some() {
fields_no += 1;
}
@ -204,7 +204,7 @@ impl<OBJ: Object + Serialize + std::fmt::Debug> Serialize for Get<OBJ> {
}
}
if !self.properties.is_none() {
if self.properties.is_some() {
state.serialize_field("properties", self.properties.as_ref().unwrap())?;
}

View File

@ -283,10 +283,7 @@ impl MailBackend for MaildirType {
let op = Box::new(MaildirOp::new(hash, map.clone(), mailbox_hash));
if let Ok(e) = Envelope::from_token(op, hash) {
mailbox_index.lock().unwrap().insert(e.hash(), mailbox_hash);
let file_name = PathBuf::from(file)
.strip_prefix(&root_path)
.unwrap()
.to_path_buf();
let file_name = file.strip_prefix(&root_path).unwrap().to_path_buf();
if let Ok(cached) = cache_dir.place_cache_file(file_name) {
/* place result in cache directory */
let f = match fs::File::create(cached) {
@ -449,7 +446,6 @@ impl MailBackend for MaildirType {
*v = pathbuf.clone().into();
*k
} else {
drop(index_lock);
drop(hash_indexes_lock);
/* Did we just miss a Create event? In any case, create
* envelope. */
@ -608,7 +604,6 @@ impl MailBackend for MaildirType {
.unwrap()
.to_path_buf();
debug!("filename = {:?}", file_name);
drop(index_lock);
drop(hash_indexes_lock);
if let Some(env) = add_path_to_index(
&hash_indexes,
@ -813,10 +808,11 @@ impl MaildirType {
&settings,
) {
f.children = recurse_mailboxes(mailboxes, settings, &path)?;
f.children
.iter()
.map(|c| mailboxes.get_mut(c).map(|f| f.parent = Some(f.hash)))
.count();
for c in &f.children {
if let Some(f) = mailboxes.get_mut(c) {
f.parent = Some(f.hash);
}
}
children.push(f.hash);
mailboxes.insert(f.hash, f);
} else {
@ -834,14 +830,11 @@ impl MaildirType {
true,
&settings,
) {
f.children
.iter()
.map(|c| {
mailboxes
.get_mut(c)
.map(|f| f.parent = Some(f.hash))
})
.count();
for c in &f.children {
if let Some(f) = mailboxes.get_mut(c) {
f.parent = Some(f.hash);
}
}
children.push(f.hash);
mailboxes.insert(f.hash, f);
}
@ -881,18 +874,22 @@ impl MaildirType {
if mailboxes.is_empty() {
let children = recurse_mailboxes(&mut mailboxes, settings, &root_path)?;
children
.iter()
.map(|c| mailboxes.get_mut(c).map(|f| f.parent = None))
.count();
for c in &children {
if let Some(f) = mailboxes.get_mut(c) {
f.parent = None;
}
}
} else {
let root_hash = *mailboxes.keys().nth(0).unwrap();
let root_hash = *mailboxes.keys().next().unwrap();
let children = recurse_mailboxes(&mut mailboxes, settings, &root_path)?;
children
.iter()
.map(|c| mailboxes.get_mut(c).map(|f| f.parent = Some(root_hash)))
.count();
mailboxes.get_mut(&root_hash).map(|f| f.children = children);
for c in &children {
if let Some(f) = mailboxes.get_mut(c) {
f.parent = Some(root_hash);
}
}
if let Some(f) = mailboxes.get_mut(&root_hash) {
f.children = children;
}
}
for f in mailboxes.values_mut() {
if is_subscribed(f.path()) {
@ -1176,7 +1173,7 @@ impl MaildirType {
let mut writer = io::BufWriter::new(file);
writer.write_all(&bytes).unwrap();
return Ok(());
Ok(())
}
pub fn validate_config(s: &AccountSettings) -> Result<()> {

View File

@ -105,11 +105,6 @@ impl MaildirStream {
map: HashIndexes,
mailbox_index: Arc<Mutex<HashMap<EnvelopeHash, MailboxHash>>>,
) -> Result<Vec<Envelope>> {
let unseen = unseen.clone();
let total = total.clone();
let map = map.clone();
let mailbox_index = mailbox_index.clone();
let root_path = root_path.clone();
let len = chunk.len();
let size = if len <= 100 { 100 } else { (len / 100) * 100 };
let mut local_r: Vec<Envelope> = Vec::with_capacity(chunk.len());

View File

@ -31,7 +31,6 @@ use crate::email::*;
use crate::error::{MeliError, Result};
use crate::get_path_hash;
use crate::shellexpand::ShellExpandTrait;
use libc;
use memmap::{Mmap, Protection};
use nom::bytes::complete::tag;
use nom::character::complete::digit1;
@ -324,33 +323,33 @@ impl MboxReader {
Ok(mut env) => {
let mut flags = Flag::empty();
if env.other_headers().contains_key("Status") {
if env.other_headers()["Status"].contains("F") {
if env.other_headers()["Status"].contains('F') {
flags.set(Flag::FLAGGED, true);
}
if env.other_headers()["Status"].contains("A") {
if env.other_headers()["Status"].contains('A') {
flags.set(Flag::REPLIED, true);
}
if env.other_headers()["Status"].contains("R") {
if env.other_headers()["Status"].contains('R') {
flags.set(Flag::SEEN, true);
}
if env.other_headers()["Status"].contains("D") {
if env.other_headers()["Status"].contains('D') {
flags.set(Flag::TRASHED, true);
}
}
if env.other_headers().contains_key("X-Status") {
if env.other_headers()["X-Status"].contains("F") {
if env.other_headers()["X-Status"].contains('F') {
flags.set(Flag::FLAGGED, true);
}
if env.other_headers()["X-Status"].contains("A") {
if env.other_headers()["X-Status"].contains('A') {
flags.set(Flag::REPLIED, true);
}
if env.other_headers()["X-Status"].contains("R") {
if env.other_headers()["X-Status"].contains('R') {
flags.set(Flag::SEEN, true);
}
if env.other_headers()["X-Status"].contains("D") {
if env.other_headers()["X-Status"].contains('D') {
flags.set(Flag::TRASHED, true);
}
if env.other_headers()["X-Status"].contains("T") {
if env.other_headers()["X-Status"].contains('T') {
flags.set(Flag::DRAFT, true);
}
}
@ -422,33 +421,33 @@ impl MboxReader {
Ok(mut env) => {
let mut flags = Flag::empty();
if env.other_headers().contains_key("Status") {
if env.other_headers()["Status"].contains("F") {
if env.other_headers()["Status"].contains('F') {
flags.set(Flag::FLAGGED, true);
}
if env.other_headers()["Status"].contains("A") {
if env.other_headers()["Status"].contains('A') {
flags.set(Flag::REPLIED, true);
}
if env.other_headers()["Status"].contains("R") {
if env.other_headers()["Status"].contains('R') {
flags.set(Flag::SEEN, true);
}
if env.other_headers()["Status"].contains("D") {
if env.other_headers()["Status"].contains('D') {
flags.set(Flag::TRASHED, true);
}
}
if env.other_headers().contains_key("X-Status") {
if env.other_headers()["X-Status"].contains("F") {
if env.other_headers()["X-Status"].contains('F') {
flags.set(Flag::FLAGGED, true);
}
if env.other_headers()["X-Status"].contains("A") {
if env.other_headers()["X-Status"].contains('A') {
flags.set(Flag::REPLIED, true);
}
if env.other_headers()["X-Status"].contains("R") {
if env.other_headers()["X-Status"].contains('R') {
flags.set(Flag::SEEN, true);
}
if env.other_headers()["X-Status"].contains("D") {
if env.other_headers()["X-Status"].contains('D') {
flags.set(Flag::TRASHED, true);
}
if env.other_headers()["X-Status"].contains("T") {
if env.other_headers()["X-Status"].contains('T') {
flags.set(Flag::DRAFT, true);
}
}
@ -471,33 +470,33 @@ impl MboxReader {
Ok(mut env) => {
let mut flags = Flag::empty();
if env.other_headers().contains_key("Status") {
if env.other_headers()["Status"].contains("F") {
if env.other_headers()["Status"].contains('F') {
flags.set(Flag::FLAGGED, true);
}
if env.other_headers()["Status"].contains("A") {
if env.other_headers()["Status"].contains('A') {
flags.set(Flag::REPLIED, true);
}
if env.other_headers()["Status"].contains("R") {
if env.other_headers()["Status"].contains('R') {
flags.set(Flag::SEEN, true);
}
if env.other_headers()["Status"].contains("D") {
if env.other_headers()["Status"].contains('D') {
flags.set(Flag::TRASHED, true);
}
}
if env.other_headers().contains_key("X-Status") {
if env.other_headers()["X-Status"].contains("F") {
if env.other_headers()["X-Status"].contains('F') {
flags.set(Flag::FLAGGED, true);
}
if env.other_headers()["X-Status"].contains("A") {
if env.other_headers()["X-Status"].contains('A') {
flags.set(Flag::REPLIED, true);
}
if env.other_headers()["X-Status"].contains("R") {
if env.other_headers()["X-Status"].contains('R') {
flags.set(Flag::SEEN, true);
}
if env.other_headers()["X-Status"].contains("D") {
if env.other_headers()["X-Status"].contains('D') {
flags.set(Flag::TRASHED, true);
}
if env.other_headers()["X-Status"].contains("T") {
if env.other_headers()["X-Status"].contains('T') {
flags.set(Flag::DRAFT, true);
}
}
@ -583,9 +582,7 @@ impl MboxReader {
Ok((input, env))
}
}
Err(_err) => {
return Self::MboxRd.parse(orig_input);
}
Err(_err) => Self::MboxRd.parse(orig_input),
}
}
}
@ -621,7 +618,7 @@ pub fn mbox_parse(
offset += 2;
}
} else {
Err(e)?;
return Err(e);
}
continue;
}
@ -636,7 +633,7 @@ pub fn mbox_parse(
envelopes.push(env);
}
return Ok((&[], envelopes));
Ok((&[], envelopes))
}
/// Mbox backend
@ -662,7 +659,7 @@ impl MailBackend for MboxType {
let mailbox_index = self.mailbox_index.clone();
let mailboxes = self.mailboxes.clone();
let mailbox_path = mailboxes.lock().unwrap()[&mailbox_hash].fs_path.clone();
let prefer_mbox_type = self.prefer_mbox_type.clone();
let prefer_mbox_type = self.prefer_mbox_type;
let closure = move |_work_context| {
let tx = tx.clone();
let file = match std::fs::OpenOptions::new()
@ -691,7 +688,7 @@ impl MailBackend for MboxType {
let index = mailboxes_lck[&mailbox_hash].index.clone();
drop(mailboxes_lck);
let payload = mbox_parse(index, contents.as_slice(), 0, prefer_mbox_type)
.map_err(|e| MeliError::from(e))
.map_err(MeliError::from)
.map(|(_, v)| {
for v in v.iter() {
mailbox_index_lck.insert(v.hash(), mailbox_hash);
@ -735,7 +732,7 @@ impl MailBackend for MboxType {
hasher.finish()
};
let mailboxes = self.mailboxes.clone();
let prefer_mbox_type = self.prefer_mbox_type.clone();
let prefer_mbox_type = self.prefer_mbox_type;
let handle = std::thread::Builder::new()
.name(format!("watching {}", self.account_name,))
.spawn(move || {
@ -813,7 +810,7 @@ impl MailBackend for MboxType {
.lock()
.unwrap()
.values()
.any(|f| &f.fs_path == &pathbuf)
.any(|f| f.fs_path == pathbuf)
{
let mailbox_hash = get_path_hash!(&pathbuf);
sender.send(RefreshEvent {
@ -971,7 +968,7 @@ impl MboxType {
.path
.file_name()
.map(|f| f.to_string_lossy().into())
.unwrap_or(String::new());
.unwrap_or_default();
let hash = get_path_hash!(&ret.path);
let read_only = if let Ok(metadata) = std::fs::metadata(&ret.path) {

View File

@ -189,7 +189,7 @@ impl NotmuchDb {
_is_subscribed: Box<dyn Fn(&str) -> bool>,
) -> Result<Box<dyn MailBackend>> {
let lib = Arc::new(libloading::Library::new("libnotmuch.so.5")?);
let path = Path::new(s.root_mailbox.as_str()).expand().to_path_buf();
let path = Path::new(s.root_mailbox.as_str()).expand();
if !path.exists() {
return Err(MeliError::new(format!(
"\"root_mailbox\" {} for account {} is not a valid path.",
@ -243,7 +243,7 @@ impl NotmuchDb {
}
pub fn validate_config(s: &AccountSettings) -> Result<()> {
let path = Path::new(s.root_mailbox.as_str()).expand().to_path_buf();
let path = Path::new(s.root_mailbox.as_str()).expand();
if !path.exists() {
return Err(MeliError::new(format!(
"\"root_mailbox\" {} for account {} is not a valid path.",
@ -580,7 +580,7 @@ impl MailBackend for NotmuchDb {
sender.send(RefreshEvent {
account_hash,
mailbox_hash: 0,
kind: Failure(err.into()),
kind: Failure(err),
});
}
})?;