Inline format arguments

This feature has been stable since Rust 1.58.0.
This commit is contained in:
link2xt
2023-01-30 08:37:17 +00:00
parent c911f1262a
commit fcf73165ed
58 changed files with 357 additions and 435 deletions

View File

@@ -6,8 +6,7 @@
non_upper_case_globals, non_upper_case_globals,
non_camel_case_types, non_camel_case_types,
clippy::missing_safety_doc, clippy::missing_safety_doc,
clippy::expect_fun_call, clippy::expect_fun_call
clippy::uninlined_format_args
)] )]
#[macro_use] #[macro_use]
@@ -116,7 +115,7 @@ pub unsafe extern "C" fn dc_context_new(
match ctx { match ctx {
Ok(ctx) => Box::into_raw(Box::new(ctx)), Ok(ctx) => Box::into_raw(Box::new(ctx)),
Err(err) => { Err(err) => {
eprintln!("failed to create context: {:#}", err); eprintln!("failed to create context: {err:#}");
ptr::null_mut() ptr::null_mut()
} }
} }
@@ -140,7 +139,7 @@ pub unsafe extern "C" fn dc_context_new_closed(dbfile: *const libc::c_char) -> *
)) { )) {
Ok(context) => Box::into_raw(Box::new(context)), Ok(context) => Box::into_raw(Box::new(context)),
Err(err) => { Err(err) => {
eprintln!("failed to create context: {:#}", err); eprintln!("failed to create context: {err:#}");
ptr::null_mut() ptr::null_mut()
} }
} }
@@ -215,7 +214,7 @@ pub unsafe extern "C" fn dc_set_config(
if key.starts_with("ui.") { if key.starts_with("ui.") {
ctx.set_ui_config(&key, value.as_deref()) ctx.set_ui_config(&key, value.as_deref())
.await .await
.with_context(|| format!("Can't set {} to {:?}", key, value)) .with_context(|| format!("Can't set {key} to {value:?}"))
.log_err(ctx, "dc_set_config() failed") .log_err(ctx, "dc_set_config() failed")
.is_ok() as libc::c_int .is_ok() as libc::c_int
} else { } else {
@@ -223,7 +222,7 @@ pub unsafe extern "C" fn dc_set_config(
Ok(key) => ctx Ok(key) => ctx
.set_config(key, value.as_deref()) .set_config(key, value.as_deref())
.await .await
.with_context(|| format!("Can't set {} to {:?}", key, value)) .with_context(|| format!("Can't set {key} to {value:?}"))
.log_err(ctx, "dc_set_config() failed") .log_err(ctx, "dc_set_config() failed")
.is_ok() as libc::c_int, .is_ok() as libc::c_int,
Err(_) => { Err(_) => {
@@ -350,7 +349,7 @@ fn render_info(
) -> std::result::Result<String, std::fmt::Error> { ) -> std::result::Result<String, std::fmt::Error> {
let mut res = String::new(); let mut res = String::new();
for (key, value) in &info { for (key, value) in &info {
writeln!(&mut res, "{}={}", key, value)?; writeln!(&mut res, "{key}={value}")?;
} }
Ok(res) Ok(res)
@@ -1286,11 +1285,11 @@ pub unsafe extern "C" fn dc_get_chat_media(
} else { } else {
Some(ChatId::new(chat_id)) Some(ChatId::new(chat_id))
}; };
let msg_type = from_prim(msg_type).expect(&format!("invalid msg_type = {}", msg_type)); let msg_type = from_prim(msg_type).expect(&format!("invalid msg_type = {msg_type}"));
let or_msg_type2 = let or_msg_type2 =
from_prim(or_msg_type2).expect(&format!("incorrect or_msg_type2 = {}", or_msg_type2)); from_prim(or_msg_type2).expect(&format!("incorrect or_msg_type2 = {or_msg_type2}"));
let or_msg_type3 = let or_msg_type3 =
from_prim(or_msg_type3).expect(&format!("incorrect or_msg_type3 = {}", or_msg_type3)); from_prim(or_msg_type3).expect(&format!("incorrect or_msg_type3 = {or_msg_type3}"));
block_on(async move { block_on(async move {
Box::into_raw(Box::new( Box::into_raw(Box::new(
@@ -1322,11 +1321,11 @@ pub unsafe extern "C" fn dc_get_next_media(
}; };
let ctx = &*context; let ctx = &*context;
let msg_type = from_prim(msg_type).expect(&format!("invalid msg_type = {}", msg_type)); let msg_type = from_prim(msg_type).expect(&format!("invalid msg_type = {msg_type}"));
let or_msg_type2 = let or_msg_type2 =
from_prim(or_msg_type2).expect(&format!("incorrect or_msg_type2 = {}", or_msg_type2)); from_prim(or_msg_type2).expect(&format!("incorrect or_msg_type2 = {or_msg_type2}"));
let or_msg_type3 = let or_msg_type3 =
from_prim(or_msg_type3).expect(&format!("incorrect or_msg_type3 = {}", or_msg_type3)); from_prim(or_msg_type3).expect(&format!("incorrect or_msg_type3 = {or_msg_type3}"));
block_on(async move { block_on(async move {
chat::get_next_media( chat::get_next_media(
@@ -2186,7 +2185,7 @@ pub unsafe extern "C" fn dc_imex(
let what = match imex::ImexMode::from_i32(what_raw) { let what = match imex::ImexMode::from_i32(what_raw) {
Some(what) => what, Some(what) => what,
None => { None => {
eprintln!("ignoring invalid argument {} to dc_imex", what_raw); eprintln!("ignoring invalid argument {what_raw} to dc_imex");
return; return;
} }
}; };
@@ -3074,7 +3073,7 @@ pub unsafe extern "C" fn dc_msg_new(
return ptr::null_mut(); return ptr::null_mut();
} }
let context = &*context; let context = &*context;
let viewtype = from_prim(viewtype).expect(&format!("invalid viewtype = {}", viewtype)); let viewtype = from_prim(viewtype).expect(&format!("invalid viewtype = {viewtype}"));
let msg = MessageWrapper { let msg = MessageWrapper {
context, context,
message: message::Message::new(viewtype), message: message::Message::new(viewtype),
@@ -3257,7 +3256,7 @@ pub unsafe extern "C" fn dc_msg_get_webxdc_blob(
ptr as *mut libc::c_char ptr as *mut libc::c_char
} }
Err(err) => { Err(err) => {
eprintln!("failed read blob from archive: {}", err); eprintln!("failed read blob from archive: {err}");
ptr::null_mut() ptr::null_mut()
} }
} }
@@ -4310,7 +4309,7 @@ pub unsafe extern "C" fn dc_accounts_new(
Ok(accs) => Box::into_raw(Box::new(AccountsWrapper::new(accs))), Ok(accs) => Box::into_raw(Box::new(AccountsWrapper::new(accs))),
Err(err) => { Err(err) => {
// We are using Anyhow's .context() and to show the inner error, too, we need the {:#}: // We are using Anyhow's .context() and to show the inner error, too, we need the {:#}:
eprintln!("failed to create accounts: {:#}", err); eprintln!("failed to create accounts: {err:#}");
ptr::null_mut() ptr::null_mut()
} }
} }
@@ -4378,8 +4377,7 @@ pub unsafe extern "C" fn dc_accounts_select_account(
Ok(()) => 1, Ok(()) => 1,
Err(err) => { Err(err) => {
accounts.emit_event(EventType::Error(format!( accounts.emit_event(EventType::Error(format!(
"Failed to select account: {:#}", "Failed to select account: {err:#}"
err
))); )));
0 0
} }
@@ -4401,10 +4399,7 @@ pub unsafe extern "C" fn dc_accounts_add_account(accounts: *mut dc_accounts_t) -
match accounts.add_account().await { match accounts.add_account().await {
Ok(id) => id, Ok(id) => id,
Err(err) => { Err(err) => {
accounts.emit_event(EventType::Error(format!( accounts.emit_event(EventType::Error(format!("Failed to add account: {err:#}")));
"Failed to add account: {:#}",
err
)));
0 0
} }
} }
@@ -4425,10 +4420,7 @@ pub unsafe extern "C" fn dc_accounts_add_closed_account(accounts: *mut dc_accoun
match accounts.add_closed_account().await { match accounts.add_closed_account().await {
Ok(id) => id, Ok(id) => id,
Err(err) => { Err(err) => {
accounts.emit_event(EventType::Error(format!( accounts.emit_event(EventType::Error(format!("Failed to add account: {err:#}")));
"Failed to add account: {:#}",
err
)));
0 0
} }
} }
@@ -4453,8 +4445,7 @@ pub unsafe extern "C" fn dc_accounts_remove_account(
Ok(()) => 1, Ok(()) => 1,
Err(err) => { Err(err) => {
accounts.emit_event(EventType::Error(format!( accounts.emit_event(EventType::Error(format!(
"Failed to remove account: {:#}", "Failed to remove account: {err:#}"
err
))); )));
0 0
} }
@@ -4484,8 +4475,7 @@ pub unsafe extern "C" fn dc_accounts_migrate_account(
Ok(id) => id, Ok(id) => id,
Err(err) => { Err(err) => {
accounts.emit_event(EventType::Error(format!( accounts.emit_event(EventType::Error(format!(
"Failed to migrate account: {:#}", "Failed to migrate account: {err:#}"
err
))); )));
0 0
} }

View File

@@ -134,7 +134,7 @@ impl CommandApi {
if let Some(ctx) = context_option { if let Some(ctx) = context_option {
accounts.push(Account::from_context(&ctx, id).await?) accounts.push(Account::from_context(&ctx, id).await?)
} else { } else {
println!("account with id {} doesn't exist anymore", id); println!("account with id {id} doesn't exist anymore");
} }
} }
Ok(accounts) Ok(accounts)
@@ -242,7 +242,7 @@ impl CommandApi {
for (key, value) in config.into_iter() { for (key, value) in config.into_iter() {
set_config(&ctx, &key, value.as_deref()) set_config(&ctx, &key, value.as_deref())
.await .await
.with_context(|| format!("Can't set {} to {:?}", key, value))?; .with_context(|| format!("Can't set {key} to {value:?}"))?;
} }
Ok(()) Ok(())
} }
@@ -459,7 +459,7 @@ impl CommandApi {
Ok(res) => res, Ok(res) => res,
Err(err) => ChatListItemFetchResult::Error { Err(err) => ChatListItemFetchResult::Error {
id: entry.0, id: entry.0,
error: format!("{:?}", err), error: format!("{err:?}"),
}, },
}, },
); );
@@ -1714,7 +1714,7 @@ async fn set_config(
ctx.set_ui_config(key, value).await?; ctx.set_ui_config(key, value).await?;
} else { } else {
ctx.set_config( ctx.set_config(
Config::from_str(key).with_context(|| format!("unknown key {:?}", key))?, Config::from_str(key).with_context(|| format!("unknown key {key:?}"))?,
value, value,
) )
.await?; .await?;
@@ -1736,7 +1736,7 @@ async fn get_config(
if key.starts_with("ui.") { if key.starts_with("ui.") {
ctx.get_ui_config(key).await ctx.get_ui_config(key).await
} else { } else {
ctx.get_config(Config::from_str(key).with_context(|| format!("unknown key {:?}", key))?) ctx.get_config(Config::from_str(key).with_context(|| format!("unknown key {key:?}"))?)
.await .await
} }
} }

View File

@@ -10,7 +10,7 @@ pub mod reactions;
pub mod webxdc; pub mod webxdc;
pub fn color_int_to_hex_string(color: u32) -> String { pub fn color_int_to_hex_string(color: u32) -> String {
format!("{:#08x}", color).replace("0x", "#") format!("{color:#08x}").replace("0x", "#")
} }
fn maybe_empty_string_to_option(string: String) -> Option<String> { fn maybe_empty_string_to_option(string: String) -> Option<String> {

View File

@@ -1,5 +1,3 @@
#![allow(clippy::uninlined_format_args)]
pub mod api; pub mod api;
pub use api::events; pub use api::events;
pub use yerpc; pub use yerpc;
@@ -39,7 +37,7 @@ mod tests {
let response = r#"{"jsonrpc":"2.0","id":1,"result":1}"#; let response = r#"{"jsonrpc":"2.0","id":1,"result":1}"#;
session.handle_incoming(request).await; session.handle_incoming(request).await;
let result = receiver.next().await; let result = receiver.next().await;
println!("{:?}", result); println!("{result:?}");
assert_eq!(result, Some(response.to_owned())); assert_eq!(result, Some(response.to_owned()));
} }
{ {
@@ -47,7 +45,7 @@ mod tests {
let response = r#"{"jsonrpc":"2.0","id":2,"result":[1]}"#; let response = r#"{"jsonrpc":"2.0","id":2,"result":[1]}"#;
session.handle_incoming(request).await; session.handle_incoming(request).await;
let result = receiver.next().await; let result = receiver.next().await;
println!("{:?}", result); println!("{result:?}");
assert_eq!(result, Some(response.to_owned())); assert_eq!(result, Some(response.to_owned()));
} }

View File

@@ -1,5 +1,3 @@
#![allow(clippy::uninlined_format_args)]
///! Delta Chat core RPC server. ///! Delta Chat core RPC server.
///! ///!
///! It speaks JSON Lines over stdio. ///! It speaks JSON Lines over stdio.
@@ -42,7 +40,7 @@ async fn main() -> Result<()> {
while let Some(message) = out_receiver.next().await { while let Some(message) = out_receiver.next().await {
let message = serde_json::to_string(&message)?; let message = serde_json::to_string(&message)?;
log::trace!("RPC send {}", message); log::trace!("RPC send {}", message);
println!("{}", message); println!("{message}");
} }
Ok(()) Ok(())
}); });

View File

@@ -31,7 +31,7 @@ use tokio::fs;
/// Argument is a bitmask, executing single or multiple actions in one call. /// Argument is a bitmask, executing single or multiple actions in one call.
/// e.g. bitmask 7 triggers actions definded with bits 1, 2 and 4. /// e.g. bitmask 7 triggers actions definded with bits 1, 2 and 4.
async fn reset_tables(context: &Context, bits: i32) { async fn reset_tables(context: &Context, bits: i32) {
println!("Resetting tables ({})...", bits); println!("Resetting tables ({bits})...");
if 0 != bits & 1 { if 0 != bits & 1 {
context context
.sql() .sql()
@@ -101,7 +101,7 @@ async fn poke_eml_file(context: &Context, filename: impl AsRef<Path>) -> Result<
let data = read_file(context, filename).await?; let data = read_file(context, filename).await?;
if let Err(err) = receive_imf(context, &data, false).await { if let Err(err) = receive_imf(context, &data, false).await {
println!("receive_imf errored: {:?}", err); println!("receive_imf errored: {err:?}");
} }
Ok(()) Ok(())
} }
@@ -148,7 +148,7 @@ async fn poke_spec(context: &Context, spec: Option<&str>) -> bool {
let name = name_f.to_string_lossy(); let name = name_f.to_string_lossy();
if name.ends_with(".eml") { if name.ends_with(".eml") {
let path_plus_name = format!("{}/{}", &real_spec, name); let path_plus_name = format!("{}/{}", &real_spec, name);
println!("Import: {}", path_plus_name); println!("Import: {path_plus_name}");
if poke_eml_file(context, path_plus_name).await.is_ok() { if poke_eml_file(context, path_plus_name).await.is_ok() {
read_cnt += 1 read_cnt += 1
} }
@@ -168,7 +168,7 @@ async fn log_msg(context: &Context, prefix: impl AsRef<str>, msg: &Message) {
.await .await
.expect("invalid contact"); .expect("invalid contact");
let contact_name = if let Some(name) = msg.get_override_sender_name() { let contact_name = if let Some(name) = msg.get_override_sender_name() {
format!("~{}", name) format!("~{name}")
} else { } else {
contact.get_display_name().to_string() contact.get_display_name().to_string()
}; };
@@ -223,7 +223,7 @@ async fn log_msg(context: &Context, prefix: impl AsRef<str>, msg: &Message) {
"[WEBXDC: {}, icon={}, document={}, summary={}, source_code_url={}]", "[WEBXDC: {}, icon={}, document={}, summary={}, source_code_url={}]",
info.name, info.icon, info.document, info.summary, info.source_code_url info.name, info.icon, info.document, info.summary, info.source_code_url
), ),
Err(err) => format!("[get_webxdc_info() failed: {}]", err), Err(err) => format!("[get_webxdc_info() failed: {err}]"),
} }
} else { } else {
"".to_string() "".to_string()
@@ -435,10 +435,9 @@ pub async fn cmdline(context: Context, line: &str, chat_id: &mut ChatId) -> Resu
), ),
}, },
"initiate-key-transfer" => match initiate_key_transfer(&context).await { "initiate-key-transfer" => match initiate_key_transfer(&context).await {
Ok(setup_code) => println!( Ok(setup_code) => {
"Setup code for the transferred setup message: {}", println!("Setup code for the transferred setup message: {setup_code}",)
setup_code, }
),
Err(err) => bail!("Failed to generate setup code: {}", err), Err(err) => bail!("Failed to generate setup code: {}", err),
}, },
"get-setupcodebegin" => { "get-setupcodebegin" => {
@@ -528,7 +527,7 @@ pub async fn cmdline(context: Context, line: &str, chat_id: &mut ChatId) -> Resu
ensure!(!arg1.is_empty(), "Argument <key> missing."); ensure!(!arg1.is_empty(), "Argument <key> missing.");
let key = config::Config::from_str(arg1)?; let key = config::Config::from_str(arg1)?;
let val = context.get_config(key).await; let val = context.get_config(key).await;
println!("{}={:?}", key, val); println!("{key}={val:?}");
} }
"info" => { "info" => {
println!("{:#?}", context.get_info().await); println!("{:#?}", context.get_info().await);
@@ -540,7 +539,7 @@ pub async fn cmdline(context: Context, line: &str, chat_id: &mut ChatId) -> Resu
match context.get_connectivity_html().await { match context.get_connectivity_html().await {
Ok(html) => { Ok(html) => {
fs::write(&file, html).await?; fs::write(&file, html).await?;
println!("Report written to: {:#?}", file); println!("Report written to: {file:#?}");
} }
Err(err) => { Err(err) => {
bail!("Failed to get connectivity html: {}", err); bail!("Failed to get connectivity html: {}", err);
@@ -613,7 +612,7 @@ pub async fn cmdline(context: Context, line: &str, chat_id: &mut ChatId) -> Resu
"{}{}{} [{}]{}", "{}{}{} [{}]{}",
summary summary
.prefix .prefix
.map_or_else(String::new, |prefix| format!("{}: ", prefix)), .map_or_else(String::new, |prefix| format!("{prefix}: ")),
summary.text, summary.text,
statestr, statestr,
&timestr, &timestr,
@@ -631,8 +630,8 @@ pub async fn cmdline(context: Context, line: &str, chat_id: &mut ChatId) -> Resu
if location::is_sending_locations_to_chat(&context, None).await? { if location::is_sending_locations_to_chat(&context, None).await? {
println!("Location streaming enabled."); println!("Location streaming enabled.");
} }
println!("{} chats", cnt); println!("{cnt} chats");
println!("{:?} to create this list", time_needed); println!("{time_needed:?} to create this list");
} }
"chat" => { "chat" => {
if sel_chat.is_none() && arg1.is_empty() { if sel_chat.is_none() && arg1.is_empty() {
@@ -640,7 +639,7 @@ pub async fn cmdline(context: Context, line: &str, chat_id: &mut ChatId) -> Resu
} }
if !arg1.is_empty() { if !arg1.is_empty() {
let id = ChatId::new(arg1.parse()?); let id = ChatId::new(arg1.parse()?);
println!("Selecting chat {}", id); println!("Selecting chat {id}");
sel_chat = Some(Chat::load_from_db(&context, id).await?); sel_chat = Some(Chat::load_from_db(&context, id).await?);
*chat_id = id; *chat_id = id;
} }
@@ -686,7 +685,7 @@ pub async fn cmdline(context: Context, line: &str, chat_id: &mut ChatId) -> Resu
}, },
match sel_chat.get_profile_image(&context).await? { match sel_chat.get_profile_image(&context).await? {
Some(icon) => match icon.to_str() { Some(icon) => match icon.to_str() {
Some(icon) => format!(" Icon: {}", icon), Some(icon) => format!(" Icon: {icon}"),
_ => " Icon: Err".to_string(), _ => " Icon: Err".to_string(),
}, },
_ => "".to_string(), _ => "".to_string(),
@@ -712,8 +711,7 @@ pub async fn cmdline(context: Context, line: &str, chat_id: &mut ChatId) -> Resu
let time_noticed_needed = time_noticed_start.elapsed().unwrap_or_default(); let time_noticed_needed = time_noticed_start.elapsed().unwrap_or_default();
println!( println!(
"{:?} to create this list, {:?} to mark all messages as noticed.", "{time_needed:?} to create this list, {time_noticed_needed:?} to mark all messages as noticed."
time_needed, time_noticed_needed
); );
} }
"createchat" => { "createchat" => {
@@ -721,26 +719,26 @@ pub async fn cmdline(context: Context, line: &str, chat_id: &mut ChatId) -> Resu
let contact_id = ContactId::new(arg1.parse()?); let contact_id = ContactId::new(arg1.parse()?);
let chat_id = ChatId::create_for_contact(&context, contact_id).await?; let chat_id = ChatId::create_for_contact(&context, contact_id).await?;
println!("Single#{} created successfully.", chat_id,); println!("Single#{chat_id} created successfully.",);
} }
"creategroup" => { "creategroup" => {
ensure!(!arg1.is_empty(), "Argument <name> missing."); ensure!(!arg1.is_empty(), "Argument <name> missing.");
let chat_id = let chat_id =
chat::create_group_chat(&context, ProtectionStatus::Unprotected, arg1).await?; chat::create_group_chat(&context, ProtectionStatus::Unprotected, arg1).await?;
println!("Group#{} created successfully.", chat_id); println!("Group#{chat_id} created successfully.");
} }
"createbroadcast" => { "createbroadcast" => {
let chat_id = chat::create_broadcast_list(&context).await?; let chat_id = chat::create_broadcast_list(&context).await?;
println!("Broadcast#{} created successfully.", chat_id); println!("Broadcast#{chat_id} created successfully.");
} }
"createprotected" => { "createprotected" => {
ensure!(!arg1.is_empty(), "Argument <name> missing."); ensure!(!arg1.is_empty(), "Argument <name> missing.");
let chat_id = let chat_id =
chat::create_group_chat(&context, ProtectionStatus::Protected, arg1).await?; chat::create_group_chat(&context, ProtectionStatus::Protected, arg1).await?;
println!("Group#{} created and protected successfully.", chat_id); println!("Group#{chat_id} created and protected successfully.");
} }
"addmember" => { "addmember" => {
ensure!(sel_chat.is_some(), "No chat selected"); ensure!(sel_chat.is_some(), "No chat selected");
@@ -770,7 +768,7 @@ pub async fn cmdline(context: Context, line: &str, chat_id: &mut ChatId) -> Resu
chat::set_chat_name( chat::set_chat_name(
&context, &context,
sel_chat.as_ref().unwrap().get_id(), sel_chat.as_ref().unwrap().get_id(),
format!("{} {}", arg1, arg2).trim(), format!("{arg1} {arg2}").trim(),
) )
.await?; .await?;
@@ -874,7 +872,7 @@ pub async fn cmdline(context: Context, line: &str, chat_id: &mut ChatId) -> Resu
ensure!(sel_chat.is_some(), "No chat selected."); ensure!(sel_chat.is_some(), "No chat selected.");
ensure!(!arg1.is_empty(), "No message text given."); ensure!(!arg1.is_empty(), "No message text given.");
let msg = format!("{} {}", arg1, arg2); let msg = format!("{arg1} {arg2}");
chat::send_text_msg(&context, sel_chat.as_ref().unwrap().get_id(), msg).await?; chat::send_text_msg(&context, sel_chat.as_ref().unwrap().get_id(), msg).await?;
} }
@@ -916,7 +914,7 @@ pub async fn cmdline(context: Context, line: &str, chat_id: &mut ChatId) -> Resu
chat::send_msg(&context, sel_chat.as_ref().unwrap().get_id(), &mut msg).await?; chat::send_msg(&context, sel_chat.as_ref().unwrap().get_id(), &mut msg).await?;
} }
"sendsyncmsg" => match context.send_sync_msg().await? { "sendsyncmsg" => match context.send_sync_msg().await? {
Some(msg_id) => println!("sync message sent as {}.", msg_id), Some(msg_id) => println!("sync message sent as {msg_id}."),
None => println!("sync message not needed."), None => println!("sync message not needed."),
}, },
"sendupdate" => { "sendupdate" => {
@@ -936,7 +934,7 @@ pub async fn cmdline(context: Context, line: &str, chat_id: &mut ChatId) -> Resu
"listmsgs" => { "listmsgs" => {
ensure!(!arg1.is_empty(), "Argument <query> missing."); ensure!(!arg1.is_empty(), "Argument <query> missing.");
let query = format!("{} {}", arg1, arg2).trim().to_string(); let query = format!("{arg1} {arg2}").trim().to_string();
let chat = sel_chat.as_ref().map(|sel_chat| sel_chat.get_id()); let chat = sel_chat.as_ref().map(|sel_chat| sel_chat.get_id());
let time_start = std::time::SystemTime::now(); let time_start = std::time::SystemTime::now();
let msglist = context.search_msgs(chat, &query).await?; let msglist = context.search_msgs(chat, &query).await?;
@@ -954,7 +952,7 @@ pub async fn cmdline(context: Context, line: &str, chat_id: &mut ChatId) -> Resu
}, },
query, query,
); );
println!("{:?} to create this list", time_needed); println!("{time_needed:?} to create this list");
} }
"draft" => { "draft" => {
ensure!(sel_chat.is_some(), "No chat selected."); ensure!(sel_chat.is_some(), "No chat selected.");
@@ -1000,9 +998,9 @@ pub async fn cmdline(context: Context, line: &str, chat_id: &mut ChatId) -> Resu
println!("{} images or videos: ", images.len()); println!("{} images or videos: ", images.len());
for (i, data) in images.iter().enumerate() { for (i, data) in images.iter().enumerate() {
if 0 == i { if 0 == i {
print!("{}", data); print!("{data}");
} else { } else {
print!(", {}", data); print!(", {data}");
} }
} }
println!(); println!();
@@ -1073,12 +1071,12 @@ pub async fn cmdline(context: Context, line: &str, chat_id: &mut ChatId) -> Resu
ensure!(!arg1.is_empty(), "Argument <msg-id> missing."); ensure!(!arg1.is_empty(), "Argument <msg-id> missing.");
let id = MsgId::new(arg1.parse()?); let id = MsgId::new(arg1.parse()?);
let res = message::get_msg_info(&context, id).await?; let res = message::get_msg_info(&context, id).await?;
println!("{}", res); println!("{res}");
} }
"download" => { "download" => {
ensure!(!arg1.is_empty(), "Argument <msg-id> missing."); ensure!(!arg1.is_empty(), "Argument <msg-id> missing.");
let id = MsgId::new(arg1.parse()?); let id = MsgId::new(arg1.parse()?);
println!("Scheduling download for {:?}", id); println!("Scheduling download for {id:?}");
id.download_full(&context).await?; id.download_full(&context).await?;
} }
"html" => { "html" => {
@@ -1089,7 +1087,7 @@ pub async fn cmdline(context: Context, line: &str, chat_id: &mut ChatId) -> Resu
.join(format!("msg-{}.html", id.to_u32())); .join(format!("msg-{}.html", id.to_u32()));
let html = id.get_html(&context).await?.unwrap_or_default(); let html = id.get_html(&context).await?.unwrap_or_default();
fs::write(&file, html).await?; fs::write(&file, html).await?;
println!("HTML written to: {:#?}", file); println!("HTML written to: {file:#?}");
} }
"listfresh" => { "listfresh" => {
let msglist = context.get_fresh_msgs().await?; let msglist = context.get_fresh_msgs().await?;
@@ -1151,7 +1149,7 @@ pub async fn cmdline(context: Context, line: &str, chat_id: &mut ChatId) -> Resu
ensure!(!arg1.is_empty(), "Arguments [<name>] <addr> expected."); ensure!(!arg1.is_empty(), "Arguments [<name>] <addr> expected.");
if !arg2.is_empty() { if !arg2.is_empty() {
let book = format!("{}\n{}", arg1, arg2); let book = format!("{arg1}\n{arg2}");
Contact::add_address_book(&context, &book).await?; Contact::add_address_book(&context, &book).await?;
} else { } else {
Contact::create(&context, "", arg1).await?; Contact::create(&context, "", arg1).await?;
@@ -1178,10 +1176,7 @@ pub async fn cmdline(context: Context, line: &str, chat_id: &mut ChatId) -> Resu
let chatlist = Chatlist::try_load(&context, 0, None, Some(contact_id)).await?; let chatlist = Chatlist::try_load(&context, 0, None, Some(contact_id)).await?;
let chatlist_cnt = chatlist.len(); let chatlist_cnt = chatlist.len();
if chatlist_cnt > 0 { if chatlist_cnt > 0 {
res += &format!( res += &format!("\n\n{chatlist_cnt} chats shared with Contact#{contact_id}: ",);
"\n\n{} chats shared with Contact#{}: ",
chatlist_cnt, contact_id,
);
for i in 0..chatlist_cnt { for i in 0..chatlist_cnt {
if 0 != i { if 0 != i {
res += ", "; res += ", ";
@@ -1191,7 +1186,7 @@ pub async fn cmdline(context: Context, line: &str, chat_id: &mut ChatId) -> Resu
} }
} }
println!("{}", res); println!("{res}");
} }
"delcontact" => { "delcontact" => {
ensure!(!arg1.is_empty(), "Argument <contact-id> missing."); ensure!(!arg1.is_empty(), "Argument <contact-id> missing.");
@@ -1215,13 +1210,13 @@ pub async fn cmdline(context: Context, line: &str, chat_id: &mut ChatId) -> Resu
"checkqr" => { "checkqr" => {
ensure!(!arg1.is_empty(), "Argument <qr-content> missing."); ensure!(!arg1.is_empty(), "Argument <qr-content> missing.");
let qr = check_qr(&context, arg1).await?; let qr = check_qr(&context, arg1).await?;
println!("qr={:?}", qr); println!("qr={qr:?}");
} }
"setqr" => { "setqr" => {
ensure!(!arg1.is_empty(), "Argument <qr-content> missing."); ensure!(!arg1.is_empty(), "Argument <qr-content> missing.");
match set_config_from_qr(&context, arg1).await { match set_config_from_qr(&context, arg1).await {
Ok(()) => println!("Config set from QR code, you can now call 'configure'"), Ok(()) => println!("Config set from QR code, you can now call 'configure'"),
Err(err) => println!("Cannot set config from QR code: {:?}", err), Err(err) => println!("Cannot set config from QR code: {err:?}"),
} }
} }
"providerinfo" => { "providerinfo" => {
@@ -1231,7 +1226,7 @@ pub async fn cmdline(context: Context, line: &str, chat_id: &mut ChatId) -> Resu
.await?; .await?;
match provider::get_provider_info(&context, arg1, socks5_enabled).await { match provider::get_provider_info(&context, arg1, socks5_enabled).await {
Some(info) => { Some(info) => {
println!("Information for provider belonging to {}:", arg1); println!("Information for provider belonging to {arg1}:");
println!("status: {}", info.status as u32); println!("status: {}", info.status as u32);
println!("before_login_hint: {}", info.before_login_hint); println!("before_login_hint: {}", info.before_login_hint);
println!("after_login_hint: {}", info.after_login_hint); println!("after_login_hint: {}", info.after_login_hint);
@@ -1241,7 +1236,7 @@ pub async fn cmdline(context: Context, line: &str, chat_id: &mut ChatId) -> Resu
} }
} }
None => { None => {
println!("No information for provider belonging to {} found.", arg1); println!("No information for provider belonging to {arg1} found.");
} }
} }
} }
@@ -1250,7 +1245,7 @@ pub async fn cmdline(context: Context, line: &str, chat_id: &mut ChatId) -> Resu
if let Ok(buf) = read_file(&context, &arg1).await { if let Ok(buf) = read_file(&context, &arg1).await {
let (width, height) = get_filemeta(&buf)?; let (width, height) = get_filemeta(&buf)?;
println!("width={}, height={}", width, height); println!("width={width}, height={height}");
} else { } else {
bail!("Command failed."); bail!("Command failed.");
} }
@@ -1261,8 +1256,7 @@ pub async fn cmdline(context: Context, line: &str, chat_id: &mut ChatId) -> Resu
let device_cnt = message::estimate_deletion_cnt(&context, false, seconds).await?; let device_cnt = message::estimate_deletion_cnt(&context, false, seconds).await?;
let server_cnt = message::estimate_deletion_cnt(&context, true, seconds).await?; let server_cnt = message::estimate_deletion_cnt(&context, true, seconds).await?;
println!( println!(
"estimated count of messages older than {} seconds:\non device: {}\non server: {}", "estimated count of messages older than {seconds} seconds:\non device: {device_cnt}\non server: {server_cnt}"
seconds, device_cnt, server_cnt
); );
} }
"" => (), "" => (),

View File

@@ -1,4 +1,3 @@
#![allow(clippy::uninlined_format_args)]
//! This is a CLI program and a little testing frame. This file must not be //! This is a CLI program and a little testing frame. This file must not be
//! included when using Delta Chat Core as a library. //! included when using Delta Chat Core as a library.
//! //!
@@ -68,8 +67,7 @@ fn receive_event(event: EventType) {
info!( info!(
"{}", "{}",
yellow.paint(format!( yellow.paint(format!(
"Received MSGS_CHANGED(chat_id={}, msg_id={})", "Received MSGS_CHANGED(chat_id={chat_id}, msg_id={msg_id})",
chat_id, msg_id,
)) ))
); );
} }
@@ -81,8 +79,7 @@ fn receive_event(event: EventType) {
info!( info!(
"{}", "{}",
yellow.paint(format!( yellow.paint(format!(
"Received REACTIONS_CHANGED(chat_id={}, msg_id={}, contact_id={})", "Received REACTIONS_CHANGED(chat_id={chat_id}, msg_id={msg_id}, contact_id={contact_id})"
chat_id, msg_id, contact_id
)) ))
); );
} }
@@ -92,7 +89,7 @@ fn receive_event(event: EventType) {
EventType::LocationChanged(contact) => { EventType::LocationChanged(contact) => {
info!( info!(
"{}", "{}",
yellow.paint(format!("Received LOCATION_CHANGED(contact={:?})", contact)) yellow.paint(format!("Received LOCATION_CHANGED(contact={contact:?})"))
); );
} }
EventType::ConfigureProgress { progress, comment } => { EventType::ConfigureProgress { progress, comment } => {
@@ -100,21 +97,20 @@ fn receive_event(event: EventType) {
info!( info!(
"{}", "{}",
yellow.paint(format!( yellow.paint(format!(
"Received CONFIGURE_PROGRESS({} ‰, {})", "Received CONFIGURE_PROGRESS({progress} ‰, {comment})"
progress, comment
)) ))
); );
} else { } else {
info!( info!(
"{}", "{}",
yellow.paint(format!("Received CONFIGURE_PROGRESS({} ‰)", progress)) yellow.paint(format!("Received CONFIGURE_PROGRESS({progress} ‰)"))
); );
} }
} }
EventType::ImexProgress(progress) => { EventType::ImexProgress(progress) => {
info!( info!(
"{}", "{}",
yellow.paint(format!("Received IMEX_PROGRESS({} ‰)", progress)) yellow.paint(format!("Received IMEX_PROGRESS({progress} ‰)"))
); );
} }
EventType::ImexFileWritten(file) => { EventType::ImexFileWritten(file) => {
@@ -126,7 +122,7 @@ fn receive_event(event: EventType) {
EventType::ChatModified(chat) => { EventType::ChatModified(chat) => {
info!( info!(
"{}", "{}",
yellow.paint(format!("Received CHAT_MODIFIED({})", chat)) yellow.paint(format!("Received CHAT_MODIFIED({chat})"))
); );
} }
_ => { _ => {
@@ -363,7 +359,7 @@ async fn start(args: Vec<String>) -> Result<(), Error> {
false false
} }
Err(err) => { Err(err) => {
println!("Error: {}", err); println!("Error: {err}");
true true
} }
} }
@@ -378,7 +374,7 @@ async fn start(args: Vec<String>) -> Result<(), Error> {
break; break;
} }
Err(err) => { Err(err) => {
println!("Error: {}", err); println!("Error: {err}");
break; break;
} }
} }
@@ -445,7 +441,7 @@ async fn handle_cmd(
if arg0 == "getbadqr" && qr.len() > 40 { if arg0 == "getbadqr" && qr.len() > 40 {
qr.replace_range(12..22, "0000000000") qr.replace_range(12..22, "0000000000")
} }
println!("{}", qr); println!("{qr}");
let output = Command::new("qrencode") let output = Command::new("qrencode")
.args(["-t", "ansiutf8", qr.as_str(), "-o", "-"]) .args(["-t", "ansiutf8", qr.as_str(), "-o", "-"])
.output() .output()
@@ -461,7 +457,7 @@ async fn handle_cmd(
match get_securejoin_qr_svg(&ctx, group).await { match get_securejoin_qr_svg(&ctx, group).await {
Ok(svg) => { Ok(svg) => {
fs::write(&file, svg).await?; fs::write(&file, svg).await?;
println!("QR code svg written to: {:#?}", file); println!("QR code svg written to: {file:#?}");
} }
Err(err) => { Err(err) => {
bail!("Failed to get QR code svg: {}", err); bail!("Failed to get QR code svg: {}", err);

View File

@@ -1,4 +1,3 @@
#![allow(clippy::uninlined_format_args)]
use deltachat::chat::{self, ChatId}; use deltachat::chat::{self, ChatId};
use deltachat::chatlist::*; use deltachat::chatlist::*;
use deltachat::config; use deltachat::config;
@@ -75,7 +74,7 @@ async fn main() {
for i in 0..1 { for i in 0..1 {
log::info!("sending message {}", i); log::info!("sending message {}", i);
chat::send_text_msg(&ctx, chat_id, format!("Hi, here is my {}nth message!", i)) chat::send_text_msg(&ctx, chat_id, format!("Hi, here is my {i}nth message!"))
.await .await
.unwrap(); .unwrap();
} }

View File

@@ -143,7 +143,7 @@ impl Accounts {
let ctx = self let ctx = self
.accounts .accounts
.remove(&id) .remove(&id)
.with_context(|| format!("no account with id {}", id))?; .with_context(|| format!("no account with id {id}"))?;
ctx.stop_io().await; ctx.stop_io().await;
drop(ctx); drop(ctx);

View File

@@ -90,7 +90,7 @@ impl fmt::Display for Aheader {
res res
}, },
); );
write!(fmt, " keydata={}", keydata) write!(fmt, " keydata={keydata}")
} }
} }
@@ -152,11 +152,8 @@ mod tests {
#[test] #[test]
fn test_from_str() -> Result<()> { fn test_from_str() -> Result<()> {
let h: Aheader = format!( let h: Aheader =
"addr=me@mail.com; prefer-encrypt=mutual; keydata={}", format!("addr=me@mail.com; prefer-encrypt=mutual; keydata={RAWKEY}").parse()?;
RAWKEY
)
.parse()?;
assert_eq!(h.addr, "me@mail.com"); assert_eq!(h.addr, "me@mail.com");
assert_eq!(h.prefer_encrypt, EncryptPreference::Mutual); assert_eq!(h.prefer_encrypt, EncryptPreference::Mutual);
@@ -166,10 +163,7 @@ mod tests {
// EncryptPreference::Reset is an internal value, parser should never return it // EncryptPreference::Reset is an internal value, parser should never return it
#[test] #[test]
fn test_from_str_reset() -> Result<()> { fn test_from_str_reset() -> Result<()> {
let raw = format!( let raw = format!("addr=reset@example.com; prefer-encrypt=reset; keydata={RAWKEY}");
"addr=reset@example.com; prefer-encrypt=reset; keydata={}",
RAWKEY
);
let h: Aheader = raw.parse()?; let h: Aheader = raw.parse()?;
assert_eq!(h.addr, "reset@example.com"); assert_eq!(h.addr, "reset@example.com");
@@ -179,7 +173,7 @@ mod tests {
#[test] #[test]
fn test_from_str_non_critical() -> Result<()> { fn test_from_str_non_critical() -> Result<()> {
let raw = format!("addr=me@mail.com; _foo=one; _bar=two; keydata={}", RAWKEY); let raw = format!("addr=me@mail.com; _foo=one; _bar=two; keydata={RAWKEY}");
let h: Aheader = raw.parse()?; let h: Aheader = raw.parse()?;
assert_eq!(h.addr, "me@mail.com"); assert_eq!(h.addr, "me@mail.com");
@@ -189,10 +183,7 @@ mod tests {
#[test] #[test]
fn test_from_str_superflous_critical() { fn test_from_str_superflous_critical() {
let raw = format!( let raw = format!("addr=me@mail.com; _foo=one; _bar=two; other=me; keydata={RAWKEY}");
"addr=me@mail.com; _foo=one; _bar=two; other=me; keydata={}",
RAWKEY
);
assert!(raw.parse::<Aheader>().is_err()); assert!(raw.parse::<Aheader>().is_err());
} }
@@ -226,21 +217,20 @@ mod tests {
let ah = Aheader::from_str(fixed_header)?; let ah = Aheader::from_str(fixed_header)?;
assert_eq!(ah.addr, "a@b.example.org"); assert_eq!(ah.addr, "a@b.example.org");
assert_eq!(ah.prefer_encrypt, EncryptPreference::Mutual); assert_eq!(ah.prefer_encrypt, EncryptPreference::Mutual);
assert_eq!(format!("{}", ah), fixed_header); assert_eq!(format!("{ah}"), fixed_header);
let rendered = ah.to_string(); let rendered = ah.to_string();
assert_eq!(rendered, fixed_header); assert_eq!(rendered, fixed_header);
let ah = Aheader::from_str(&format!(" _foo; __FOO=BAR ;;; addr = a@b.example.org ;\r\n prefer-encrypt = mutual ; keydata = {}", RAWKEY))?; let ah = Aheader::from_str(&format!(" _foo; __FOO=BAR ;;; addr = a@b.example.org ;\r\n prefer-encrypt = mutual ; keydata = {RAWKEY}"))?;
assert_eq!(ah.addr, "a@b.example.org"); assert_eq!(ah.addr, "a@b.example.org");
assert_eq!(ah.prefer_encrypt, EncryptPreference::Mutual); assert_eq!(ah.prefer_encrypt, EncryptPreference::Mutual);
Aheader::from_str(&format!( Aheader::from_str(&format!(
"addr=a@b.example.org; prefer-encrypt=ignoreUnknownValues; keydata={}", "addr=a@b.example.org; prefer-encrypt=ignoreUnknownValues; keydata={RAWKEY}"
RAWKEY
))?; ))?;
Aheader::from_str(&format!("addr=a@b.example.org; keydata={}", RAWKEY))?; Aheader::from_str(&format!("addr=a@b.example.org; keydata={RAWKEY}"))?;
Ok(()) Ok(())
} }

View File

@@ -59,7 +59,7 @@ impl<'a> BlobObject<'a> {
let blob = BlobObject { let blob = BlobObject {
blobdir, blobdir,
name: format!("$BLOBDIR/{}", name), name: format!("$BLOBDIR/{name}"),
}; };
context.emit_event(EventType::NewBlobFile(blob.as_name().to_string())); context.emit_event(EventType::NewBlobFile(blob.as_name().to_string()));
Ok(blob) Ok(blob)
@@ -74,7 +74,7 @@ impl<'a> BlobObject<'a> {
) -> Result<(String, fs::File)> { ) -> Result<(String, fs::File)> {
const MAX_ATTEMPT: u32 = 16; const MAX_ATTEMPT: u32 = 16;
let mut attempt = 0; let mut attempt = 0;
let mut name = format!("{}{}", stem, ext); let mut name = format!("{stem}{ext}");
loop { loop {
attempt += 1; attempt += 1;
let path = dir.join(&name); let path = dir.join(&name);
@@ -124,7 +124,7 @@ impl<'a> BlobObject<'a> {
let blob = BlobObject { let blob = BlobObject {
blobdir: context.get_blobdir(), blobdir: context.get_blobdir(),
name: format!("$BLOBDIR/{}", name), name: format!("$BLOBDIR/{name}"),
}; };
context.emit_event(EventType::NewBlobFile(blob.as_name().to_string())); context.emit_event(EventType::NewBlobFile(blob.as_name().to_string()));
Ok(blob) Ok(blob)
@@ -184,7 +184,7 @@ impl<'a> BlobObject<'a> {
} }
Ok(BlobObject { Ok(BlobObject {
blobdir: context.get_blobdir(), blobdir: context.get_blobdir(),
name: format!("$BLOBDIR/{}", name), name: format!("$BLOBDIR/{name}"),
}) })
} }
@@ -285,7 +285,7 @@ impl<'a> BlobObject<'a> {
if ext.is_empty() { if ext.is_empty() {
(stem, "".to_string()) (stem, "".to_string())
} else { } else {
(stem, format!(".{}", ext).to_lowercase()) (stem, format!(".{ext}").to_lowercase())
// Return ("file", ".d_point_and_double_ending.tar.gz") // Return ("file", ".d_point_and_double_ending.tar.gz")
// which is not perfect but acceptable. // which is not perfect but acceptable.
} }
@@ -428,7 +428,7 @@ impl<'a> BlobObject<'a> {
blob_abs = blob_abs.with_extension("jpg"); blob_abs = blob_abs.with_extension("jpg");
let file_name = blob_abs.file_name().context("No avatar file name (???)")?; let file_name = blob_abs.file_name().context("No avatar file name (???)")?;
let file_name = file_name.to_str().context("Filename is no UTF-8 (???)")?; let file_name = file_name.to_str().context("Filename is no UTF-8 (???)")?;
changed_name = Some(format!("$BLOBDIR/{}", file_name)); changed_name = Some(format!("$BLOBDIR/{file_name}"));
} }
if encoded.is_empty() { if encoded.is_empty() {
@@ -596,7 +596,7 @@ mod tests {
assert_eq!(fs::read(&foo_path).await.unwrap(), b"hello"); assert_eq!(fs::read(&foo_path).await.unwrap(), b"hello");
} else { } else {
let name = fname.to_str().unwrap(); let name = fname.to_str().unwrap();
println!("{}", name); println!("{name}");
assert!(name.starts_with("foo")); assert!(name.starts_with("foo"));
assert!(name.ends_with(".tar.gz")); assert!(name.ends_with(".tar.gz"));
} }

View File

@@ -908,11 +908,10 @@ impl ChatId {
{ {
let sql = &context.sql; let sql = &context.sql;
let query = format!( let query = format!(
"SELECT {} \ "SELECT {fields} \
FROM msgs WHERE chat_id=? AND state NOT IN (?, ?, ?, ?) AND NOT hidden \ FROM msgs WHERE chat_id=? AND state NOT IN (?, ?, ?, ?) AND NOT hidden \
ORDER BY timestamp DESC, id DESC \ ORDER BY timestamp DESC, id DESC \
LIMIT 1;", LIMIT 1;"
fields
); );
let row = sql let row = sql
.query_row_optional( .query_row_optional(
@@ -993,9 +992,9 @@ impl ChatId {
}) })
.map(|peerstate| peerstate.prefer_encrypt) .map(|peerstate| peerstate.prefer_encrypt)
{ {
Some(EncryptPreference::Mutual) => ret_mutual += &format!("{}\n", addr), Some(EncryptPreference::Mutual) => ret_mutual += &format!("{addr}\n"),
Some(EncryptPreference::NoPreference) => ret_nopreference += &format!("{}\n", addr), Some(EncryptPreference::NoPreference) => ret_nopreference += &format!("{addr}\n"),
Some(EncryptPreference::Reset) | None => ret_reset += &format!("{}\n", addr), Some(EncryptPreference::Reset) | None => ret_reset += &format!("{addr}\n"),
}; };
} }
@@ -1171,7 +1170,7 @@ impl Chat {
}, },
) )
.await .await
.context(format!("Failed loading chat {} from database", chat_id))?; .context(format!("Failed loading chat {chat_id} from database"))?;
if chat.id.is_archived_link() { if chat.id.is_archived_link() {
chat.name = stock_str::archived_chats(context).await; chat.name = stock_str::archived_chats(context).await;
@@ -1491,11 +1490,11 @@ impl Chat {
if !parent_references.is_empty() && !parent_rfc724_mid.is_empty() { if !parent_references.is_empty() && !parent_rfc724_mid.is_empty() {
// angle brackets are added by the mimefactory later // angle brackets are added by the mimefactory later
new_references = format!("{} {}", parent_references, parent_rfc724_mid); new_references = format!("{parent_references} {parent_rfc724_mid}");
} else if !parent_references.is_empty() { } else if !parent_references.is_empty() {
new_references = parent_references.to_string(); new_references = parent_references.to_string();
} else if !parent_in_reply_to.is_empty() && !parent_rfc724_mid.is_empty() { } else if !parent_in_reply_to.is_empty() && !parent_rfc724_mid.is_empty() {
new_references = format!("{} {}", parent_in_reply_to, parent_rfc724_mid); new_references = format!("{parent_in_reply_to} {parent_rfc724_mid}");
} else if !parent_in_reply_to.is_empty() { } else if !parent_in_reply_to.is_empty() {
new_references = parent_in_reply_to; new_references = parent_in_reply_to;
} else { } else {
@@ -2797,7 +2796,7 @@ async fn find_unused_broadcast_list_name(context: &Context) -> Result<String> {
let base_name = stock_str::broadcast_list(context).await; let base_name = stock_str::broadcast_list(context).await;
for attempt in 1..1000 { for attempt in 1..1000 {
let better_name = if attempt > 1 { let better_name = if attempt > 1 {
format!("{} {}", base_name, attempt) format!("{base_name} {attempt}")
} else { } else {
base_name.clone() base_name.clone()
}; };
@@ -3065,7 +3064,7 @@ pub async fn set_muted(context: &Context, chat_id: ChatId, duration: MuteDuratio
paramsv![duration, chat_id], paramsv![duration, chat_id],
) )
.await .await
.context(format!("Failed to set mute duration for {}", chat_id))?; .context(format!("Failed to set mute duration for {chat_id}"))?;
context.emit_event(EventType::ChatModified(chat_id)); context.emit_event(EventType::ChatModified(chat_id));
Ok(()) Ok(())
} }
@@ -4498,12 +4497,11 @@ mod tests {
format!( format!(
"From: bob@example.net\n\ "From: bob@example.net\n\
To: alice@example.org\n\ To: alice@example.org\n\
Message-ID: <{}@example.org>\n\ Message-ID: <{num}@example.org>\n\
Chat-Version: 1.0\n\ Chat-Version: 1.0\n\
Date: Sun, 22 Mar 2022 19:37:57 +0000\n\ Date: Sun, 22 Mar 2022 19:37:57 +0000\n\
\n\ \n\
hello\n", hello\n"
num
) )
.as_bytes(), .as_bytes(),
false, false,
@@ -4579,14 +4577,13 @@ mod tests {
receive_imf( receive_imf(
t, t,
format!( format!(
"From: {}@example.net\n\ "From: {name}@example.net\n\
To: alice@example.org\n\ To: alice@example.org\n\
Message-ID: <{}@example.org>\n\ Message-ID: <{num}@example.org>\n\
Chat-Version: 1.0\n\ Chat-Version: 1.0\n\
Date: Sun, 22 Mar 2022 19:37:57 +0000\n\ Date: Sun, 22 Mar 2022 19:37:57 +0000\n\
\n\ \n\
hello\n", hello\n"
name, num
) )
.as_bytes(), .as_bytes(),
false, false,
@@ -4793,7 +4790,7 @@ mod tests {
let chat_id = ChatId::create_for_contact(&context.ctx, contact1) let chat_id = ChatId::create_for_contact(&context.ctx, contact1)
.await .await
.unwrap(); .unwrap();
assert!(!chat_id.is_special(), "chat_id too small {}", chat_id); assert!(!chat_id.is_special(), "chat_id too small {chat_id}");
let chat = Chat::load_from_db(&context.ctx, chat_id).await.unwrap(); let chat = Chat::load_from_db(&context.ctx, chat_id).await.unwrap();
let chat2_id = ChatId::create_for_contact(&context.ctx, contact1) let chat2_id = ChatId::create_for_contact(&context.ctx, contact1)

View File

@@ -179,7 +179,7 @@ impl Chatlist {
warn!(context, "cannot update special chat names: {:?}", err) warn!(context, "cannot update special chat names: {:?}", err)
} }
let str_like_cmd = format!("%{}%", query); let str_like_cmd = format!("%{query}%");
context context
.sql .sql
.query_map( .query_map(

View File

@@ -36,7 +36,7 @@ pub(crate) fn str_to_color(s: &str) -> u32 {
} }
pub fn color_int_to_hex_string(color: u32) -> String { pub fn color_int_to_hex_string(color: u32) -> String {
format!("{:#08x}", color).replace("0x", "#") format!("{color:#08x}").replace("0x", "#")
} }
#[cfg(test)] #[cfg(test)]

View File

@@ -277,7 +277,7 @@ impl Context {
rel_path.map(|p| get_abs_path(self, p).to_string_lossy().into_owned()) rel_path.map(|p| get_abs_path(self, p).to_string_lossy().into_owned())
} }
Config::SysVersion => Some((*DC_VERSION_STR).clone()), Config::SysVersion => Some((*DC_VERSION_STR).clone()),
Config::SysMsgsizeMaxRecommended => Some(format!("{}", RECOMMENDED_FILE_SIZE)), Config::SysMsgsizeMaxRecommended => Some(format!("{RECOMMENDED_FILE_SIZE}")),
Config::SysConfigKeys => Some(get_config_keys_string()), Config::SysConfigKeys => Some(get_config_keys_string()),
_ => self.sql.get_raw_config(key.as_ref()).await?, _ => self.sql.get_raw_config(key.as_ref()).await?,
}; };
@@ -505,7 +505,7 @@ fn get_config_keys_string() -> String {
acc acc
}); });
format!(" {} ", keys) format!(" {keys} ")
} }
#[cfg(test)] #[cfg(test)]

View File

@@ -87,7 +87,7 @@ impl Context {
self, self,
// We are using Anyhow's .context() and to show the // We are using Anyhow's .context() and to show the
// inner error, too, we need the {:#}: // inner error, too, we need the {:#}:
&format!("{:#}", err), &format!("{err:#}"),
) )
.await .await
) )
@@ -492,8 +492,7 @@ async fn get_autoconfig(
if let Ok(res) = moz_autoconfigure( if let Ok(res) = moz_autoconfigure(
ctx, ctx,
&format!( &format!(
"https://autoconfig.{}/mail/config-v1.1.xml?emailaddress={}", "https://autoconfig.{param_domain}/mail/config-v1.1.xml?emailaddress={param_addr_urlencoded}"
param_domain, param_addr_urlencoded
), ),
param, param,
) )
@@ -586,7 +585,7 @@ async fn try_imap_one_param(
info!(context, "failure: {:#}", err); info!(context, "failure: {:#}", err);
return Err(ConfigurationError { return Err(ConfigurationError {
config: inf, config: inf,
msg: format!("{:#}", err), msg: format!("{err:#}"),
}); });
} }
Ok(imap) => imap, Ok(imap) => imap,
@@ -597,7 +596,7 @@ async fn try_imap_one_param(
info!(context, "failure: {:#}", err); info!(context, "failure: {:#}", err);
Err(ConfigurationError { Err(ConfigurationError {
config: inf, config: inf,
msg: format!("{:#}", err), msg: format!("{err:#}"),
}) })
} }
Ok(()) => { Ok(()) => {
@@ -638,7 +637,7 @@ async fn try_smtp_one_param(
info!(context, "failure: {}", err); info!(context, "failure: {}", err);
Err(ConfigurationError { Err(ConfigurationError {
config: inf, config: inf,
msg: format!("{:#}", err), msg: format!("{err:#}"),
}) })
} else { } else {
info!(context, "success: {}", inf); info!(context, "success: {}", inf);

View File

@@ -961,7 +961,7 @@ impl Contact {
}; };
let finger_prints = stock_str::finger_prints(context).await; let finger_prints = stock_str::finger_prints(context).await;
ret += &format!("{}.\n{}:", stock_message, finger_prints); ret += &format!("{stock_message}.\n{finger_prints}:");
let fingerprint_self = SignedPublicKey::load_self(context) let fingerprint_self = SignedPublicKey::load_self(context)
.await? .await?
@@ -1499,7 +1499,7 @@ fn cat_fingerprint(
&& !fingerprint_unverified.is_empty() && !fingerprint_unverified.is_empty()
&& fingerprint_verified != fingerprint_unverified && fingerprint_verified != fingerprint_unverified
{ {
*ret += &format!("\n\n{} (alternative):\n{}", addr, fingerprint_unverified); *ret += &format!("\n\n{addr} (alternative):\n{fingerprint_unverified}");
} }
} }

View File

@@ -601,7 +601,7 @@ impl Context {
.await?; .await?;
let fingerprint_str = match SignedPublicKey::load_self(self).await { let fingerprint_str = match SignedPublicKey::load_self(self).await {
Ok(key) => key.fingerprint().hex(), Ok(key) => key.fingerprint().hex(),
Err(err) => format!("<key failure: {}>", err), Err(err) => format!("<key failure: {err}>"),
}; };
let sentbox_watch = self.get_config_int(Config::SentboxWatch).await?; let sentbox_watch = self.get_config_int(Config::SentboxWatch).await?;
@@ -658,7 +658,7 @@ impl Context {
res.insert("used_account_settings", l2.to_string()); res.insert("used_account_settings", l2.to_string());
if let Some(server_id) = &*self.server_id.read().await { if let Some(server_id) = &*self.server_id.read().await {
res.insert("imap_server_id", format!("{:?}", server_id)); res.insert("imap_server_id", format!("{server_id:?}"));
} }
res.insert("secondary_addrs", secondary_addrs); res.insert("secondary_addrs", secondary_addrs);
@@ -808,7 +808,7 @@ impl Context {
if real_query.is_empty() { if real_query.is_empty() {
return Ok(Vec::new()); return Ok(Vec::new());
} }
let str_like_in_text = format!("%{}%", real_query); let str_like_in_text = format!("%{real_query}%");
let do_query = |query, params| { let do_query = |query, params| {
self.sql.query_map( self.sql.query_map(
@@ -964,7 +964,7 @@ mod tests {
contact.get_addr(), contact.get_addr(),
create_outgoing_rfc724_mid(None, contact.get_addr()) create_outgoing_rfc724_mid(None, contact.get_addr())
); );
println!("{}", msg); println!("{msg}");
receive_imf(t, msg.as_bytes(), false).await.unwrap(); receive_imf(t, msg.as_bytes(), false).await.unwrap();
} }
@@ -1191,8 +1191,7 @@ mod tests {
{ {
assert!( assert!(
info.contains_key(&*key), info.contains_key(&*key),
"'{}' missing in get_info() output", "'{key}' missing in get_info() output"
key
); );
} }
} }

View File

@@ -45,7 +45,7 @@ pub async fn debug_logging_loop(context: &Context, events: Receiver<DebugEventLo
.await .await
{ {
Err(err) => { Err(err) => {
eprintln!("Can't log event to webxdc status update: {:#}", err); eprintln!("Can't log event to webxdc status update: {err:#}");
} }
Ok(serial) => { Ok(serial) => {
context.events.emit(Event { context.events.emit(Event {

View File

@@ -407,7 +407,7 @@ mod tests {
async fn test_quote_div() { async fn test_quote_div() {
let input = include_str!("../test-data/message/gmx-quote-body.eml"); let input = include_str!("../test-data/message/gmx-quote-body.eml");
let dehtml = dehtml(input).unwrap(); let dehtml = dehtml(input).unwrap();
println!("{}", dehtml); println!("{dehtml}");
let SimplifiedText { let SimplifiedText {
text, text,
is_forwarded, is_forwarded,

View File

@@ -246,7 +246,7 @@ impl MimeMessage {
time() + max(delete_server_after, MIN_DELETE_SERVER_AFTER), time() + max(delete_server_after, MIN_DELETE_SERVER_AFTER),
) )
.await; .await;
text += format!(" [{}]", until).as_str(); text += format!(" [{until}]").as_str();
}; };
info!(context, "Partial download: {}", text); info!(context, "Partial download: {}", text);
@@ -370,7 +370,7 @@ mod tests {
receive_imf_inner( receive_imf_inner(
&t, &t,
"Mr.12345678901@example.com", "Mr.12345678901@example.com",
format!("{}\n\n100k text...", header).as_bytes(), format!("{header}\n\n100k text...").as_bytes(),
false, false,
None, None,
false, false,

View File

@@ -78,7 +78,7 @@ impl EncryptHelper {
}; };
} }
None => { None => {
let msg = format!("peerstate for {:?} missing, cannot encrypt", addr); let msg = format!("peerstate for {addr:?} missing, cannot encrypt");
if e2ee_guaranteed { if e2ee_guaranteed {
return Err(format_err!("{}", msg)); return Err(format_err!("{}", msg));
} else { } else {
@@ -112,7 +112,7 @@ impl EncryptHelper {
{ {
let key = peerstate let key = peerstate
.take_key(min_verified) .take_key(min_verified)
.with_context(|| format!("proper enc-key for {} missing, cannot encrypt", addr))?; .with_context(|| format!("proper enc-key for {addr} missing, cannot encrypt"))?;
keyring.add(key); keyring.add(key);
} }
keyring.add(self.public_key.clone()); keyring.add(self.public_key.clone());

View File

@@ -1099,7 +1099,7 @@ mod tests {
.query_get_value("SELECT txt_raw FROM msgs WHERE id=?;", paramsv![msg_id]) .query_get_value("SELECT txt_raw FROM msgs WHERE id=?;", paramsv![msg_id])
.await .await
.unwrap(); .unwrap();
assert!(rawtxt.is_none_or_empty(), "{:?}", rawtxt); assert!(rawtxt.is_none_or_empty(), "{rawtxt:?}");
} }
} }

View File

@@ -207,7 +207,7 @@ impl HtmlMsgParser {
self.html = re self.html = re
.replace_all( .replace_all(
&self.html, &self.html,
format!("${{1}}{}${{3}}", replacement).as_str(), format!("${{1}}{replacement}${{3}}").as_str(),
) )
.as_ref() .as_ref()
.to_string() .to_string()
@@ -561,7 +561,7 @@ test some special html-characters as &lt; &gt; and &amp; but also &quot; and &#x
assert!(msg.text.as_ref().unwrap().contains("foo bar ä ö ü ß")); assert!(msg.text.as_ref().unwrap().contains("foo bar ä ö ü ß"));
assert!(msg.has_html()); assert!(msg.has_html());
let html = msg.get_id().get_html(&t).await?.unwrap(); let html = msg.get_id().get_html(&t).await?.unwrap();
println!("{}", html); println!("{html}");
assert!(html.contains("foo bar ä ö ü ß")); assert!(html.contains("foo bar ä ö ü ß"));
Ok(()) Ok(())
} }

View File

@@ -505,7 +505,7 @@ impl Imap {
let mut list = session let mut list = session
.uid_fetch("1:*", RFC724MID_UID) .uid_fetch("1:*", RFC724MID_UID)
.await .await
.with_context(|| format!("can't resync folder {}", folder))?; .with_context(|| format!("can't resync folder {folder}"))?;
while let Some(fetch) = list.next().await { while let Some(fetch) = list.next().await {
let msg = fetch?; let msg = fetch?;
@@ -564,22 +564,22 @@ impl Imap {
let newly_selected = session let newly_selected = session
.select_or_create_folder(context, folder) .select_or_create_folder(context, folder)
.await .await
.with_context(|| format!("failed to select or create folder {}", folder))?; .with_context(|| format!("failed to select or create folder {folder}"))?;
let mailbox = session let mailbox = session
.selected_mailbox .selected_mailbox
.as_mut() .as_mut()
.with_context(|| format!("No mailbox selected, folder: {}", folder))?; .with_context(|| format!("No mailbox selected, folder: {folder}"))?;
let new_uid_validity = mailbox let new_uid_validity = mailbox
.uid_validity .uid_validity
.with_context(|| format!("No UIDVALIDITY for folder {}", folder))?; .with_context(|| format!("No UIDVALIDITY for folder {folder}"))?;
let old_uid_validity = get_uidvalidity(context, folder) let old_uid_validity = get_uidvalidity(context, folder)
.await .await
.with_context(|| format!("failed to get old UID validity for folder {}", folder))?; .with_context(|| format!("failed to get old UID validity for folder {folder}"))?;
let old_uid_next = get_uid_next(context, folder) let old_uid_next = get_uid_next(context, folder)
.await .await
.with_context(|| format!("failed to get old UID NEXT for folder {}", folder))?; .with_context(|| format!("failed to get old UID NEXT for folder {folder}"))?;
if new_uid_validity == old_uid_validity { if new_uid_validity == old_uid_validity {
let new_emails = if newly_selected == NewlySelected::No { let new_emails = if newly_selected == NewlySelected::No {
@@ -694,7 +694,7 @@ impl Imap {
let new_emails = self let new_emails = self
.select_with_uidvalidity(context, folder) .select_with_uidvalidity(context, folder)
.await .await
.with_context(|| format!("failed to select folder {}", folder))?; .with_context(|| format!("failed to select folder {folder}"))?;
if !new_emails && !fetch_existing_msgs { if !new_emails && !fetch_existing_msgs {
info!(context, "No new emails in folder {}", folder); info!(context, "No new emails in folder {}", folder);
@@ -917,8 +917,7 @@ impl Session {
.context("cannot remove deleted messages from imap table")?; .context("cannot remove deleted messages from imap table")?;
context.emit_event(EventType::ImapMessageDeleted(format!( context.emit_event(EventType::ImapMessageDeleted(format!(
"IMAP messages {} marked as deleted", "IMAP messages {uid_set} marked as deleted"
uid_set
))); )));
Ok(()) Ok(())
} }
@@ -948,8 +947,7 @@ impl Session {
.await .await
.context("cannot delete moved messages from imap table")?; .context("cannot delete moved messages from imap table")?;
context.emit_event(EventType::ImapMessageMoved(format!( context.emit_event(EventType::ImapMessageMoved(format!(
"IMAP messages {} moved to {}", "IMAP messages {set} moved to {target}"
set, target
))); )));
return Ok(()); return Ok(());
} }
@@ -986,8 +984,7 @@ impl Session {
.await .await
.context("cannot plan deletion of copied messages")?; .context("cannot plan deletion of copied messages")?;
context.emit_event(EventType::ImapMessageMoved(format!( context.emit_event(EventType::ImapMessageMoved(format!(
"IMAP messages {} copied to {}", "IMAP messages {set} copied to {target}"
set, target
))); )));
Ok(()) Ok(())
} }
@@ -1111,7 +1108,7 @@ impl Imap {
let session = self let session = self
.session .session
.as_mut() .as_mut()
.with_context(|| format!("No IMAP connection established, folder: {}", folder))?; .with_context(|| format!("No IMAP connection established, folder: {folder}"))?;
if !session.can_condstore() { if !session.can_condstore() {
info!( info!(
@@ -1129,7 +1126,7 @@ impl Imap {
let mailbox = session let mailbox = session
.selected_mailbox .selected_mailbox
.as_ref() .as_ref()
.with_context(|| format!("No mailbox selected, folder: {}", folder))?; .with_context(|| format!("No mailbox selected, folder: {folder}"))?;
// Check if the mailbox supports MODSEQ. // Check if the mailbox supports MODSEQ.
// We are not interested in actual value of HIGHESTMODSEQ. // We are not interested in actual value of HIGHESTMODSEQ.
@@ -1144,12 +1141,12 @@ impl Imap {
let mut updated_chat_ids = BTreeSet::new(); let mut updated_chat_ids = BTreeSet::new();
let uid_validity = get_uidvalidity(context, folder) let uid_validity = get_uidvalidity(context, folder)
.await .await
.with_context(|| format!("failed to get UID validity for folder {}", folder))?; .with_context(|| format!("failed to get UID validity for folder {folder}"))?;
let mut highest_modseq = get_modseq(context, folder) let mut highest_modseq = get_modseq(context, folder)
.await .await
.with_context(|| format!("failed to get MODSEQ for folder {}", folder))?; .with_context(|| format!("failed to get MODSEQ for folder {folder}"))?;
let mut list = session let mut list = session
.uid_fetch("1:*", format!("(FLAGS) (CHANGEDSINCE {})", highest_modseq)) .uid_fetch("1:*", format!("(FLAGS) (CHANGEDSINCE {highest_modseq})"))
.await .await
.context("failed to fetch flags")?; .context("failed to fetch flags")?;
@@ -1166,7 +1163,7 @@ impl Imap {
if let Some(chat_id) = mark_seen_by_uid(context, folder, uid_validity, uid) if let Some(chat_id) = mark_seen_by_uid(context, folder, uid_validity, uid)
.await .await
.with_context(|| { .with_context(|| {
format!("failed to update seen status for msg {}/{}", folder, uid) format!("failed to update seen status for msg {folder}/{uid}")
})? })?
{ {
updated_chat_ids.insert(chat_id); updated_chat_ids.insert(chat_id);
@@ -1184,7 +1181,7 @@ impl Imap {
set_modseq(context, folder, highest_modseq) set_modseq(context, folder, highest_modseq)
.await .await
.with_context(|| format!("failed to set MODSEQ for folder {}", folder))?; .with_context(|| format!("failed to set MODSEQ for folder {folder}"))?;
for updated_chat_id in updated_chat_ids { for updated_chat_id in updated_chat_ids {
context.emit_event(EventType::MsgsNoticed(updated_chat_id)); context.emit_event(EventType::MsgsNoticed(updated_chat_id));
} }
@@ -1242,7 +1239,7 @@ impl Imap {
.context("no IMAP connection established")?; .context("no IMAP connection established")?;
// fetch messages with larger UID than the last one seen // fetch messages with larger UID than the last one seen
let set = format!("{}:*", uid_next); let set = format!("{uid_next}:*");
let mut list = session let mut list = session
.uid_fetch(set, PREFETCH_FLAGS) .uid_fetch(set, PREFETCH_FLAGS)
.await .await
@@ -1280,7 +1277,7 @@ impl Imap {
// Sequence numbers are sequential. If there are 1000 messages in the inbox, // Sequence numbers are sequential. If there are 1000 messages in the inbox,
// we can fetch the sequence numbers 900-1000 and get the last 100 messages. // we can fetch the sequence numbers 900-1000 and get the last 100 messages.
let first = cmp::max(1, exists - DC_FETCH_EXISTING_MSGS_COUNT); let first = cmp::max(1, exists - DC_FETCH_EXISTING_MSGS_COUNT);
let set = format!("{}:*", first); let set = format!("{first}:*");
let mut list = session let mut list = session
.fetch(&set, PREFETCH_FLAGS) .fetch(&set, PREFETCH_FLAGS)
.await .await
@@ -1499,11 +1496,11 @@ impl Session {
if flag == "\\Deleted" { if flag == "\\Deleted" {
self.selected_folder_needs_expunge = true; self.selected_folder_needs_expunge = true;
} }
let query = format!("+FLAGS ({})", flag); let query = format!("+FLAGS ({flag})");
let mut responses = self let mut responses = self
.uid_store(uid_set, &query) .uid_store(uid_set, &query)
.await .await
.with_context(|| format!("IMAP failed to store: ({}, {})", uid_set, query))?; .with_context(|| format!("IMAP failed to store: ({uid_set}, {query})"))?;
while let Some(_response) = responses.next().await { while let Some(_response) = responses.next().await {
// Read all the responses // Read all the responses
} }
@@ -1663,7 +1660,7 @@ impl Imap {
info!(context, "Using \"{}\" as folder-delimiter.", delimiter); info!(context, "Using \"{}\" as folder-delimiter.", delimiter);
let fallback_folder = format!("INBOX{}DeltaChat", delimiter); let fallback_folder = format!("INBOX{delimiter}DeltaChat");
let mvbox_folder = self let mvbox_folder = self
.configure_mvbox(context, &["DeltaChat", &fallback_folder], create_mvbox) .configure_mvbox(context, &["DeltaChat", &fallback_folder], create_mvbox)
.await .await
@@ -2109,12 +2106,7 @@ async fn mark_seen_by_uid(
}, },
) )
.await .await
.with_context(|| { .with_context(|| format!("failed to get msg and chat ID for IMAP message {folder}/{uid}"))?
format!(
"failed to get msg and chat ID for IMAP message {}/{}",
folder, uid
)
})?
{ {
let updated = context let updated = context
.sql .sql
@@ -2130,16 +2122,14 @@ async fn mark_seen_by_uid(
], ],
) )
.await .await
.with_context(|| format!("failed to update msg {} state", msg_id))? .with_context(|| format!("failed to update msg {msg_id} state"))?
> 0; > 0;
if updated { if updated {
msg_id msg_id
.start_ephemeral_timer(context) .start_ephemeral_timer(context)
.await .await
.with_context(|| { .with_context(|| format!("failed to start ephemeral timer for message {msg_id}"))?;
format!("failed to start ephemeral timer for message {}", msg_id)
})?;
Ok(Some(chat_id)) Ok(Some(chat_id))
} else { } else {
// Message state has not chnaged. // Message state has not chnaged.
@@ -2254,7 +2244,7 @@ pub(crate) async fn get_imap_self_sent_search_command(context: &Context) -> Resu
let mut search_command = format!("FROM \"{}\"", context.get_primary_self_addr().await?); let mut search_command = format!("FROM \"{}\"", context.get_primary_self_addr().await?);
for item in context.get_secondary_self_addrs().await? { for item in context.get_secondary_self_addrs().await? {
search_command = format!("OR ({}) (FROM \"{}\")", search_command, item); search_command = format!("OR ({search_command}) (FROM \"{item}\")");
} }
Ok(search_command) Ok(search_command)
@@ -2262,7 +2252,7 @@ pub(crate) async fn get_imap_self_sent_search_command(context: &Context) -> Resu
/// Deprecated, use get_uid_next() and get_uidvalidity() /// Deprecated, use get_uid_next() and get_uidvalidity()
pub async fn get_config_last_seen_uid(context: &Context, folder: &str) -> Result<(u32, u32)> { pub async fn get_config_last_seen_uid(context: &Context, folder: &str) -> Result<(u32, u32)> {
let key = format!("imap.mailbox.{}", folder); let key = format!("imap.mailbox.{folder}");
if let Some(entry) = context.sql.get_raw_config(&key).await? { if let Some(entry) = context.sql.get_raw_config(&key).await? {
// the entry has the format `imap.mailbox.<folder>=<uidvalidity>:<lastseenuid>` // the entry has the format `imap.mailbox.<folder>=<uidvalidity>:<lastseenuid>`
let mut parts = entry.split(':'); let mut parts = entry.split(':');
@@ -2367,7 +2357,7 @@ async fn add_all_recipients_as_contacts(
}; };
imap.select_with_uidvalidity(context, &mailbox) imap.select_with_uidvalidity(context, &mailbox)
.await .await
.with_context(|| format!("could not select {}", mailbox))?; .with_context(|| format!("could not select {mailbox}"))?;
let recipients = imap let recipients = imap
.get_all_recipients(context) .get_all_recipients(context)
@@ -2532,8 +2522,7 @@ mod tests {
outgoing: bool, outgoing: bool,
setupmessage: bool, setupmessage: bool,
) -> Result<()> { ) -> Result<()> {
println!("Testing: For folder {}, mvbox_move {}, chat_msg {}, accepted {}, outgoing {}, setupmessage {}", println!("Testing: For folder {folder}, mvbox_move {mvbox_move}, chat_msg {chat_msg}, accepted {accepted_chat}, outgoing {outgoing}, setupmessage {setupmessage}");
folder, mvbox_move, chat_msg, accepted_chat, outgoing, setupmessage);
let t = TestContext::new_alice().await; let t = TestContext::new_alice().await;
t.ctx t.ctx
@@ -2590,8 +2579,7 @@ mod tests {
} else { } else {
Some(expected_destination) Some(expected_destination)
}; };
assert_eq!(expected, actual.as_deref(), "For folder {}, mvbox_move {}, chat_msg {}, accepted {}, outgoing {}, setupmessage {}: expected {:?}, got {:?}", assert_eq!(expected, actual.as_deref(), "For folder {folder}, mvbox_move {mvbox_move}, chat_msg {chat_msg}, accepted {accepted_chat}, outgoing {outgoing}, setupmessage {setupmessage}: expected {expected:?}, got {actual:?}");
folder, mvbox_move, chat_msg, accepted_chat, outgoing, setupmessage, expected, actual);
Ok(()) Ok(())
} }

View File

@@ -99,8 +99,8 @@ impl Session {
let mut session = tokio::time::timeout(Duration::from_secs(15), handle.done()) let mut session = tokio::time::timeout(Duration::from_secs(15), handle.done())
.await .await
.with_context(|| format!("{}: IMAP IDLE protocol timed out", folder_name))? .with_context(|| format!("{folder_name}: IMAP IDLE protocol timed out"))?
.with_context(|| format!("{}: IMAP IDLE failed", folder_name))?; .with_context(|| format!("{folder_name}: IMAP IDLE failed"))?;
session.as_mut().set_read_timeout(Some(IMAP_TIMEOUT)); session.as_mut().set_read_timeout(Some(IMAP_TIMEOUT));
self.inner = session; self.inner = session;

View File

@@ -22,7 +22,7 @@ pub enum Error {
impl From<anyhow::Error> for Error { impl From<anyhow::Error> for Error {
fn from(err: anyhow::Error) -> Error { fn from(err: anyhow::Error) -> Error {
Error::Other(format!("{:#}", err)) Error::Other(format!("{err:#}"))
} }
} }
@@ -111,12 +111,12 @@ impl ImapSession {
Error::NoFolder(..) => { Error::NoFolder(..) => {
info!(context, "Failed to select folder {} because it does not exist, trying to create it.", folder); info!(context, "Failed to select folder {} because it does not exist, trying to create it.", folder);
self.create(folder).await.with_context(|| { self.create(folder).await.with_context(|| {
format!("Couldn't select folder ('{}'), then create() failed", err) format!("Couldn't select folder ('{err}'), then create() failed")
})?; })?;
Ok(self.select_folder(context, Some(folder)).await.with_context(|| format!("failed to select newely created folder {}", folder))?) Ok(self.select_folder(context, Some(folder)).await.with_context(|| format!("failed to select newely created folder {folder}"))?)
} }
_ => Err(err).with_context(|| format!("failed to select folder {} with error other than NO, not trying to create it", folder)), _ => Err(err).with_context(|| format!("failed to select folder {folder} with error other than NO, not trying to create it")),
}, },
} }
} }

View File

@@ -489,13 +489,13 @@ fn get_next_backup_path(folder: &Path, backup_time: i64) -> Result<(PathBuf, Pat
// 64 backup files per day should be enough for everyone // 64 backup files per day should be enough for everyone
for i in 0..64 { for i in 0..64 {
let mut tempdbfile = folder.clone(); let mut tempdbfile = folder.clone();
tempdbfile.push(format!("{}-{:02}.db", stem, i)); tempdbfile.push(format!("{stem}-{i:02}.db"));
let mut tempfile = folder.clone(); let mut tempfile = folder.clone();
tempfile.push(format!("{}-{:02}.tar.part", stem, i)); tempfile.push(format!("{stem}-{i:02}.tar.part"));
let mut destfile = folder.clone(); let mut destfile = folder.clone();
destfile.push(format!("{}-{:02}.tar", stem, i)); destfile.push(format!("{stem}-{i:02}.tar"));
if !tempdbfile.exists() && !tempfile.exists() && !destfile.exists() { if !tempdbfile.exists() && !tempfile.exists() && !destfile.exists() {
return Ok((tempdbfile, tempfile, destfile)); return Ok((tempdbfile, tempfile, destfile));
@@ -540,7 +540,7 @@ async fn export_backup(context: &Context, dir: &Path, passphrase: String) -> Res
.sql .sql
.export(&temp_db_path, passphrase) .export(&temp_db_path, passphrase)
.await .await
.with_context(|| format!("failed to backup plaintext database to {:?}", temp_db_path))?; .with_context(|| format!("failed to backup plaintext database to {temp_db_path:?}"))?;
let res = export_backup_inner(context, &temp_db_path, &temp_path).await; let res = export_backup_inner(context, &temp_db_path, &temp_path).await;
@@ -824,7 +824,7 @@ mod tests {
.await .await
.is_ok()); .is_ok());
let blobdir = context.ctx.get_blobdir().to_str().unwrap(); let blobdir = context.ctx.get_blobdir().to_str().unwrap();
let filename = format!("{}/public-key-default.asc", blobdir); let filename = format!("{blobdir}/public-key-default.asc");
let bytes = tokio::fs::read(&filename).await.unwrap(); let bytes = tokio::fs::read(&filename).await.unwrap();
assert_eq!(bytes, key.to_asc(None).into_bytes()); assert_eq!(bytes, key.to_asc(None).into_bytes());
@@ -839,7 +839,7 @@ mod tests {
.await .await
.is_ok()); .is_ok());
let blobdir = context.ctx.get_blobdir().to_str().unwrap(); let blobdir = context.ctx.get_blobdir().to_str().unwrap();
let filename = format!("{}/private-key-default.asc", blobdir); let filename = format!("{blobdir}/private-key-default.asc");
let bytes = tokio::fs::read(&filename).await.unwrap(); let bytes = tokio::fs::read(&filename).await.unwrap();
assert_eq!(bytes, key.to_asc(None).into_bytes()); assert_eq!(bytes, key.to_asc(None).into_bytes());
@@ -850,12 +850,12 @@ mod tests {
let context = TestContext::new_alice().await; let context = TestContext::new_alice().await;
let blobdir = context.ctx.get_blobdir(); let blobdir = context.ctx.get_blobdir();
if let Err(err) = imex(&context.ctx, ImexMode::ExportSelfKeys, blobdir, None).await { if let Err(err) = imex(&context.ctx, ImexMode::ExportSelfKeys, blobdir, None).await {
panic!("got error on export: {:#}", err); panic!("got error on export: {err:#}");
} }
let context2 = TestContext::new_alice().await; let context2 = TestContext::new_alice().await;
if let Err(err) = imex(&context2.ctx, ImexMode::ImportSelfKeys, blobdir, None).await { if let Err(err) = imex(&context2.ctx, ImexMode::ImportSelfKeys, blobdir, None).await {
panic!("got error on import: {:#}", err); panic!("got error on import: {err:#}");
} }
} }

View File

@@ -415,7 +415,7 @@ LIMIT 1;
.sql .sql
.execute("DELETE FROM jobs WHERE id=?;", paramsv![id]) .execute("DELETE FROM jobs WHERE id=?;", paramsv![id])
.await .await
.with_context(|| format!("Failed to delete invalid job {}", id))?; .with_context(|| format!("Failed to delete invalid job {id}"))?;
} }
} }
} }

View File

@@ -363,7 +363,7 @@ impl fmt::Display for Fingerprint {
} else if i > 0 && i % 4 == 0 { } else if i > 0 && i % 4 == 0 {
write!(f, " ")?; write!(f, " ")?;
} }
write!(f, "{}", c)?; write!(f, "{c}")?;
} }
Ok(()) Ok(())
} }

View File

@@ -15,7 +15,6 @@
clippy::unused_async clippy::unused_async
)] )]
#![allow( #![allow(
clippy::uninlined_format_args,
clippy::match_bool, clippy::match_bool,
clippy::mixed_read_write_in_expression, clippy::mixed_read_write_in_expression,
clippy::bool_assert_comparison, clippy::bool_assert_comparison,

View File

@@ -465,8 +465,7 @@ pub async fn get_kml(context: &Context, chat_id: ChatId) -> Result<(String, u32)
if locations_send_begin != 0 && now <= locations_send_until { if locations_send_begin != 0 && now <= locations_send_until {
ret += &format!( ret += &format!(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
<kml xmlns=\"http://www.opengis.net/kml/2.2\">\n<Document addr=\"{}\">\n", <kml xmlns=\"http://www.opengis.net/kml/2.2\">\n<Document addr=\"{self_addr}\">\n",
self_addr,
); );
context context
@@ -500,10 +499,9 @@ pub async fn get_kml(context: &Context, chat_id: ChatId) -> Result<(String, u32)
let (location_id, latitude, longitude, accuracy, timestamp) = row?; let (location_id, latitude, longitude, accuracy, timestamp) = row?;
ret += &format!( ret += &format!(
"<Placemark>\ "<Placemark>\
<Timestamp><when>{}</when></Timestamp>\ <Timestamp><when>{timestamp}</when></Timestamp>\
<Point><coordinates accuracy=\"{}\">{},{}</coordinates></Point>\ <Point><coordinates accuracy=\"{accuracy}\">{longitude},{latitude}</coordinates></Point>\
</Placemark>\n", </Placemark>\n"
timestamp, accuracy, longitude, latitude
); );
location_count += 1; location_count += 1;
last_added_location_id = location_id as u32; last_added_location_id = location_id as u32;

View File

@@ -92,7 +92,7 @@ impl LoginParam {
async fn from_database(context: &Context, prefix: &str) -> Result<Self> { async fn from_database(context: &Context, prefix: &str) -> Result<Self> {
let sql = &context.sql; let sql = &context.sql;
let key = &format!("{}addr", prefix); let key = &format!("{prefix}addr");
let addr = sql let addr = sql
.get_raw_config(key) .get_raw_config(key)
.await? .await?
@@ -100,26 +100,26 @@ impl LoginParam {
.trim() .trim()
.to_string(); .to_string();
let key = &format!("{}mail_server", prefix); let key = &format!("{prefix}mail_server");
let mail_server = sql.get_raw_config(key).await?.unwrap_or_default(); let mail_server = sql.get_raw_config(key).await?.unwrap_or_default();
let key = &format!("{}mail_port", prefix); let key = &format!("{prefix}mail_port");
let mail_port = sql.get_raw_config_int(key).await?.unwrap_or_default(); let mail_port = sql.get_raw_config_int(key).await?.unwrap_or_default();
let key = &format!("{}mail_user", prefix); let key = &format!("{prefix}mail_user");
let mail_user = sql.get_raw_config(key).await?.unwrap_or_default(); let mail_user = sql.get_raw_config(key).await?.unwrap_or_default();
let key = &format!("{}mail_pw", prefix); let key = &format!("{prefix}mail_pw");
let mail_pw = sql.get_raw_config(key).await?.unwrap_or_default(); let mail_pw = sql.get_raw_config(key).await?.unwrap_or_default();
let key = &format!("{}mail_security", prefix); let key = &format!("{prefix}mail_security");
let mail_security = sql let mail_security = sql
.get_raw_config_int(key) .get_raw_config_int(key)
.await? .await?
.and_then(num_traits::FromPrimitive::from_i32) .and_then(num_traits::FromPrimitive::from_i32)
.unwrap_or_default(); .unwrap_or_default();
let key = &format!("{}imap_certificate_checks", prefix); let key = &format!("{prefix}imap_certificate_checks");
let imap_certificate_checks = let imap_certificate_checks =
if let Some(certificate_checks) = sql.get_raw_config_int(key).await? { if let Some(certificate_checks) = sql.get_raw_config_int(key).await? {
num_traits::FromPrimitive::from_i32(certificate_checks).unwrap() num_traits::FromPrimitive::from_i32(certificate_checks).unwrap()
@@ -127,26 +127,26 @@ impl LoginParam {
Default::default() Default::default()
}; };
let key = &format!("{}send_server", prefix); let key = &format!("{prefix}send_server");
let send_server = sql.get_raw_config(key).await?.unwrap_or_default(); let send_server = sql.get_raw_config(key).await?.unwrap_or_default();
let key = &format!("{}send_port", prefix); let key = &format!("{prefix}send_port");
let send_port = sql.get_raw_config_int(key).await?.unwrap_or_default(); let send_port = sql.get_raw_config_int(key).await?.unwrap_or_default();
let key = &format!("{}send_user", prefix); let key = &format!("{prefix}send_user");
let send_user = sql.get_raw_config(key).await?.unwrap_or_default(); let send_user = sql.get_raw_config(key).await?.unwrap_or_default();
let key = &format!("{}send_pw", prefix); let key = &format!("{prefix}send_pw");
let send_pw = sql.get_raw_config(key).await?.unwrap_or_default(); let send_pw = sql.get_raw_config(key).await?.unwrap_or_default();
let key = &format!("{}send_security", prefix); let key = &format!("{prefix}send_security");
let send_security = sql let send_security = sql
.get_raw_config_int(key) .get_raw_config_int(key)
.await? .await?
.and_then(num_traits::FromPrimitive::from_i32) .and_then(num_traits::FromPrimitive::from_i32)
.unwrap_or_default(); .unwrap_or_default();
let key = &format!("{}smtp_certificate_checks", prefix); let key = &format!("{prefix}smtp_certificate_checks");
let smtp_certificate_checks = let smtp_certificate_checks =
if let Some(certificate_checks) = sql.get_raw_config_int(key).await? { if let Some(certificate_checks) = sql.get_raw_config_int(key).await? {
num_traits::FromPrimitive::from_i32(certificate_checks).unwrap_or_default() num_traits::FromPrimitive::from_i32(certificate_checks).unwrap_or_default()
@@ -154,11 +154,11 @@ impl LoginParam {
Default::default() Default::default()
}; };
let key = &format!("{}server_flags", prefix); let key = &format!("{prefix}server_flags");
let server_flags = sql.get_raw_config_int(key).await?.unwrap_or_default(); let server_flags = sql.get_raw_config_int(key).await?.unwrap_or_default();
let oauth2 = matches!(server_flags & DC_LP_AUTH_FLAGS, DC_LP_AUTH_OAUTH2); let oauth2 = matches!(server_flags & DC_LP_AUTH_FLAGS, DC_LP_AUTH_OAUTH2);
let key = &format!("{}provider", prefix); let key = &format!("{prefix}provider");
let provider = sql let provider = sql
.get_raw_config(key) .get_raw_config(key)
.await? .await?
@@ -198,50 +198,50 @@ impl LoginParam {
context.set_primary_self_addr(&self.addr).await?; context.set_primary_self_addr(&self.addr).await?;
let key = &format!("{}mail_server", prefix); let key = &format!("{prefix}mail_server");
sql.set_raw_config(key, Some(&self.imap.server)).await?; sql.set_raw_config(key, Some(&self.imap.server)).await?;
let key = &format!("{}mail_port", prefix); let key = &format!("{prefix}mail_port");
sql.set_raw_config_int(key, i32::from(self.imap.port)) sql.set_raw_config_int(key, i32::from(self.imap.port))
.await?; .await?;
let key = &format!("{}mail_user", prefix); let key = &format!("{prefix}mail_user");
sql.set_raw_config(key, Some(&self.imap.user)).await?; sql.set_raw_config(key, Some(&self.imap.user)).await?;
let key = &format!("{}mail_pw", prefix); let key = &format!("{prefix}mail_pw");
sql.set_raw_config(key, Some(&self.imap.password)).await?; sql.set_raw_config(key, Some(&self.imap.password)).await?;
let key = &format!("{}mail_security", prefix); let key = &format!("{prefix}mail_security");
sql.set_raw_config_int(key, self.imap.security as i32) sql.set_raw_config_int(key, self.imap.security as i32)
.await?; .await?;
let key = &format!("{}imap_certificate_checks", prefix); let key = &format!("{prefix}imap_certificate_checks");
sql.set_raw_config_int(key, self.imap.certificate_checks as i32) sql.set_raw_config_int(key, self.imap.certificate_checks as i32)
.await?; .await?;
let key = &format!("{}send_server", prefix); let key = &format!("{prefix}send_server");
sql.set_raw_config(key, Some(&self.smtp.server)).await?; sql.set_raw_config(key, Some(&self.smtp.server)).await?;
let key = &format!("{}send_port", prefix); let key = &format!("{prefix}send_port");
sql.set_raw_config_int(key, i32::from(self.smtp.port)) sql.set_raw_config_int(key, i32::from(self.smtp.port))
.await?; .await?;
let key = &format!("{}send_user", prefix); let key = &format!("{prefix}send_user");
sql.set_raw_config(key, Some(&self.smtp.user)).await?; sql.set_raw_config(key, Some(&self.smtp.user)).await?;
let key = &format!("{}send_pw", prefix); let key = &format!("{prefix}send_pw");
sql.set_raw_config(key, Some(&self.smtp.password)).await?; sql.set_raw_config(key, Some(&self.smtp.password)).await?;
let key = &format!("{}send_security", prefix); let key = &format!("{prefix}send_security");
sql.set_raw_config_int(key, self.smtp.security as i32) sql.set_raw_config_int(key, self.smtp.security as i32)
.await?; .await?;
let key = &format!("{}smtp_certificate_checks", prefix); let key = &format!("{prefix}smtp_certificate_checks");
sql.set_raw_config_int(key, self.smtp.certificate_checks as i32) sql.set_raw_config_int(key, self.smtp.certificate_checks as i32)
.await?; .await?;
// The OAuth2 flag is either set for both IMAP and SMTP or not at all. // The OAuth2 flag is either set for both IMAP and SMTP or not at all.
let key = &format!("{}server_flags", prefix); let key = &format!("{prefix}server_flags");
let server_flags = match self.imap.oauth2 { let server_flags = match self.imap.oauth2 {
true => DC_LP_AUTH_OAUTH2, true => DC_LP_AUTH_OAUTH2,
false => DC_LP_AUTH_NORMAL, false => DC_LP_AUTH_NORMAL,
@@ -249,7 +249,7 @@ impl LoginParam {
sql.set_raw_config_int(key, server_flags).await?; sql.set_raw_config_int(key, server_flags).await?;
if let Some(provider) = self.provider { if let Some(provider) = self.provider {
let key = &format!("{}provider", prefix); let key = &format!("{prefix}provider");
sql.set_raw_config(key, Some(provider.id)).await?; sql.set_raw_config(key, Some(provider.id)).await?;
} }

View File

@@ -706,7 +706,7 @@ impl Message {
// make sure, there is a scheme in the url // make sure, there is a scheme in the url
if !url.contains(':') { if !url.contains(':') {
url = format!("https://{}", url); url = format!("https://{url}");
} }
// add/replace room // add/replace room
@@ -731,13 +731,13 @@ impl Message {
} else { } else {
"/" "/"
}; };
format!("{}{}{}", url, maybe_slash, room) format!("{url}{maybe_slash}{room}")
}; };
// re-add and normalize type // re-add and normalize type
match videochat_type { match videochat_type {
VideochatType::BasicWebrtc => format!("basicwebrtc:{}", url), VideochatType::BasicWebrtc => format!("basicwebrtc:{url}"),
VideochatType::Jitsi => format!("jitsi:{}", url), VideochatType::Jitsi => format!("jitsi:{url}"),
VideochatType::Unknown => url, VideochatType::Unknown => url,
} }
} }
@@ -1085,21 +1085,21 @@ pub async fn get_msg_info(context: &Context, msg_id: MsgId) -> Result<String> {
let mut ret = String::new(); let mut ret = String::new();
if rawtxt.is_none() { if rawtxt.is_none() {
ret += &format!("Cannot load message {}.", msg_id); ret += &format!("Cannot load message {msg_id}.");
return Ok(ret); return Ok(ret);
} }
let rawtxt = rawtxt.unwrap_or_default(); let rawtxt = rawtxt.unwrap_or_default();
let rawtxt = truncate(rawtxt.trim(), DC_DESIRED_TEXT_LEN); let rawtxt = truncate(rawtxt.trim(), DC_DESIRED_TEXT_LEN);
let fts = timestamp_to_str(msg.get_timestamp()); let fts = timestamp_to_str(msg.get_timestamp());
ret += &format!("Sent: {}", fts); ret += &format!("Sent: {fts}");
let name = Contact::load_from_db(context, msg.from_id) let name = Contact::load_from_db(context, msg.from_id)
.await .await
.map(|contact| contact.get_name_n_addr()) .map(|contact| contact.get_name_n_addr())
.unwrap_or_default(); .unwrap_or_default();
ret += &format!(" by {}", name); ret += &format!(" by {name}");
ret += "\n"; ret += "\n";
if msg.from_id != ContactId::SELF { if msg.from_id != ContactId::SELF {
@@ -1113,7 +1113,7 @@ pub async fn get_msg_info(context: &Context, msg_id: MsgId) -> Result<String> {
} }
if let EphemeralTimer::Enabled { duration } = msg.ephemeral_timer { if let EphemeralTimer::Enabled { duration } = msg.ephemeral_timer {
ret += &format!("Ephemeral timer: {}\n", duration); ret += &format!("Ephemeral timer: {duration}\n");
} }
if msg.ephemeral_timestamp != 0 { if msg.ephemeral_timestamp != 0 {
@@ -1141,14 +1141,14 @@ pub async fn get_msg_info(context: &Context, msg_id: MsgId) -> Result<String> {
{ {
for (contact_id, ts) in rows { for (contact_id, ts) in rows {
let fts = timestamp_to_str(ts); let fts = timestamp_to_str(ts);
ret += &format!("Read: {}", fts); ret += &format!("Read: {fts}");
let name = Contact::load_from_db(context, contact_id) let name = Contact::load_from_db(context, contact_id)
.await .await
.map(|contact| contact.get_name_n_addr()) .map(|contact| contact.get_name_n_addr())
.unwrap_or_default(); .unwrap_or_default();
ret += &format!(" by {}", name); ret += &format!(" by {name}");
ret += "\n"; ret += "\n";
} }
} }
@@ -1173,11 +1173,11 @@ pub async fn get_msg_info(context: &Context, msg_id: MsgId) -> Result<String> {
let reactions = get_msg_reactions(context, msg_id).await?; let reactions = get_msg_reactions(context, msg_id).await?;
if !reactions.is_empty() { if !reactions.is_empty() {
ret += &format!("Reactions: {}\n", reactions); ret += &format!("Reactions: {reactions}\n");
} }
if let Some(error) = msg.error.as_ref() { if let Some(error) = msg.error.as_ref() {
ret += &format!("Error: {}", error); ret += &format!("Error: {error}");
} }
if let Some(path) = msg.get_file(context) { if let Some(path) = msg.get_file(context) {
@@ -1194,14 +1194,14 @@ pub async fn get_msg_info(context: &Context, msg_id: MsgId) -> Result<String> {
let w = msg.param.get_int(Param::Width).unwrap_or_default(); let w = msg.param.get_int(Param::Width).unwrap_or_default();
let h = msg.param.get_int(Param::Height).unwrap_or_default(); let h = msg.param.get_int(Param::Height).unwrap_or_default();
if w != 0 || h != 0 { if w != 0 || h != 0 {
ret += &format!("Dimension: {} x {}\n", w, h,); ret += &format!("Dimension: {w} x {h}\n",);
} }
let duration = msg.param.get_int(Param::Duration).unwrap_or_default(); let duration = msg.param.get_int(Param::Duration).unwrap_or_default();
if duration != 0 { if duration != 0 {
ret += &format!("Duration: {} ms\n", duration,); ret += &format!("Duration: {duration} ms\n",);
} }
if !rawtxt.is_empty() { if !rawtxt.is_empty() {
ret += &format!("\n{}\n", rawtxt); ret += &format!("\n{rawtxt}\n");
} }
if !msg.rfc724_mid.is_empty() { if !msg.rfc724_mid.is_empty() {
ret += &format!("\nMessage-ID: {}", msg.rfc724_mid); ret += &format!("\nMessage-ID: {}", msg.rfc724_mid);
@@ -1225,7 +1225,7 @@ pub async fn get_msg_info(context: &Context, msg_id: MsgId) -> Result<String> {
for (folder, uid) in server_uids { for (folder, uid) in server_uids {
// Format as RFC 5092 relative IMAP URL. // Format as RFC 5092 relative IMAP URL.
ret += &format!("\n</{}/;UID={}>", folder, uid); ret += &format!("\n</{folder}/;UID={uid}>");
} }
} }
let hop_info: Option<String> = context let hop_info: Option<String> = context
@@ -1364,7 +1364,7 @@ pub async fn delete_msgs(context: &Context, msg_ids: &[MsgId]) -> Result<()> {
msg_id msg_id
.trash(context) .trash(context)
.await .await
.with_context(|| format!("Unable to trash message {}", msg_id))?; .with_context(|| format!("Unable to trash message {msg_id}"))?;
if msg.viewtype == Viewtype::Webxdc { if msg.viewtype == Viewtype::Webxdc {
context.emit_event(EventType::WebxdcInstanceDeleted { msg_id: *msg_id }); context.emit_event(EventType::WebxdcInstanceDeleted { msg_id: *msg_id });
@@ -1718,7 +1718,7 @@ pub(crate) async fn handle_ndn(
let error = if let Some(error) = error { let error = if let Some(error) = error {
error error
} else if let Some(failed_recipient) = &failed.failed_recipient { } else if let Some(failed_recipient) = &failed.failed_recipient {
format!("Delivery to {} failed.", failed_recipient).clone() format!("Delivery to {failed_recipient} failed.").clone()
} else { } else {
"Delivery to at least one recipient failed.".to_string() "Delivery to at least one recipient failed.".to_string()
}; };

View File

@@ -716,7 +716,7 @@ impl<'a> MimeFactory<'a> {
} }
let message = message.replace_header(Header::new( let message = message.replace_header(Header::new(
"Content-Type".to_string(), "Content-Type".to_string(),
format!("{} protected-headers=\"v1\";", existing_ct), format!("{existing_ct} protected-headers=\"v1\";"),
)); ));
// Set the appropriate Content-Type for the outer message // Set the appropriate Content-Type for the outer message
@@ -1234,7 +1234,7 @@ impl<'a> MimeFactory<'a> {
Some(path) => match build_selfavatar_file(context, &path).await { Some(path) => match build_selfavatar_file(context, &path).await {
Ok(avatar) => headers.hidden.push(Header::new( Ok(avatar) => headers.hidden.push(Header::new(
"Chat-User-Avatar".into(), "Chat-User-Avatar".into(),
format!("base64:{}", avatar), format!("base64:{avatar}"),
)), )),
Err(err) => warn!(context, "mimefactory: cannot attach selfavatar: {}", err), Err(err) => warn!(context, "mimefactory: cannot attach selfavatar: {}", err),
}, },
@@ -1470,7 +1470,7 @@ fn render_rfc724_mid(rfc724_mid: &str) -> String {
if rfc724_mid.chars().next().unwrap_or_default() == '<' { if rfc724_mid.chars().next().unwrap_or_default() == '<' {
rfc724_mid rfc724_mid
} else { } else {
format!("<{}>", rfc724_mid) format!("<{rfc724_mid}>")
} }
} }
@@ -1535,7 +1535,7 @@ mod tests {
Address::new_mailbox_with_name(display_name.to_string(), addr.to_string()) Address::new_mailbox_with_name(display_name.to_string(), addr.to_string())
); );
println!("{}", s); println!("{s}");
assert_eq!(s, "=?utf-8?q?=C3=A4_space?= <x@y.org>"); assert_eq!(s, "=?utf-8?q?=C3=A4_space?= <x@y.org>");
} }

View File

@@ -377,13 +377,13 @@ impl MimeMessage {
} }
Err(err) => { Err(err) => {
let msg_body = stock_str::cant_decrypt_msg_body(context).await; let msg_body = stock_str::cant_decrypt_msg_body(context).await;
let txt = format!("[{}]", msg_body); let txt = format!("[{msg_body}]");
let part = Part { let part = Part {
typ: Viewtype::Text, typ: Viewtype::Text,
msg_raw: Some(txt.clone()), msg_raw: Some(txt.clone()),
msg: txt, msg: txt,
error: Some(format!("Decrypting failed: {:#}", err)), error: Some(format!("Decrypting failed: {err:#}")),
..Default::default() ..Default::default()
}; };
parser.parts.push(part); parser.parts.push(part);
@@ -669,14 +669,14 @@ impl MimeMessage {
if let Ok(decoded_data) = avatar { if let Ok(decoded_data) = avatar {
let extension = if let Ok(format) = image::guess_format(&decoded_data) { let extension = if let Ok(format) = image::guess_format(&decoded_data) {
if let Some(ext) = format.extensions_str().first() { if let Some(ext) = format.extensions_str().first() {
format!(".{}", ext) format!(".{ext}")
} else { } else {
String::new() String::new()
} }
} else { } else {
String::new() String::new()
}; };
match BlobObject::create(context, &format!("avatar{}", extension), &decoded_data) match BlobObject::create(context, &format!("avatar{extension}"), &decoded_data)
.await .await
{ {
Ok(blob) => Some(AvatarAction::Change(blob.as_name().to_string())), Ok(blob) => Some(AvatarAction::Change(blob.as_name().to_string())),
@@ -1302,7 +1302,7 @@ impl MimeMessage {
self.is_system_message = SystemMessage::Unknown; self.is_system_message = SystemMessage::Unknown;
if let Some(part) = self.parts.first_mut() { if let Some(part) = self.parts.first_mut() {
part.typ = Viewtype::Text; part.typ = Viewtype::Text;
part.msg = format!("[{}]", error_msg); part.msg = format!("[{error_msg}]");
self.parts.truncate(1); self.parts.truncate(1);
} }
} }
@@ -1882,7 +1882,7 @@ fn get_attachment_filename(
// If there is no filename, but part is an attachment, guess filename // If there is no filename, but part is an attachment, guess filename
if desired_filename.is_none() && ct.disposition == DispositionType::Attachment { if desired_filename.is_none() && ct.disposition == DispositionType::Attachment {
if let Some(subtype) = mail.ctype.mimetype.split('/').nth(1) { if let Some(subtype) = mail.ctype.mimetype.split('/').nth(1) {
desired_filename = Some(format!("file.{}", subtype,)); desired_filename = Some(format!("file.{subtype}",));
} else { } else {
bail!( bail!(
"could not determine attachment filename: {:?}", "could not determine attachment filename: {:?}",

View File

@@ -391,7 +391,7 @@ impl Params {
/// Set the given paramter to the passed in `i32`. /// Set the given paramter to the passed in `i32`.
pub fn set_int(&mut self, key: Param, value: i32) -> &mut Self { pub fn set_int(&mut self, key: Param, value: i32) -> &mut Self {
self.set(key, format!("{}", value)); self.set(key, format!("{value}"));
self self
} }
@@ -403,7 +403,7 @@ impl Params {
/// Set the given parameter to the passed in `f64` . /// Set the given parameter to the passed in `f64` .
pub fn set_float(&mut self, key: Param, value: f64) -> &mut Self { pub fn set_float(&mut self, key: Param, value: f64) -> &mut Self {
self.set(key, format!("{}", value)); self.set(key, format!("{value}"));
self self
} }
} }

View File

@@ -417,8 +417,7 @@ impl Peerstate {
Ok(()) Ok(())
} else { } else {
Err(Error::msg(format!( Err(Error::msg(format!(
"{} is not peer's public key fingerprint", "{fingerprint} is not peer's public key fingerprint",
fingerprint,
))) )))
} }
} }
@@ -432,8 +431,7 @@ impl Peerstate {
Ok(()) Ok(())
} else { } else {
Err(Error::msg(format!( Err(Error::msg(format!(
"{} is not peer's gossip key fingerprint", "{fingerprint} is not peer's gossip key fingerprint",
fingerprint,
))) )))
} }
} }

View File

@@ -136,7 +136,7 @@ pub(crate) fn create_keypair(addr: EmailAddress, keygen_type: KeyGenType) -> Res
KeyGenType::Ed25519 | KeyGenType::Default => (PgpKeyType::EdDSA, PgpKeyType::ECDH), KeyGenType::Ed25519 | KeyGenType::Default => (PgpKeyType::EdDSA, PgpKeyType::ECDH),
}; };
let user_id = format!("<{}>", addr); let user_id = format!("<{addr}>");
let key_params = SecretKeyParamsBuilder::default() let key_params = SecretKeyParamsBuilder::default()
.key_type(secret_key_type) .key_type(secret_key_type)
.can_create_certificates(true) .can_create_certificates(true)

View File

@@ -227,13 +227,13 @@ async fn decode_openpgp(context: &Context, qr: &str) -> Result<Qr> {
let addr = ContactAddress::new(addr)?; let addr = ContactAddress::new(addr)?;
let (contact_id, _) = Contact::add_or_lookup(context, &name, addr, Origin::UnhandledQrScan) let (contact_id, _) = Contact::add_or_lookup(context, &name, addr, Origin::UnhandledQrScan)
.await .await
.with_context(|| format!("failed to add or lookup contact for address {:?}", addr))?; .with_context(|| format!("failed to add or lookup contact for address {addr:?}"))?;
if let (Some(grpid), Some(grpname)) = (grpid, grpname) { if let (Some(grpid), Some(grpname)) = (grpid, grpname) {
if context if context
.is_self_addr(&addr) .is_self_addr(&addr)
.await .await
.with_context(|| format!("can't check if address {:?} is our address", addr))? .with_context(|| format!("can't check if address {addr:?} is our address"))?
{ {
if token::exists(context, token::Namespace::InviteNumber, &invitenumber).await { if token::exists(context, token::Namespace::InviteNumber, &invitenumber).await {
Ok(Qr::WithdrawVerifyGroup { Ok(Qr::WithdrawVerifyGroup {
@@ -309,7 +309,7 @@ async fn decode_openpgp(context: &Context, qr: &str) -> Result<Qr> {
} else { } else {
let contact_id = Contact::lookup_id_by_addr(context, &addr, Origin::Unknown) let contact_id = Contact::lookup_id_by_addr(context, &addr, Origin::Unknown)
.await .await
.with_context(|| format!("Error looking up contact {:?}", addr))?; .with_context(|| format!("Error looking up contact {addr:?}"))?;
Ok(Qr::FprMismatch { contact_id }) Ok(Qr::FprMismatch { contact_id })
} }
} else { } else {
@@ -325,7 +325,7 @@ fn decode_account(qr: &str) -> Result<Qr> {
.get(DCACCOUNT_SCHEME.len()..) .get(DCACCOUNT_SCHEME.len()..)
.context("invalid DCACCOUNT payload")?; .context("invalid DCACCOUNT payload")?;
let url = let url =
url::Url::parse(payload).with_context(|| format!("Invalid account URL: {:?}", payload))?; url::Url::parse(payload).with_context(|| format!("Invalid account URL: {payload:?}"))?;
if url.scheme() == "http" || url.scheme() == "https" { if url.scheme() == "http" || url.scheme() == "https" {
Ok(Qr::Account { Ok(Qr::Account {
domain: url domain: url
@@ -346,7 +346,7 @@ fn decode_webrtc_instance(_context: &Context, qr: &str) -> Result<Qr> {
let (_type, url) = Message::parse_webrtc_instance(payload); let (_type, url) = Message::parse_webrtc_instance(payload);
let url = let url =
url::Url::parse(&url).with_context(|| format!("Invalid WebRTC instance: {:?}", payload))?; url::Url::parse(&url).with_context(|| format!("Invalid WebRTC instance: {payload:?}"))?;
if url.scheme() == "http" || url.scheme() == "https" { if url.scheme() == "http" || url.scheme() == "https" {
Ok(Qr::WebrtcInstance { Ok(Qr::WebrtcInstance {
@@ -380,18 +380,14 @@ async fn set_account_from_qr(context: &Context, qr: &str) -> Result<()> {
let response = crate::http::get_client()?.post(url_str).send().await?; let response = crate::http::get_client()?.post(url_str).send().await?;
let response_status = response.status(); let response_status = response.status();
let response_text = response.text().await.with_context(|| { let response_text = response.text().await.with_context(|| {
format!( format!("Cannot create account, request to {url_str:?} failed: empty response")
"Cannot create account, request to {:?} failed: empty response",
url_str
)
})?; })?;
if response_status.is_success() { if response_status.is_success() {
let CreateAccountSuccessResponse { password, email } = serde_json::from_str(&response_text) let CreateAccountSuccessResponse { password, email } = serde_json::from_str(&response_text)
.with_context(|| { .with_context(|| {
format!( format!(
"Cannot create account, response from {:?} is malformed:\n{:?}", "Cannot create account, response from {url_str:?} is malformed:\n{response_text:?}"
url_str, response_text
) )
})?; })?;
context.set_config(Config::Addr, Some(&email)).await?; context.set_config(Config::Addr, Some(&email)).await?;
@@ -403,8 +399,7 @@ async fn set_account_from_qr(context: &Context, qr: &str) -> Result<()> {
Ok(error) => Err(anyhow!(error.reason)), Ok(error) => Err(anyhow!(error.reason)),
Err(parse_error) => { Err(parse_error) => {
context.emit_event(EventType::Error(format!( context.emit_event(EventType::Error(format!(
"Cannot create account, server response could not be parsed:\n{:#}\nraw response:\n{}", "Cannot create account, server response could not be parsed:\n{parse_error:#}\nraw response:\n{response_text}"
parse_error, response_text
))); )));
bail!( bail!(
"Cannot create account, unexpected server response:\n{:?}", "Cannot create account, unexpected server response:\n{:?}",
@@ -603,7 +598,7 @@ async fn decode_vcard(context: &Context, qr: &str) -> Result<Qr> {
let last_name = caps.get(1)?.as_str().trim(); let last_name = caps.get(1)?.as_str().trim();
let first_name = caps.get(2)?.as_str().trim(); let first_name = caps.get(2)?.as_str().trim();
Some(format!("{} {}", first_name, last_name)) Some(format!("{first_name} {last_name}"))
}) })
.unwrap_or_default(); .unwrap_or_default();

View File

@@ -32,7 +32,7 @@ pub enum LoginOptions {
/// scheme: `dclogin://user@host/?p=password&v=1[&options]` /// scheme: `dclogin://user@host/?p=password&v=1[&options]`
/// read more about the scheme at <https://github.com/deltachat/interface/blob/master/uri-schemes.md#DCLOGIN> /// read more about the scheme at <https://github.com/deltachat/interface/blob/master/uri-schemes.md#DCLOGIN>
pub(super) fn decode_login(qr: &str) -> Result<Qr> { pub(super) fn decode_login(qr: &str) -> Result<Qr> {
let url = url::Url::parse(qr).with_context(|| format!("Malformed url: {:?}", qr))?; let url = url::Url::parse(qr).with_context(|| format!("Malformed url: {qr:?}"))?;
let url_without_scheme = qr let url_without_scheme = qr
.get(DCLOGIN_SCHEME.len()..) .get(DCLOGIN_SCHEME.len()..)

View File

@@ -90,7 +90,7 @@ fn inner_generate_secure_join_qr_code(
w.elem("svg", |d| { w.elem("svg", |d| {
d.attr("xmlns", "http://www.w3.org/2000/svg")?; d.attr("xmlns", "http://www.w3.org/2000/svg")?;
d.attr("viewBox", format_args!("0 0 {} {}", width, height))?; d.attr("viewBox", format_args!("0 0 {width} {height}"))?;
Ok(()) Ok(())
})? })?
.build(|w| { .build(|w| {
@@ -129,14 +129,14 @@ fn inner_generate_secure_join_qr_code(
for y in 0..qr.size() { for y in 0..qr.size() {
for x in 0..qr.size() { for x in 0..qr.size() {
if qr.get_module(x, y) { if qr.get_module(x, y) {
path_data += &format!("M{},{}h1v1h-1z", x, y); path_data += &format!("M{x},{y}h1v1h-1z");
} }
} }
} }
d.attr("style", "fill:#000000")?; d.attr("style", "fill:#000000")?;
d.attr("d", path_data)?; d.attr("d", path_data)?;
d.attr("transform", format!("scale({})", scale)) d.attr("transform", format!("scale({scale})"))
}) })
})?; })?;
@@ -167,10 +167,9 @@ fn inner_generate_secure_join_qr_code(
format!( format!(
"font-family:sans-serif;\ "font-family:sans-serif;\
font-weight:bold;\ font-weight:bold;\
font-size:{}px;\ font-size:{text_font_size}px;\
fill:#000000;\ fill:#000000;\
stroke:none", stroke:none"
text_font_size
), ),
) )
})? })?
@@ -236,9 +235,8 @@ fn inner_generate_secure_join_qr_code(
format!( format!(
"font-family:sans-serif;\ "font-family:sans-serif;\
font-weight:400;\ font-weight:400;\
font-size:{}px;\ font-size:{avatar_font_size}px;\
fill:#ffffff;", fill:#ffffff;"
avatar_font_size
), ),
) )
})? })?

View File

@@ -135,7 +135,7 @@ impl fmt::Display for Reactions {
write!(f, " ")?; write!(f, " ")?;
} }
first = false; first = false;
write!(f, "{}{}", emoji, frequency)?; write!(f, "{emoji}{frequency}")?;
} }
Ok(()) Ok(())
} }
@@ -500,7 +500,7 @@ Content-Disposition: reaction\n\
Message-ID: <first@example.org>\n\ Message-ID: <first@example.org>\n\
Date: Sun, 14 Nov 2021 00:10:00 +0000\ Date: Sun, 14 Nov 2021 00:10:00 +0000\
Content-Type: text/plain"; Content-Type: text/plain";
let msg_full = format!("{}\n\n100k text...", msg_header); let msg_full = format!("{msg_header}\n\n100k text...");
// Alice downloads message from Bob partially. // Alice downloads message from Bob partially.
let alice_received_message = receive_imf_inner( let alice_received_message = receive_imf_inner(

View File

@@ -996,7 +996,7 @@ async fn add_parts(
if let Err(err) = check_verified_properties(context, mime_parser, from_id, to_ids).await if let Err(err) = check_verified_properties(context, mime_parser, from_id, to_ids).await
{ {
warn!(context, "verification problem: {:#}", err); warn!(context, "verification problem: {:#}", err);
let s = format!("{}. See 'Info' for more details", err); let s = format!("{err}. See 'Info' for more details");
mime_parser.repl_msg_by_error(&s); mime_parser.repl_msg_by_error(&s);
} else { } else {
// change chat protection only when verification check passes // change chat protection only when verification check passes
@@ -1013,7 +1013,7 @@ async fn add_parts(
chat::add_info_msg( chat::add_info_msg(
context, context,
chat_id, chat_id,
&format!("Cannot set protection: {}", e), &format!("Cannot set protection: {e}"),
sort_timestamp, sort_timestamp,
) )
.await?; .await?;
@@ -1162,7 +1162,7 @@ SET rfc724_mid=excluded.rfc724_mid, chat_id=excluded.chat_id,
if part.typ == Viewtype::Text { if part.typ == Viewtype::Text {
let msg_raw = part.msg_raw.as_ref().cloned().unwrap_or_default(); let msg_raw = part.msg_raw.as_ref().cloned().unwrap_or_default();
txt_raw = format!("{}\n\n{}", subject, msg_raw); txt_raw = format!("{subject}\n\n{msg_raw}");
} }
let ephemeral_timestamp = if in_fresh { let ephemeral_timestamp = if in_fresh {
@@ -1254,7 +1254,7 @@ SET rfc724_mid=excluded.rfc724_mid, chat_id=excluded.chat_id,
info!( info!(
context, context,
"Message has {} parts and is assigned to chat #{}.", icnt, chat_id, "Message has {icnt} parts and is assigned to chat #{chat_id}."
); );
// new outgoing message from another device marks the chat as noticed. // new outgoing message from another device marks the chat as noticed.
@@ -1522,7 +1522,7 @@ async fn create_or_lookup_group(
let create_protected = if mime_parser.get_header(HeaderDef::ChatVerified).is_some() { let create_protected = if mime_parser.get_header(HeaderDef::ChatVerified).is_some() {
if let Err(err) = check_verified_properties(context, mime_parser, from_id, to_ids).await { if let Err(err) = check_verified_properties(context, mime_parser, from_id, to_ids).await {
warn!(context, "verification problem: {:#}", err); warn!(context, "verification problem: {:#}", err);
let s = format!("{}. See 'Info' for more details", err); let s = format!("{err}. See 'Info' for more details");
mime_parser.repl_msg_by_error(&s); mime_parser.repl_msg_by_error(&s);
} }
ProtectionStatus::Protected ProtectionStatus::Protected
@@ -1573,7 +1573,7 @@ async fn create_or_lookup_group(
None, None,
) )
.await .await
.with_context(|| format!("Failed to create group '{}' for grpid={}", grpname, grpid))?; .with_context(|| format!("Failed to create group '{grpname}' for grpid={grpid}"))?;
chat_id = Some(new_chat_id); chat_id = Some(new_chat_id);
chat_id_blocked = create_blocked; chat_id_blocked = create_blocked;
@@ -1720,7 +1720,7 @@ async fn apply_group_changes(
if mime_parser.get_header(HeaderDef::ChatVerified).is_some() { if mime_parser.get_header(HeaderDef::ChatVerified).is_some() {
if let Err(err) = check_verified_properties(context, mime_parser, from_id, to_ids).await { if let Err(err) = check_verified_properties(context, mime_parser, from_id, to_ids).await {
warn!(context, "verification problem: {:#}", err); warn!(context, "verification problem: {:#}", err);
let s = format!("{}. See 'Info' for more details", err); let s = format!("{err}. See 'Info' for more details");
mime_parser.repl_msg_by_error(&s); mime_parser.repl_msg_by_error(&s);
} }

View File

@@ -627,15 +627,14 @@ async fn test_parse_ndn(
&t, &t,
format!( format!(
"Received: (Postfix, from userid 1000); Mon, 4 Dec 2006 14:51:39 +0100 (CET)\n\ "Received: (Postfix, from userid 1000); Mon, 4 Dec 2006 14:51:39 +0100 (CET)\n\
From: {}\n\ From: {self_addr}\n\
To: {}\n\ To: {foreign_addr}\n\
Subject: foo\n\ Subject: foo\n\
Message-ID: <{}>\n\ Message-ID: <{rfc724_mid_outgoing}>\n\
Chat-Version: 1.0\n\ Chat-Version: 1.0\n\
Date: Sun, 22 Mar 2020 22:37:57 +0000\n\ Date: Sun, 22 Mar 2020 22:37:57 +0000\n\
\n\ \n\
hello\n", hello\n"
self_addr, foreign_addr, rfc724_mid_outgoing
) )
.as_bytes(), .as_bytes(),
false, false,
@@ -861,7 +860,7 @@ async fn test_classic_mailing_list() -> Result<()> {
let sent = t.send_text(chat.id, "Hello mailinglist!").await; let sent = t.send_text(chat.id, "Hello mailinglist!").await;
let mime = sent.payload(); let mime = sent.payload();
println!("Sent mime message is:\n\n{}\n\n", mime); println!("Sent mime message is:\n\n{mime}\n\n");
assert!(mime.contains("Content-Type: text/plain; charset=utf-8; format=flowed; delsp=no\r\n")); assert!(mime.contains("Content-Type: text/plain; charset=utf-8; format=flowed; delsp=no\r\n"));
assert!(mime.contains("Subject: =?utf-8?q?Re=3A_=5Bdelta-dev=5D_What=27s_up=3F?=\r\n")); assert!(mime.contains("Subject: =?utf-8?q?Re=3A_=5Bdelta-dev=5D_What=27s_up=3F?=\r\n"));
assert!(mime.contains("MIME-Version: 1.0\r\n")); assert!(mime.contains("MIME-Version: 1.0\r\n"));
@@ -1375,7 +1374,7 @@ async fn test_apply_mailinglist_changes_assigned_by_reply() {
let chat = Chat::load_from_db(&t, chat_id).await.unwrap(); let chat = Chat::load_from_db(&t, chat_id).await.unwrap();
assert!(chat.can_send(&t).await.unwrap()); assert!(chat.can_send(&t).await.unwrap());
let imf_raw = format!("In-Reply-To: 3333@example.org\n{}", GH_MAILINGLIST2); let imf_raw = format!("In-Reply-To: 3333@example.org\n{GH_MAILINGLIST2}");
receive_imf(&t, imf_raw.as_bytes(), false).await.unwrap(); receive_imf(&t, imf_raw.as_bytes(), false).await.unwrap();
assert_eq!( assert_eq!(
@@ -1470,7 +1469,7 @@ async fn check_dont_show_in_contacts_list(addr: &str) {
&t, &t,
format!( format!(
"Subject: Re: [deltachat/deltachat-core-rust] DC is the best repo on GitHub! "Subject: Re: [deltachat/deltachat-core-rust] DC is the best repo on GitHub!
To: {} To: {addr}
References: <deltachat/deltachat-core-rust/pull/1625@github.com> References: <deltachat/deltachat-core-rust/pull/1625@github.com>
<deltachat/deltachat-core-rust/pull/1625/c644661857@github.com> <deltachat/deltachat-core-rust/pull/1625/c644661857@github.com>
From: alice@example.org From: alice@example.org
@@ -1481,8 +1480,7 @@ Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: 7bit Content-Transfer-Encoding: 7bit
YEAAAAAA!. YEAAAAAA!.
", "
addr
) )
.as_bytes(), .as_bytes(),
false, false,
@@ -2814,7 +2812,7 @@ async fn test_long_filenames() -> Result<()> {
"a.a..a.a.a.a.tar.gz", "a.a..a.a.a.a.tar.gz",
] { ] {
let attachment = alice.blobdir.join(filename_sent); let attachment = alice.blobdir.join(filename_sent);
let content = format!("File content of {}", filename_sent); let content = format!("File content of {filename_sent}");
tokio::fs::write(&attachment, content.as_bytes()).await?; tokio::fs::write(&attachment, content.as_bytes()).await?;
let mut msg_alice = Message::new(Viewtype::File); let mut msg_alice = Message::new(Viewtype::File);
@@ -2831,14 +2829,11 @@ async fn test_long_filenames() -> Result<()> {
let path = msg.get_file(t).unwrap(); let path = msg.get_file(t).unwrap();
assert!( assert!(
resulting_filename.ends_with(".tar.gz"), resulting_filename.ends_with(".tar.gz"),
"{:?} doesn't end with .tar.gz, path: {:?}", "{resulting_filename:?} doesn't end with .tar.gz, path: {path:?}"
resulting_filename,
path
); );
assert!( assert!(
path.to_str().unwrap().ends_with(".tar.gz"), path.to_str().unwrap().ends_with(".tar.gz"),
"path {:?} doesn't end with .tar.gz", "path {path:?} doesn't end with .tar.gz"
path
); );
assert_eq!(fs::read_to_string(path).await.unwrap(), content); assert_eq!(fs::read_to_string(path).await.unwrap(), content);
} }

View File

@@ -393,7 +393,7 @@ impl Context {
let watched_folders = get_watched_folder_configs(self).await?; let watched_folders = get_watched_folder_configs(self).await?;
let incoming_messages = stock_str::incoming_messages(self).await; let incoming_messages = stock_str::incoming_messages(self).await;
ret += &format!("<h3>{}</h3><ul>", incoming_messages); ret += &format!("<h3>{incoming_messages}</h3><ul>");
for (folder, state) in &folders_states { for (folder, state) in &folders_states {
let mut folder_added = false; let mut folder_added = false;
@@ -436,7 +436,7 @@ impl Context {
// ============================================================================================= // =============================================================================================
let outgoing_messages = stock_str::outgoing_messages(self).await; let outgoing_messages = stock_str::outgoing_messages(self).await;
ret += &format!("<h3>{}</h3><ul><li>", outgoing_messages); ret += &format!("<h3>{outgoing_messages}</h3><ul><li>");
let detailed = smtp.get_detailed().await; let detailed = smtp.get_detailed().await;
ret += &*detailed.to_icon(); ret += &*detailed.to_icon();
ret += " "; ret += " ";
@@ -452,7 +452,7 @@ impl Context {
let domain = &tools::EmailAddress::new(&self.get_primary_self_addr().await?)?.domain; let domain = &tools::EmailAddress::new(&self.get_primary_self_addr().await?)?.domain;
let storage_on_domain = stock_str::storage_on_domain(self, domain).await; let storage_on_domain = stock_str::storage_on_domain(self, domain).await;
ret += &format!("<h3>{}</h3><ul>", storage_on_domain); ret += &format!("<h3>{storage_on_domain}</h3><ul>");
let quota = self.quota.read().await; let quota = self.quota.read().await;
if let Some(quota) = &*quota { if let Some(quota) = &*quota {
match &quota.recent { match &quota.recent {
@@ -488,7 +488,7 @@ impl Context {
) )
} }
Message => { Message => {
format!("<b>{}:</b> {}", part_of_total_used, messages) format!("<b>{part_of_total_used}:</b> {messages}")
} }
Storage => { Storage => {
// do not use a special title needed for "Storage": // do not use a special title needed for "Storage":
@@ -511,14 +511,14 @@ impl Context {
} else { } else {
"green" "green"
}; };
ret += &format!("<div class=\"bar\"><div class=\"progress {}\" style=\"width: {}%\">{}%</div></div>", color, percent, percent); ret += &format!("<div class=\"bar\"><div class=\"progress {color}\" style=\"width: {percent}%\">{percent}%</div></div>");
ret += "</li>"; ret += "</li>";
} }
} }
} }
Err(e) => { Err(e) => {
ret += format!("<li>{}</li>", e).as_str(); ret += format!("<li>{e}</li>").as_str();
} }
} }
@@ -527,7 +527,7 @@ impl Context {
} }
} else { } else {
let not_connected = stock_str::not_connected(self).await; let not_connected = stock_str::not_connected(self).await;
ret += &format!("<li>{}</li>", not_connected); ret += &format!("<li>{not_connected}</li>");
self.schedule_quota_update().await?; self.schedule_quota_update().await?;
} }
ret += "</ul>"; ret += "</ul>";

View File

@@ -179,7 +179,7 @@ async fn send_alice_handshake_msg(
) -> Result<()> { ) -> Result<()> {
let mut msg = Message { let mut msg = Message {
viewtype: Viewtype::Text, viewtype: Viewtype::Text,
text: Some(format!("Secure-Join: {}", step)), text: Some(format!("Secure-Join: {step}")),
hidden: true, hidden: true,
..Default::default() ..Default::default()
}; };
@@ -625,7 +625,7 @@ pub(crate) async fn observe_securejoin_on_other_device(
context, context,
contact_id, contact_id,
info_chat_id(context, contact_id).await?, info_chat_id(context, contact_id).await?,
&format!("Could not mark peer as verified at step {}: {}", step, err), &format!("Could not mark peer as verified at step {step}: {err}"),
) )
.await?; .await?;
return Ok(HandshakeMessage::Ignore); return Ok(HandshakeMessage::Ignore);
@@ -653,7 +653,7 @@ pub(crate) async fn observe_securejoin_on_other_device(
context, context,
contact_id, contact_id,
info_chat_id(context, contact_id).await?, info_chat_id(context, contact_id).await?,
format!("Fingerprint mismatch on observing {}.", step).as_ref(), format!("Fingerprint mismatch on observing {step}.").as_ref(),
) )
.await?; .await?;
return Ok(HandshakeMessage::Ignore); return Ok(HandshakeMessage::Ignore);
@@ -1333,7 +1333,7 @@ mod tests {
if let chat::ChatItem::Message { msg_id } = item { if let chat::ChatItem::Message { msg_id } = item {
let msg = Message::load_from_db(&bob.ctx, msg_id).await.unwrap(); let msg = Message::load_from_db(&bob.ctx, msg_id).await.unwrap();
let text = msg.get_text().unwrap(); let text = msg.get_text().unwrap();
println!("msg {} text: {}", msg_id, text); println!("msg {msg_id} text: {text}");
} }
} }
let mut msg_iter = chat::get_chat_msgs(&bob.ctx, bob_chatid, DC_GCM_ADDDAYMARKER) let mut msg_iter = chat::get_chat_msgs(&bob.ctx, bob_chatid, DC_GCM_ADDDAYMARKER)

View File

@@ -126,7 +126,7 @@ impl Smtp {
} }
let from = EmailAddress::new(addr.to_string()) let from = EmailAddress::new(addr.to_string())
.with_context(|| format!("invalid login address {}", addr))?; .with_context(|| format!("invalid login address {addr}"))?;
self.from = Some(from); self.from = Some(from);
@@ -227,7 +227,7 @@ pub(crate) async fn smtp_send(
) -> SendResult { ) -> SendResult {
if std::env::var(crate::DCC_MIME_DEBUG).is_ok() { if std::env::var(crate::DCC_MIME_DEBUG).is_ok() {
info!(context, "smtp-sending out mime message:"); info!(context, "smtp-sending out mime message:");
println!("{}", message); println!("{message}");
} }
smtp.connectivity.set_working(context).await; smtp.connectivity.set_working(context).await;
@@ -237,7 +237,7 @@ pub(crate) async fn smtp_send(
.await .await
.context("Failed to open SMTP connection") .context("Failed to open SMTP connection")
{ {
smtp.last_send_error = Some(format!("{:#}", err)); smtp.last_send_error = Some(format!("{err:#}"));
return SendResult::Retry; return SendResult::Retry;
} }
@@ -374,7 +374,7 @@ pub(crate) async fn send_msg_to_smtp(
.await .await
.context("SMTP connection failure") .context("SMTP connection failure")
{ {
smtp.last_send_error = Some(format!("{:#}", err)); smtp.last_send_error = Some(format!("{err:#}"));
return Err(err); return Err(err);
} }
@@ -436,7 +436,7 @@ pub(crate) async fn send_msg_to_smtp(
// delete_msgs() was called before the generated mime was sent out. // delete_msgs() was called before the generated mime was sent out.
if !message::exists(context, msg_id) if !message::exists(context, msg_id)
.await .await
.with_context(|| format!("failed to check message {} existence", msg_id))? .with_context(|| format!("failed to check message {msg_id} existence"))?
{ {
info!( info!(
context, context,

View File

@@ -77,8 +77,7 @@ impl Smtp {
.map_err(Error::SmtpSend)?; .map_err(Error::SmtpSend)?;
context.emit_event(EventType::SmtpMessageSent(format!( context.emit_event(EventType::SmtpMessageSent(format!(
"Message len={} was smtp-sent to {}", "Message len={message_len_bytes} was smtp-sent to {recipients_display}"
message_len_bytes, recipients_display
))); )));
self.last_success = Some(std::time::SystemTime::now()); self.last_success = Some(std::time::SystemTime::now());
} else { } else {

View File

@@ -125,7 +125,7 @@ impl Sql {
pub(crate) async fn export(&self, path: &Path, passphrase: String) -> Result<()> { pub(crate) async fn export(&self, path: &Path, passphrase: String) -> Result<()> {
let path_str = path let path_str = path
.to_str() .to_str()
.with_context(|| format!("path {:?} is not valid unicode", path))?; .with_context(|| format!("path {path:?} is not valid unicode"))?;
let conn = self.get_conn().await?; let conn = self.get_conn().await?;
tokio::task::block_in_place(move || { tokio::task::block_in_place(move || {
conn.execute( conn.execute(
@@ -148,7 +148,7 @@ impl Sql {
pub(crate) async fn import(&self, path: &Path, passphrase: String) -> Result<()> { pub(crate) async fn import(&self, path: &Path, passphrase: String) -> Result<()> {
let path_str = path let path_str = path
.to_str() .to_str()
.with_context(|| format!("path {:?} is not valid unicode", path))?; .with_context(|| format!("path {path:?} is not valid unicode"))?;
let conn = self.get_conn().await?; let conn = self.get_conn().await?;
tokio::task::block_in_place(move || { tokio::task::block_in_place(move || {
@@ -587,7 +587,7 @@ impl Sql {
let value = self let value = self
.query_get_value("SELECT value FROM config WHERE keyname=?;", paramsv![key]) .query_get_value("SELECT value FROM config WHERE keyname=?;", paramsv![key])
.await .await
.context(format!("failed to fetch raw config: {}", key))?; .context(format!("failed to fetch raw config: {key}"))?;
lock.insert(key.to_string(), value.clone()); lock.insert(key.to_string(), value.clone());
drop(lock); drop(lock);
@@ -595,7 +595,7 @@ impl Sql {
} }
pub async fn set_raw_config_int(&self, key: &str, value: i32) -> Result<()> { pub async fn set_raw_config_int(&self, key: &str, value: i32) -> Result<()> {
self.set_raw_config(key, Some(&format!("{}", value))).await self.set_raw_config(key, Some(&format!("{value}"))).await
} }
pub async fn get_raw_config_int(&self, key: &str) -> Result<Option<i32>> { pub async fn get_raw_config_int(&self, key: &str) -> Result<Option<i32>> {
@@ -623,7 +623,7 @@ impl Sql {
} }
pub async fn set_raw_config_int64(&self, key: &str, value: i64) -> Result<()> { pub async fn set_raw_config_int64(&self, key: &str, value: i64) -> Result<()> {
self.set_raw_config(key, Some(&format!("{}", value))).await self.set_raw_config(key, Some(&format!("{value}"))).await
} }
pub async fn get_raw_config_int64(&self, key: &str) -> Result<Option<i64>> { pub async fn get_raw_config_int64(&self, key: &str) -> Result<Option<i64>> {
@@ -863,7 +863,7 @@ async fn maybe_add_from_param(
}, },
) )
.await .await
.context(format!("housekeeping: failed to add_from_param {}", query))?; .context(format!("housekeeping: failed to add_from_param {query}"))?;
Ok(()) Ok(())
} }
@@ -986,8 +986,7 @@ mod tests {
match event.typ { match event.typ {
EventType::Info(s) => assert!( EventType::Info(s) => assert!(
!s.contains("Keeping new unreferenced file"), !s.contains("Keeping new unreferenced file"),
"File {} was almost deleted, only reason it was kept is that it was created recently (as the tests don't run for a long time)", "File {s} was almost deleted, only reason it was kept is that it was created recently (as the tests don't run for a long time)"
s
), ),
EventType::Error(s) => panic!("{}", s), EventType::Error(s) => panic!("{}", s),
_ => {} _ => {}

View File

@@ -30,7 +30,7 @@ pub async fn run(context: &Context, sql: &Sql) -> Result<(bool, bool, bool, bool
// set raw config inside the transaction // set raw config inside the transaction
transaction.execute( transaction.execute(
"INSERT INTO config (keyname, value) VALUES (?, ?);", "INSERT INTO config (keyname, value) VALUES (?, ?);",
paramsv![VERSION_CFG, format!("{}", dbversion_before_update)], paramsv![VERSION_CFG, format!("{dbversion_before_update}")],
)?; )?;
Ok(()) Ok(())
}) })
@@ -40,7 +40,7 @@ pub async fn run(context: &Context, sql: &Sql) -> Result<(bool, bool, bool, bool
let mut lock = context.sql.config_cache.write().await; let mut lock = context.sql.config_cache.write().await;
lock.insert( lock.insert(
VERSION_CFG.to_string(), VERSION_CFG.to_string(),
Some(format!("{}", dbversion_before_update)), Some(format!("{dbversion_before_update}")),
); );
drop(lock); drop(lock);
} else { } else {
@@ -320,11 +320,11 @@ ALTER TABLE msgs ADD COLUMN ephemeral_timestamp INTEGER DEFAULT 0;"#,
if dbversion < 67 { if dbversion < 67 {
for prefix in &["", "configured_"] { for prefix in &["", "configured_"] {
if let Some(server_flags) = sql if let Some(server_flags) = sql
.get_raw_config_int(&format!("{}server_flags", prefix)) .get_raw_config_int(&format!("{prefix}server_flags"))
.await? .await?
{ {
let imap_socket_flags = server_flags & 0x700; let imap_socket_flags = server_flags & 0x700;
let key = &format!("{}mail_security", prefix); let key = &format!("{prefix}mail_security");
match imap_socket_flags { match imap_socket_flags {
0x100 => sql.set_raw_config_int(key, 2).await?, // STARTTLS 0x100 => sql.set_raw_config_int(key, 2).await?, // STARTTLS
0x200 => sql.set_raw_config_int(key, 1).await?, // SSL/TLS 0x200 => sql.set_raw_config_int(key, 1).await?, // SSL/TLS
@@ -332,7 +332,7 @@ ALTER TABLE msgs ADD COLUMN ephemeral_timestamp INTEGER DEFAULT 0;"#,
_ => sql.set_raw_config_int(key, 0).await?, _ => sql.set_raw_config_int(key, 0).await?,
} }
let smtp_socket_flags = server_flags & 0x70000; let smtp_socket_flags = server_flags & 0x70000;
let key = &format!("{}send_security", prefix); let key = &format!("{prefix}send_security");
match smtp_socket_flags { match smtp_socket_flags {
0x10000 => sql.set_raw_config_int(key, 2).await?, // STARTTLS 0x10000 => sql.set_raw_config_int(key, 2).await?, // STARTTLS
0x20000 => sql.set_raw_config_int(key, 1).await?, // SSL/TLS 0x20000 => sql.set_raw_config_int(key, 1).await?, // SSL/TLS
@@ -721,16 +721,16 @@ impl Sql {
// set raw config inside the transaction // set raw config inside the transaction
transaction.execute( transaction.execute(
"UPDATE config SET value=? WHERE keyname=?;", "UPDATE config SET value=? WHERE keyname=?;",
paramsv![format!("{}", version), VERSION_CFG], paramsv![format!("{version}"), VERSION_CFG],
)?; )?;
Ok(()) Ok(())
}) })
.await .await
.with_context(|| format!("execute_migration failed for version {}", version))?; .with_context(|| format!("execute_migration failed for version {version}"))?;
let mut lock = self.config_cache.write().await; let mut lock = self.config_cache.write().await;
lock.insert(VERSION_CFG.to_string(), Some(format!("{}", version))); lock.insert(VERSION_CFG.to_string(), Some(format!("{version}")));
drop(lock); drop(lock);
Ok(()) Ok(())

View File

@@ -719,10 +719,7 @@ pub(crate) async fn secure_join_started(
.replace1(&contact.get_name_n_addr()) .replace1(&contact.get_name_n_addr())
.replace2(contact.get_display_name()) .replace2(contact.get_display_name())
} else { } else {
format!( format!("secure_join_started: unknown contact {inviter_contact_id}")
"secure_join_started: unknown contact {}",
inviter_contact_id
)
} }
} }
@@ -733,7 +730,7 @@ pub(crate) async fn secure_join_replies(context: &Context, contact_id: ContactId
.await .await
.replace1(contact.get_display_name()) .replace1(contact.get_display_name())
} else { } else {
format!("secure_join_replies: unknown contact {}", contact_id) format!("secure_join_replies: unknown contact {contact_id}")
} }
} }
@@ -746,7 +743,7 @@ pub(crate) async fn setup_contact_qr_description(
let name = &if display_name == addr { let name = &if display_name == addr {
addr.to_owned() addr.to_owned()
} else { } else {
format!("{} ({})", display_name, addr) format!("{display_name} ({addr})")
}; };
translated(context, StockMessage::SetupContactQRDescription) translated(context, StockMessage::SetupContactQRDescription)
.await .await
@@ -1117,7 +1114,7 @@ pub(crate) async fn forwarded(context: &Context) -> String {
pub(crate) async fn quota_exceeding(context: &Context, highest_usage: u64) -> String { pub(crate) async fn quota_exceeding(context: &Context, highest_usage: u64) -> String {
translated(context, StockMessage::QuotaExceedingMsgBody) translated(context, StockMessage::QuotaExceedingMsgBody)
.await .await
.replace1(&format!("{}", highest_usage)) .replace1(&format!("{highest_usage}"))
.replace("%%", "%") .replace("%%", "%")
} }

View File

@@ -29,9 +29,9 @@ pub enum SummaryPrefix {
impl fmt::Display for SummaryPrefix { impl fmt::Display for SummaryPrefix {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self { match self {
SummaryPrefix::Username(username) => write!(f, "{}", username), SummaryPrefix::Username(username) => write!(f, "{username}"),
SummaryPrefix::Draft(text) => write!(f, "{}", text), SummaryPrefix::Draft(text) => write!(f, "{text}"),
SummaryPrefix::Me(text) => write!(f, "{}", text), SummaryPrefix::Me(text) => write!(f, "{text}"),
} }
} }
} }
@@ -133,7 +133,7 @@ impl Message {
} else { } else {
stock_str::file(context).await stock_str::file(context).await
}; };
format!("{} {}", label, file_name) format!("{label} {file_name}")
} }
} }
Viewtype::VideochatInvitation => { Viewtype::VideochatInvitation => {
@@ -167,7 +167,7 @@ impl Message {
} else if prefix.is_empty() { } else if prefix.is_empty() {
text.to_string() text.to_string()
} else { } else {
format!("{} {}", prefix, text) format!("{prefix} {text}")
} }
} else { } else {
prefix prefix

View File

@@ -177,7 +177,7 @@ impl Context {
Ok(None) Ok(None)
} else { } else {
Ok(Some(( Ok(Some((
format!("{{\"items\":[\n{}\n]}}", serialized), format!("{{\"items\":[\n{serialized}\n]}}"),
ids.iter() ids.iter()
.map(|x| x.to_string()) .map(|x| x.to_string())
.collect::<Vec<String>>() .collect::<Vec<String>>()
@@ -200,7 +200,7 @@ impl Context {
pub(crate) async fn delete_sync_ids(&self, ids: String) -> Result<()> { pub(crate) async fn delete_sync_ids(&self, ids: String) -> Result<()> {
self.sql self.sql
.execute( .execute(
&format!("DELETE FROM multi_device_sync WHERE id IN ({});", ids), &format!("DELETE FROM multi_device_sync WHERE id IN ({ids});"),
paramsv![], paramsv![],
) )
.await?; .await?;

View File

@@ -656,7 +656,7 @@ impl TestContext {
}, },
match sel_chat.get_profile_image(self).await.unwrap() { match sel_chat.get_profile_image(self).await.unwrap() {
Some(icon) => match icon.to_str() { Some(icon) => match icon.to_str() {
Some(icon) => format!(" Icon: {}", icon), Some(icon) => format!(" Icon: {icon}"),
_ => " Icon: Err".to_string(), _ => " Icon: Err".to_string(),
}, },
_ => "".to_string(), _ => "".to_string(),
@@ -931,7 +931,7 @@ pub(crate) async fn get_chat_msg(
fn print_logevent(logevent: &LogEvent) { fn print_logevent(logevent: &LogEvent) {
match logevent { match logevent {
LogEvent::Event(event) => print_event(event), LogEvent::Event(event) => print_event(event),
LogEvent::Section(msg) => println!("\n========== {} ==========", msg), LogEvent::Section(msg) => println!("\n========== {msg} =========="),
} }
} }
@@ -944,60 +944,57 @@ fn print_event(event: &Event) {
let red = Color::Red.normal(); let red = Color::Red.normal();
let msg = match &event.typ { let msg = match &event.typ {
EventType::Info(msg) => format!("INFO: {}", msg), EventType::Info(msg) => format!("INFO: {msg}"),
EventType::SmtpConnected(msg) => format!("[SMTP_CONNECTED] {}", msg), EventType::SmtpConnected(msg) => format!("[SMTP_CONNECTED] {msg}"),
EventType::ImapConnected(msg) => format!("[IMAP_CONNECTED] {}", msg), EventType::ImapConnected(msg) => format!("[IMAP_CONNECTED] {msg}"),
EventType::SmtpMessageSent(msg) => format!("[SMTP_MESSAGE_SENT] {}", msg), EventType::SmtpMessageSent(msg) => format!("[SMTP_MESSAGE_SENT] {msg}"),
EventType::Warning(msg) => format!("WARN: {}", yellow.paint(msg)), EventType::Warning(msg) => format!("WARN: {}", yellow.paint(msg)),
EventType::Error(msg) => format!("ERROR: {}", red.paint(msg)), EventType::Error(msg) => format!("ERROR: {}", red.paint(msg)),
EventType::ErrorSelfNotInGroup(msg) => { EventType::ErrorSelfNotInGroup(msg) => {
format!("{}", red.paint(format!("[SELF_NOT_IN_GROUP] {}", msg))) format!("{}", red.paint(format!("[SELF_NOT_IN_GROUP] {msg}")))
} }
EventType::MsgsChanged { chat_id, msg_id } => format!( EventType::MsgsChanged { chat_id, msg_id } => format!(
"{}", "{}",
green.paint(format!( green.paint(format!(
"Received MSGS_CHANGED(chat_id={}, msg_id={})", "Received MSGS_CHANGED(chat_id={chat_id}, msg_id={msg_id})",
chat_id, msg_id,
)) ))
), ),
EventType::ContactsChanged(_) => format!("{}", green.paint("Received CONTACTS_CHANGED()")), EventType::ContactsChanged(_) => format!("{}", green.paint("Received CONTACTS_CHANGED()")),
EventType::LocationChanged(contact) => format!( EventType::LocationChanged(contact) => format!(
"{}", "{}",
green.paint(format!("Received LOCATION_CHANGED(contact={:?})", contact)) green.paint(format!("Received LOCATION_CHANGED(contact={contact:?})"))
), ),
EventType::ConfigureProgress { progress, comment } => { EventType::ConfigureProgress { progress, comment } => {
if let Some(comment) = comment { if let Some(comment) = comment {
format!( format!(
"{}", "{}",
green.paint(format!( green.paint(format!(
"Received CONFIGURE_PROGRESS({} ‰, {})", "Received CONFIGURE_PROGRESS({progress} ‰, {comment})"
progress, comment
)) ))
) )
} else { } else {
format!( format!(
"{}", "{}",
green.paint(format!("Received CONFIGURE_PROGRESS({} ‰)", progress)) green.paint(format!("Received CONFIGURE_PROGRESS({progress} ‰)"))
) )
} }
} }
EventType::ImexProgress(progress) => format!( EventType::ImexProgress(progress) => format!(
"{}", "{}",
green.paint(format!("Received IMEX_PROGRESS({} ‰)", progress)) green.paint(format!("Received IMEX_PROGRESS({progress} ‰)"))
), ),
EventType::ImexFileWritten(file) => format!( EventType::ImexFileWritten(file) => format!(
"{}", "{}",
green.paint(format!("Received IMEX_FILE_WRITTEN({})", file.display())) green.paint(format!("Received IMEX_FILE_WRITTEN({})", file.display()))
), ),
EventType::ChatModified(chat) => format!( EventType::ChatModified(chat) => {
"{}", format!("{}", green.paint(format!("Received CHAT_MODIFIED({chat})")))
green.paint(format!("Received CHAT_MODIFIED({})", chat)) }
), _ => format!("Received {event:?}"),
_ => format!("Received {:?}", event),
}; };
let context_names = CONTEXT_NAMES.read().unwrap(); let context_names = CONTEXT_NAMES.read().unwrap();
match context_names.get(&event.id) { match context_names.get(&event.id) {
Some(name) => println!("{} {}", name, msg), Some(name) => println!("{name} {msg}"),
None => println!("{} {}", event.id, msg), None => println!("{} {}", event.id, msg),
} }
} }
@@ -1009,7 +1006,7 @@ async fn log_msg(context: &Context, prefix: &str, msg: &Message) {
let contact = match Contact::get_by_id(context, msg.get_from_id()).await { let contact = match Contact::get_by_id(context, msg.get_from_id()).await {
Ok(contact) => contact, Ok(contact) => contact,
Err(e) => { Err(e) => {
println!("Can't log message: invalid contact: {}", e); println!("Can't log message: invalid contact: {e}");
return; return;
} }
}; };

View File

@@ -295,7 +295,7 @@ async fn check_that_transition_worked(
assert_eq!(info_msg.text.unwrap(), expected_text); assert_eq!(info_msg.text.unwrap(), expected_text);
assert_eq!(info_msg.from_id, ContactId::INFO); assert_eq!(info_msg.from_id, ContactId::INFO);
let msg = format!("Sending to group {}", group); let msg = format!("Sending to group {group}");
let sent = bob.send_text(*group, &msg).await; let sent = bob.send_text(*group, &msg).await;
let recvd = alice.recv_msg(&sent).await; let recvd = alice.recv_msg(&sent).await;
assert_eq!(recvd.text.unwrap(), msg); assert_eq!(recvd.text.unwrap(), msg);
@@ -326,8 +326,7 @@ async fn check_no_transition_done(groups: &[ChatId], old_alice_addr: &str, bob:
let last_info_msg = get_last_info_msg(bob, *group).await; let last_info_msg = get_last_info_msg(bob, *group).await;
assert!( assert!(
last_info_msg.is_none(), last_info_msg.is_none(),
"{:?} shouldn't be there (or it's an unrelated info msg)", "{last_info_msg:?} shouldn't be there (or it's an unrelated info msg)"
last_info_msg
); );
} }
} }

View File

@@ -95,7 +95,7 @@ pub(crate) fn truncate_by_lines(
}; };
if let Some(truncated_text) = text { if let Some(truncated_text) = text {
(format!("{}{}", truncated_text, DC_ELLIPSIS), true) (format!("{truncated_text}{DC_ELLIPSIS}"), true)
} else { } else {
// In case of indexing/slicing error, we return an error // In case of indexing/slicing error, we return an error
// message as a preview and add HTML version. This should // message as a preview and add HTML version. This should
@@ -128,7 +128,7 @@ pub fn duration_to_str(duration: Duration) -> String {
let h = secs / 3600; let h = secs / 3600;
let m = (secs % 3600) / 60; let m = (secs % 3600) / 60;
let s = (secs % 3600) % 60; let s = (secs % 3600) % 60;
format!("{}h {}m {}s", h, m, s) format!("{h}h {m}m {s}s")
} }
pub(crate) fn gm2local_offset() -> i64 { pub(crate) fn gm2local_offset() -> i64 {
@@ -383,7 +383,7 @@ pub(crate) async fn delete_file(context: &Context, path: impl AsRef<Path>) -> Re
let dpath = format!("{}", path.to_string_lossy()); let dpath = format!("{}", path.to_string_lossy());
fs::remove_file(path_abs) fs::remove_file(path_abs)
.await .await
.with_context(|| format!("cannot delete {:?}", dpath))?; .with_context(|| format!("cannot delete {dpath:?}"))?;
context.emit_event(EventType::DeletedBlobFile(dpath)); context.emit_event(EventType::DeletedBlobFile(dpath));
Ok(()) Ok(())
} }

View File

@@ -596,7 +596,7 @@ impl Context {
}, },
) )
.await?; .await?;
Ok(format!("[{}]", json)) Ok(format!("[{json}]"))
} }
/// Renders JSON-object for status updates as used on the wire. /// Renders JSON-object for status updates as used on the wire.
@@ -634,7 +634,7 @@ impl Context {
if json.is_empty() { if json.is_empty() {
Ok(None) Ok(None)
} else { } else {
Ok(Some(format!(r#"{{"updates":[{}]}}"#, json))) Ok(Some(format!(r#"{{"updates":[{json}]}}"#)))
} }
} }
} }