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_camel_case_types,
clippy::missing_safety_doc,
clippy::expect_fun_call,
clippy::uninlined_format_args
clippy::expect_fun_call
)]
#[macro_use]
@@ -116,7 +115,7 @@ pub unsafe extern "C" fn dc_context_new(
match ctx {
Ok(ctx) => Box::into_raw(Box::new(ctx)),
Err(err) => {
eprintln!("failed to create context: {:#}", err);
eprintln!("failed to create context: {err:#}");
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)),
Err(err) => {
eprintln!("failed to create context: {:#}", err);
eprintln!("failed to create context: {err:#}");
ptr::null_mut()
}
}
@@ -215,7 +214,7 @@ pub unsafe extern "C" fn dc_set_config(
if key.starts_with("ui.") {
ctx.set_ui_config(&key, value.as_deref())
.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")
.is_ok() as libc::c_int
} else {
@@ -223,7 +222,7 @@ pub unsafe extern "C" fn dc_set_config(
Ok(key) => ctx
.set_config(key, value.as_deref())
.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")
.is_ok() as libc::c_int,
Err(_) => {
@@ -350,7 +349,7 @@ fn render_info(
) -> std::result::Result<String, std::fmt::Error> {
let mut res = String::new();
for (key, value) in &info {
writeln!(&mut res, "{}={}", key, value)?;
writeln!(&mut res, "{key}={value}")?;
}
Ok(res)
@@ -1286,11 +1285,11 @@ pub unsafe extern "C" fn dc_get_chat_media(
} else {
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 =
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 =
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 {
Box::into_raw(Box::new(
@@ -1322,11 +1321,11 @@ pub unsafe extern "C" fn dc_get_next_media(
};
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 =
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 =
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 {
chat::get_next_media(
@@ -2186,7 +2185,7 @@ pub unsafe extern "C" fn dc_imex(
let what = match imex::ImexMode::from_i32(what_raw) {
Some(what) => what,
None => {
eprintln!("ignoring invalid argument {} to dc_imex", what_raw);
eprintln!("ignoring invalid argument {what_raw} to dc_imex");
return;
}
};
@@ -3074,7 +3073,7 @@ pub unsafe extern "C" fn dc_msg_new(
return ptr::null_mut();
}
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 {
context,
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
}
Err(err) => {
eprintln!("failed read blob from archive: {}", err);
eprintln!("failed read blob from archive: {err}");
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))),
Err(err) => {
// 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()
}
}
@@ -4378,8 +4377,7 @@ pub unsafe extern "C" fn dc_accounts_select_account(
Ok(()) => 1,
Err(err) => {
accounts.emit_event(EventType::Error(format!(
"Failed to select account: {:#}",
err
"Failed to select account: {err:#}"
)));
0
}
@@ -4401,10 +4399,7 @@ pub unsafe extern "C" fn dc_accounts_add_account(accounts: *mut dc_accounts_t) -
match accounts.add_account().await {
Ok(id) => id,
Err(err) => {
accounts.emit_event(EventType::Error(format!(
"Failed to add account: {:#}",
err
)));
accounts.emit_event(EventType::Error(format!("Failed to add account: {err:#}")));
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 {
Ok(id) => id,
Err(err) => {
accounts.emit_event(EventType::Error(format!(
"Failed to add account: {:#}",
err
)));
accounts.emit_event(EventType::Error(format!("Failed to add account: {err:#}")));
0
}
}
@@ -4453,8 +4445,7 @@ pub unsafe extern "C" fn dc_accounts_remove_account(
Ok(()) => 1,
Err(err) => {
accounts.emit_event(EventType::Error(format!(
"Failed to remove account: {:#}",
err
"Failed to remove account: {err:#}"
)));
0
}
@@ -4484,8 +4475,7 @@ pub unsafe extern "C" fn dc_accounts_migrate_account(
Ok(id) => id,
Err(err) => {
accounts.emit_event(EventType::Error(format!(
"Failed to migrate account: {:#}",
err
"Failed to migrate account: {err:#}"
)));
0
}

View File

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

View File

@@ -10,7 +10,7 @@ pub mod reactions;
pub mod webxdc;
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> {

View File

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

View File

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

View File

@@ -31,7 +31,7 @@ use tokio::fs;
/// 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.
async fn reset_tables(context: &Context, bits: i32) {
println!("Resetting tables ({})...", bits);
println!("Resetting tables ({bits})...");
if 0 != bits & 1 {
context
.sql()
@@ -101,7 +101,7 @@ async fn poke_eml_file(context: &Context, filename: impl AsRef<Path>) -> Result<
let data = read_file(context, filename).await?;
if let Err(err) = receive_imf(context, &data, false).await {
println!("receive_imf errored: {:?}", err);
println!("receive_imf errored: {err:?}");
}
Ok(())
}
@@ -148,7 +148,7 @@ async fn poke_spec(context: &Context, spec: Option<&str>) -> bool {
let name = name_f.to_string_lossy();
if name.ends_with(".eml") {
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() {
read_cnt += 1
}
@@ -168,7 +168,7 @@ async fn log_msg(context: &Context, prefix: impl AsRef<str>, msg: &Message) {
.await
.expect("invalid contact");
let contact_name = if let Some(name) = msg.get_override_sender_name() {
format!("~{}", name)
format!("~{name}")
} else {
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={}]",
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 {
"".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 {
Ok(setup_code) => println!(
"Setup code for the transferred setup message: {}",
setup_code,
),
Ok(setup_code) => {
println!("Setup code for the transferred setup message: {setup_code}",)
}
Err(err) => bail!("Failed to generate setup code: {}", err),
},
"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.");
let key = config::Config::from_str(arg1)?;
let val = context.get_config(key).await;
println!("{}={:?}", key, val);
println!("{key}={val:?}");
}
"info" => {
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 {
Ok(html) => {
fs::write(&file, html).await?;
println!("Report written to: {:#?}", file);
println!("Report written to: {file:#?}");
}
Err(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
.prefix
.map_or_else(String::new, |prefix| format!("{}: ", prefix)),
.map_or_else(String::new, |prefix| format!("{prefix}: ")),
summary.text,
statestr,
&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? {
println!("Location streaming enabled.");
}
println!("{} chats", cnt);
println!("{:?} to create this list", time_needed);
println!("{cnt} chats");
println!("{time_needed:?} to create this list");
}
"chat" => {
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() {
let id = ChatId::new(arg1.parse()?);
println!("Selecting chat {}", id);
println!("Selecting chat {id}");
sel_chat = Some(Chat::load_from_db(&context, id).await?);
*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? {
Some(icon) => match icon.to_str() {
Some(icon) => format!(" Icon: {}", icon),
Some(icon) => format!(" Icon: {icon}"),
_ => " Icon: Err".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();
println!(
"{:?} to create this list, {:?} to mark all messages as noticed.",
time_needed, time_noticed_needed
"{time_needed:?} to create this list, {time_noticed_needed:?} to mark all messages as noticed."
);
}
"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 chat_id = ChatId::create_for_contact(&context, contact_id).await?;
println!("Single#{} created successfully.", chat_id,);
println!("Single#{chat_id} created successfully.",);
}
"creategroup" => {
ensure!(!arg1.is_empty(), "Argument <name> missing.");
let chat_id =
chat::create_group_chat(&context, ProtectionStatus::Unprotected, arg1).await?;
println!("Group#{} created successfully.", chat_id);
println!("Group#{chat_id} created successfully.");
}
"createbroadcast" => {
let chat_id = chat::create_broadcast_list(&context).await?;
println!("Broadcast#{} created successfully.", chat_id);
println!("Broadcast#{chat_id} created successfully.");
}
"createprotected" => {
ensure!(!arg1.is_empty(), "Argument <name> missing.");
let chat_id =
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" => {
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(
&context,
sel_chat.as_ref().unwrap().get_id(),
format!("{} {}", arg1, arg2).trim(),
format!("{arg1} {arg2}").trim(),
)
.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!(!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?;
}
@@ -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?;
}
"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."),
},
"sendupdate" => {
@@ -936,7 +934,7 @@ pub async fn cmdline(context: Context, line: &str, chat_id: &mut ChatId) -> Resu
"listmsgs" => {
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 time_start = std::time::SystemTime::now();
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,
);
println!("{:?} to create this list", time_needed);
println!("{time_needed:?} to create this list");
}
"draft" => {
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());
for (i, data) in images.iter().enumerate() {
if 0 == i {
print!("{}", data);
print!("{data}");
} else {
print!(", {}", data);
print!(", {data}");
}
}
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.");
let id = MsgId::new(arg1.parse()?);
let res = message::get_msg_info(&context, id).await?;
println!("{}", res);
println!("{res}");
}
"download" => {
ensure!(!arg1.is_empty(), "Argument <msg-id> missing.");
let id = MsgId::new(arg1.parse()?);
println!("Scheduling download for {:?}", id);
println!("Scheduling download for {id:?}");
id.download_full(&context).await?;
}
"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()));
let html = id.get_html(&context).await?.unwrap_or_default();
fs::write(&file, html).await?;
println!("HTML written to: {:#?}", file);
println!("HTML written to: {file:#?}");
}
"listfresh" => {
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.");
if !arg2.is_empty() {
let book = format!("{}\n{}", arg1, arg2);
let book = format!("{arg1}\n{arg2}");
Contact::add_address_book(&context, &book).await?;
} else {
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_cnt = chatlist.len();
if chatlist_cnt > 0 {
res += &format!(
"\n\n{} chats shared with Contact#{}: ",
chatlist_cnt, contact_id,
);
res += &format!("\n\n{chatlist_cnt} chats shared with Contact#{contact_id}: ",);
for i in 0..chatlist_cnt {
if 0 != i {
res += ", ";
@@ -1191,7 +1186,7 @@ pub async fn cmdline(context: Context, line: &str, chat_id: &mut ChatId) -> Resu
}
}
println!("{}", res);
println!("{res}");
}
"delcontact" => {
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" => {
ensure!(!arg1.is_empty(), "Argument <qr-content> missing.");
let qr = check_qr(&context, arg1).await?;
println!("qr={:?}", qr);
println!("qr={qr:?}");
}
"setqr" => {
ensure!(!arg1.is_empty(), "Argument <qr-content> missing.");
match set_config_from_qr(&context, arg1).await {
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" => {
@@ -1231,7 +1226,7 @@ pub async fn cmdline(context: Context, line: &str, chat_id: &mut ChatId) -> Resu
.await?;
match provider::get_provider_info(&context, arg1, socks5_enabled).await {
Some(info) => {
println!("Information for provider belonging to {}:", arg1);
println!("Information for provider belonging to {arg1}:");
println!("status: {}", info.status as u32);
println!("before_login_hint: {}", info.before_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 => {
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 {
let (width, height) = get_filemeta(&buf)?;
println!("width={}, height={}", width, height);
println!("width={width}, height={height}");
} else {
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 server_cnt = message::estimate_deletion_cnt(&context, true, seconds).await?;
println!(
"estimated count of messages older than {} seconds:\non device: {}\non server: {}",
seconds, device_cnt, server_cnt
"estimated count of messages older than {seconds} seconds:\non device: {device_cnt}\non server: {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
//! included when using Delta Chat Core as a library.
//!
@@ -68,8 +67,7 @@ fn receive_event(event: EventType) {
info!(
"{}",
yellow.paint(format!(
"Received MSGS_CHANGED(chat_id={}, msg_id={})",
chat_id, msg_id,
"Received MSGS_CHANGED(chat_id={chat_id}, msg_id={msg_id})",
))
);
}
@@ -81,8 +79,7 @@ fn receive_event(event: EventType) {
info!(
"{}",
yellow.paint(format!(
"Received REACTIONS_CHANGED(chat_id={}, msg_id={}, contact_id={})",
chat_id, msg_id, contact_id
"Received REACTIONS_CHANGED(chat_id={chat_id}, msg_id={msg_id}, contact_id={contact_id})"
))
);
}
@@ -92,7 +89,7 @@ fn receive_event(event: EventType) {
EventType::LocationChanged(contact) => {
info!(
"{}",
yellow.paint(format!("Received LOCATION_CHANGED(contact={:?})", contact))
yellow.paint(format!("Received LOCATION_CHANGED(contact={contact:?})"))
);
}
EventType::ConfigureProgress { progress, comment } => {
@@ -100,21 +97,20 @@ fn receive_event(event: EventType) {
info!(
"{}",
yellow.paint(format!(
"Received CONFIGURE_PROGRESS({} ‰, {})",
progress, comment
"Received CONFIGURE_PROGRESS({progress} ‰, {comment})"
))
);
} else {
info!(
"{}",
yellow.paint(format!("Received CONFIGURE_PROGRESS({} ‰)", progress))
yellow.paint(format!("Received CONFIGURE_PROGRESS({progress} ‰)"))
);
}
}
EventType::ImexProgress(progress) => {
info!(
"{}",
yellow.paint(format!("Received IMEX_PROGRESS({} ‰)", progress))
yellow.paint(format!("Received IMEX_PROGRESS({progress} ‰)"))
);
}
EventType::ImexFileWritten(file) => {
@@ -126,7 +122,7 @@ fn receive_event(event: EventType) {
EventType::ChatModified(chat) => {
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
}
Err(err) => {
println!("Error: {}", err);
println!("Error: {err}");
true
}
}
@@ -378,7 +374,7 @@ async fn start(args: Vec<String>) -> Result<(), Error> {
break;
}
Err(err) => {
println!("Error: {}", err);
println!("Error: {err}");
break;
}
}
@@ -445,7 +441,7 @@ async fn handle_cmd(
if arg0 == "getbadqr" && qr.len() > 40 {
qr.replace_range(12..22, "0000000000")
}
println!("{}", qr);
println!("{qr}");
let output = Command::new("qrencode")
.args(["-t", "ansiutf8", qr.as_str(), "-o", "-"])
.output()
@@ -461,7 +457,7 @@ async fn handle_cmd(
match get_securejoin_qr_svg(&ctx, group).await {
Ok(svg) => {
fs::write(&file, svg).await?;
println!("QR code svg written to: {:#?}", file);
println!("QR code svg written to: {file:#?}");
}
Err(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::chatlist::*;
use deltachat::config;
@@ -75,7 +74,7 @@ async fn main() {
for i in 0..1 {
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
.unwrap();
}

View File

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

View File

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

View File

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

View File

@@ -908,11 +908,10 @@ impl ChatId {
{
let sql = &context.sql;
let query = format!(
"SELECT {} \
"SELECT {fields} \
FROM msgs WHERE chat_id=? AND state NOT IN (?, ?, ?, ?) AND NOT hidden \
ORDER BY timestamp DESC, id DESC \
LIMIT 1;",
fields
LIMIT 1;"
);
let row = sql
.query_row_optional(
@@ -993,9 +992,9 @@ impl ChatId {
})
.map(|peerstate| peerstate.prefer_encrypt)
{
Some(EncryptPreference::Mutual) => ret_mutual += &format!("{}\n", addr),
Some(EncryptPreference::NoPreference) => ret_nopreference += &format!("{}\n", addr),
Some(EncryptPreference::Reset) | None => ret_reset += &format!("{}\n", addr),
Some(EncryptPreference::Mutual) => ret_mutual += &format!("{addr}\n"),
Some(EncryptPreference::NoPreference) => ret_nopreference += &format!("{addr}\n"),
Some(EncryptPreference::Reset) | None => ret_reset += &format!("{addr}\n"),
};
}
@@ -1171,7 +1170,7 @@ impl Chat {
},
)
.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() {
chat.name = stock_str::archived_chats(context).await;
@@ -1491,11 +1490,11 @@ impl Chat {
if !parent_references.is_empty() && !parent_rfc724_mid.is_empty() {
// 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() {
new_references = parent_references.to_string();
} 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() {
new_references = parent_in_reply_to;
} 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;
for attempt in 1..1000 {
let better_name = if attempt > 1 {
format!("{} {}", base_name, attempt)
format!("{base_name} {attempt}")
} else {
base_name.clone()
};
@@ -3065,7 +3064,7 @@ pub async fn set_muted(context: &Context, chat_id: ChatId, duration: MuteDuratio
paramsv![duration, chat_id],
)
.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));
Ok(())
}
@@ -4498,12 +4497,11 @@ mod tests {
format!(
"From: bob@example.net\n\
To: alice@example.org\n\
Message-ID: <{}@example.org>\n\
Message-ID: <{num}@example.org>\n\
Chat-Version: 1.0\n\
Date: Sun, 22 Mar 2022 19:37:57 +0000\n\
\n\
hello\n",
num
hello\n"
)
.as_bytes(),
false,
@@ -4579,14 +4577,13 @@ mod tests {
receive_imf(
t,
format!(
"From: {}@example.net\n\
"From: {name}@example.net\n\
To: alice@example.org\n\
Message-ID: <{}@example.org>\n\
Message-ID: <{num}@example.org>\n\
Chat-Version: 1.0\n\
Date: Sun, 22 Mar 2022 19:37:57 +0000\n\
\n\
hello\n",
name, num
hello\n"
)
.as_bytes(),
false,
@@ -4793,7 +4790,7 @@ mod tests {
let chat_id = ChatId::create_for_contact(&context.ctx, contact1)
.await
.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 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)
}
let str_like_cmd = format!("%{}%", query);
let str_like_cmd = format!("%{query}%");
context
.sql
.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 {
format!("{:#08x}", color).replace("0x", "#")
format!("{color:#08x}").replace("0x", "#")
}
#[cfg(test)]

View File

@@ -277,7 +277,7 @@ impl Context {
rel_path.map(|p| get_abs_path(self, p).to_string_lossy().into_owned())
}
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()),
_ => self.sql.get_raw_config(key.as_ref()).await?,
};
@@ -505,7 +505,7 @@ fn get_config_keys_string() -> String {
acc
});
format!(" {} ", keys)
format!(" {keys} ")
}
#[cfg(test)]

View File

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

View File

@@ -961,7 +961,7 @@ impl Contact {
};
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)
.await?
@@ -1499,7 +1499,7 @@ fn cat_fingerprint(
&& !fingerprint_unverified.is_empty()
&& 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?;
let fingerprint_str = match SignedPublicKey::load_self(self).await {
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?;
@@ -658,7 +658,7 @@ impl Context {
res.insert("used_account_settings", l2.to_string());
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);
@@ -808,7 +808,7 @@ impl Context {
if real_query.is_empty() {
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| {
self.sql.query_map(
@@ -964,7 +964,7 @@ mod tests {
contact.get_addr(),
create_outgoing_rfc724_mid(None, contact.get_addr())
);
println!("{}", msg);
println!("{msg}");
receive_imf(t, msg.as_bytes(), false).await.unwrap();
}
@@ -1191,8 +1191,7 @@ mod tests {
{
assert!(
info.contains_key(&*key),
"'{}' missing in get_info() output",
key
"'{key}' missing in get_info() output"
);
}
}

View File

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

View File

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

View File

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

View File

@@ -78,7 +78,7 @@ impl EncryptHelper {
};
}
None => {
let msg = format!("peerstate for {:?} missing, cannot encrypt", addr);
let msg = format!("peerstate for {addr:?} missing, cannot encrypt");
if e2ee_guaranteed {
return Err(format_err!("{}", msg));
} else {
@@ -112,7 +112,7 @@ impl EncryptHelper {
{
let key = peerstate
.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(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])
.await
.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
.replace_all(
&self.html,
format!("${{1}}{}${{3}}", replacement).as_str(),
format!("${{1}}{replacement}${{3}}").as_str(),
)
.as_ref()
.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.has_html());
let html = msg.get_id().get_html(&t).await?.unwrap();
println!("{}", html);
println!("{html}");
assert!(html.contains("foo bar ä ö ü ß"));
Ok(())
}

View File

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

View File

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

View File

@@ -22,7 +22,7 @@ pub enum Error {
impl From<anyhow::Error> for Error {
fn from(err: anyhow::Error) -> Error {
Error::Other(format!("{:#}", err))
Error::Other(format!("{err:#}"))
}
}
@@ -111,12 +111,12 @@ impl ImapSession {
Error::NoFolder(..) => {
info!(context, "Failed to select folder {} because it does not exist, trying to create it.", folder);
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
for i in 0..64 {
let mut tempdbfile = folder.clone();
tempdbfile.push(format!("{}-{:02}.db", stem, i));
tempdbfile.push(format!("{stem}-{i:02}.db"));
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();
destfile.push(format!("{}-{:02}.tar", stem, i));
destfile.push(format!("{stem}-{i:02}.tar"));
if !tempdbfile.exists() && !tempfile.exists() && !destfile.exists() {
return Ok((tempdbfile, tempfile, destfile));
@@ -540,7 +540,7 @@ async fn export_backup(context: &Context, dir: &Path, passphrase: String) -> Res
.sql
.export(&temp_db_path, passphrase)
.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;
@@ -824,7 +824,7 @@ mod tests {
.await
.is_ok());
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();
assert_eq!(bytes, key.to_asc(None).into_bytes());
@@ -839,7 +839,7 @@ mod tests {
.await
.is_ok());
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();
assert_eq!(bytes, key.to_asc(None).into_bytes());
@@ -850,12 +850,12 @@ mod tests {
let context = TestContext::new_alice().await;
let blobdir = context.ctx.get_blobdir();
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;
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
.execute("DELETE FROM jobs WHERE id=?;", paramsv![id])
.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 {
write!(f, " ")?;
}
write!(f, "{}", c)?;
write!(f, "{c}")?;
}
Ok(())
}

View File

@@ -15,7 +15,6 @@
clippy::unused_async
)]
#![allow(
clippy::uninlined_format_args,
clippy::match_bool,
clippy::mixed_read_write_in_expression,
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 {
ret += &format!(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
<kml xmlns=\"http://www.opengis.net/kml/2.2\">\n<Document addr=\"{}\">\n",
self_addr,
<kml xmlns=\"http://www.opengis.net/kml/2.2\">\n<Document addr=\"{self_addr}\">\n",
);
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?;
ret += &format!(
"<Placemark>\
<Timestamp><when>{}</when></Timestamp>\
<Point><coordinates accuracy=\"{}\">{},{}</coordinates></Point>\
</Placemark>\n",
timestamp, accuracy, longitude, latitude
<Timestamp><when>{timestamp}</when></Timestamp>\
<Point><coordinates accuracy=\"{accuracy}\">{longitude},{latitude}</coordinates></Point>\
</Placemark>\n"
);
location_count += 1;
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> {
let sql = &context.sql;
let key = &format!("{}addr", prefix);
let key = &format!("{prefix}addr");
let addr = sql
.get_raw_config(key)
.await?
@@ -100,26 +100,26 @@ impl LoginParam {
.trim()
.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 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 key = &format!("{}mail_user", prefix);
let key = &format!("{prefix}mail_user");
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 key = &format!("{}mail_security", prefix);
let key = &format!("{prefix}mail_security");
let mail_security = sql
.get_raw_config_int(key)
.await?
.and_then(num_traits::FromPrimitive::from_i32)
.unwrap_or_default();
let key = &format!("{}imap_certificate_checks", prefix);
let key = &format!("{prefix}imap_certificate_checks");
let imap_certificate_checks =
if let Some(certificate_checks) = sql.get_raw_config_int(key).await? {
num_traits::FromPrimitive::from_i32(certificate_checks).unwrap()
@@ -127,26 +127,26 @@ impl LoginParam {
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 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 key = &format!("{}send_user", prefix);
let key = &format!("{prefix}send_user");
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 key = &format!("{}send_security", prefix);
let key = &format!("{prefix}send_security");
let send_security = sql
.get_raw_config_int(key)
.await?
.and_then(num_traits::FromPrimitive::from_i32)
.unwrap_or_default();
let key = &format!("{}smtp_certificate_checks", prefix);
let key = &format!("{prefix}smtp_certificate_checks");
let smtp_certificate_checks =
if let Some(certificate_checks) = sql.get_raw_config_int(key).await? {
num_traits::FromPrimitive::from_i32(certificate_checks).unwrap_or_default()
@@ -154,11 +154,11 @@ impl LoginParam {
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 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
.get_raw_config(key)
.await?
@@ -198,50 +198,50 @@ impl LoginParam {
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?;
let key = &format!("{}mail_port", prefix);
let key = &format!("{prefix}mail_port");
sql.set_raw_config_int(key, i32::from(self.imap.port))
.await?;
let key = &format!("{}mail_user", prefix);
let key = &format!("{prefix}mail_user");
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?;
let key = &format!("{}mail_security", prefix);
let key = &format!("{prefix}mail_security");
sql.set_raw_config_int(key, self.imap.security as i32)
.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)
.await?;
let key = &format!("{}send_server", prefix);
let key = &format!("{prefix}send_server");
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))
.await?;
let key = &format!("{}send_user", prefix);
let key = &format!("{prefix}send_user");
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?;
let key = &format!("{}send_security", prefix);
let key = &format!("{prefix}send_security");
sql.set_raw_config_int(key, self.smtp.security as i32)
.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)
.await?;
// 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 {
true => DC_LP_AUTH_OAUTH2,
false => DC_LP_AUTH_NORMAL,
@@ -249,7 +249,7 @@ impl LoginParam {
sql.set_raw_config_int(key, server_flags).await?;
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?;
}

View File

@@ -706,7 +706,7 @@ impl Message {
// make sure, there is a scheme in the url
if !url.contains(':') {
url = format!("https://{}", url);
url = format!("https://{url}");
}
// add/replace room
@@ -731,13 +731,13 @@ impl Message {
} else {
"/"
};
format!("{}{}{}", url, maybe_slash, room)
format!("{url}{maybe_slash}{room}")
};
// re-add and normalize type
match videochat_type {
VideochatType::BasicWebrtc => format!("basicwebrtc:{}", url),
VideochatType::Jitsi => format!("jitsi:{}", url),
VideochatType::BasicWebrtc => format!("basicwebrtc:{url}"),
VideochatType::Jitsi => format!("jitsi:{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();
if rawtxt.is_none() {
ret += &format!("Cannot load message {}.", msg_id);
ret += &format!("Cannot load message {msg_id}.");
return Ok(ret);
}
let rawtxt = rawtxt.unwrap_or_default();
let rawtxt = truncate(rawtxt.trim(), DC_DESIRED_TEXT_LEN);
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)
.await
.map(|contact| contact.get_name_n_addr())
.unwrap_or_default();
ret += &format!(" by {}", name);
ret += &format!(" by {name}");
ret += "\n";
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 {
ret += &format!("Ephemeral timer: {}\n", duration);
ret += &format!("Ephemeral timer: {duration}\n");
}
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 {
let fts = timestamp_to_str(ts);
ret += &format!("Read: {}", fts);
ret += &format!("Read: {fts}");
let name = Contact::load_from_db(context, contact_id)
.await
.map(|contact| contact.get_name_n_addr())
.unwrap_or_default();
ret += &format!(" by {}", name);
ret += &format!(" by {name}");
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?;
if !reactions.is_empty() {
ret += &format!("Reactions: {}\n", reactions);
ret += &format!("Reactions: {reactions}\n");
}
if let Some(error) = msg.error.as_ref() {
ret += &format!("Error: {}", error);
ret += &format!("Error: {error}");
}
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 h = msg.param.get_int(Param::Height).unwrap_or_default();
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();
if duration != 0 {
ret += &format!("Duration: {} ms\n", duration,);
ret += &format!("Duration: {duration} ms\n",);
}
if !rawtxt.is_empty() {
ret += &format!("\n{}\n", rawtxt);
ret += &format!("\n{rawtxt}\n");
}
if !msg.rfc724_mid.is_empty() {
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 {
// 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
@@ -1364,7 +1364,7 @@ pub async fn delete_msgs(context: &Context, msg_ids: &[MsgId]) -> Result<()> {
msg_id
.trash(context)
.await
.with_context(|| format!("Unable to trash message {}", msg_id))?;
.with_context(|| format!("Unable to trash message {msg_id}"))?;
if msg.viewtype == Viewtype::Webxdc {
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 {
error
} else if let Some(failed_recipient) = &failed.failed_recipient {
format!("Delivery to {} failed.", failed_recipient).clone()
format!("Delivery to {failed_recipient} failed.").clone()
} else {
"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(
"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
@@ -1234,7 +1234,7 @@ impl<'a> MimeFactory<'a> {
Some(path) => match build_selfavatar_file(context, &path).await {
Ok(avatar) => headers.hidden.push(Header::new(
"Chat-User-Avatar".into(),
format!("base64:{}", avatar),
format!("base64:{avatar}"),
)),
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() == '<' {
rfc724_mid
} 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())
);
println!("{}", s);
println!("{s}");
assert_eq!(s, "=?utf-8?q?=C3=A4_space?= <x@y.org>");
}

View File

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

View File

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

View File

@@ -417,8 +417,7 @@ impl Peerstate {
Ok(())
} else {
Err(Error::msg(format!(
"{} is not peer's public key fingerprint",
fingerprint,
"{fingerprint} is not peer's public key fingerprint",
)))
}
}
@@ -432,8 +431,7 @@ impl Peerstate {
Ok(())
} else {
Err(Error::msg(format!(
"{} is not peer's gossip key fingerprint",
fingerprint,
"{fingerprint} is not peer's gossip key 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),
};
let user_id = format!("<{}>", addr);
let user_id = format!("<{addr}>");
let key_params = SecretKeyParamsBuilder::default()
.key_type(secret_key_type)
.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 (contact_id, _) = Contact::add_or_lookup(context, &name, addr, Origin::UnhandledQrScan)
.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 context
.is_self_addr(&addr)
.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 {
Ok(Qr::WithdrawVerifyGroup {
@@ -309,7 +309,7 @@ async fn decode_openpgp(context: &Context, qr: &str) -> Result<Qr> {
} else {
let contact_id = Contact::lookup_id_by_addr(context, &addr, Origin::Unknown)
.await
.with_context(|| format!("Error looking up contact {:?}", addr))?;
.with_context(|| format!("Error looking up contact {addr:?}"))?;
Ok(Qr::FprMismatch { contact_id })
}
} else {
@@ -325,7 +325,7 @@ fn decode_account(qr: &str) -> Result<Qr> {
.get(DCACCOUNT_SCHEME.len()..)
.context("invalid DCACCOUNT payload")?;
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" {
Ok(Qr::Account {
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 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" {
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_status = response.status();
let response_text = response.text().await.with_context(|| {
format!(
"Cannot create account, request to {:?} failed: empty response",
url_str
)
format!("Cannot create account, request to {url_str:?} failed: empty response")
})?;
if response_status.is_success() {
let CreateAccountSuccessResponse { password, email } = serde_json::from_str(&response_text)
.with_context(|| {
format!(
"Cannot create account, response from {:?} is malformed:\n{:?}",
url_str, response_text
"Cannot create account, response from {url_str:?} is malformed:\n{response_text:?}"
)
})?;
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)),
Err(parse_error) => {
context.emit_event(EventType::Error(format!(
"Cannot create account, server response could not be parsed:\n{:#}\nraw response:\n{}",
parse_error, response_text
"Cannot create account, server response could not be parsed:\n{parse_error:#}\nraw response:\n{response_text}"
)));
bail!(
"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 first_name = caps.get(2)?.as_str().trim();
Some(format!("{} {}", first_name, last_name))
Some(format!("{first_name} {last_name}"))
})
.unwrap_or_default();

View File

@@ -32,7 +32,7 @@ pub enum LoginOptions {
/// 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>
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
.get(DCLOGIN_SCHEME.len()..)

View File

@@ -90,7 +90,7 @@ fn inner_generate_secure_join_qr_code(
w.elem("svg", |d| {
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(())
})?
.build(|w| {
@@ -129,14 +129,14 @@ fn inner_generate_secure_join_qr_code(
for y in 0..qr.size() {
for x in 0..qr.size() {
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("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!(
"font-family:sans-serif;\
font-weight:bold;\
font-size:{}px;\
font-size:{text_font_size}px;\
fill:#000000;\
stroke:none",
text_font_size
stroke:none"
),
)
})?
@@ -236,9 +235,8 @@ fn inner_generate_secure_join_qr_code(
format!(
"font-family:sans-serif;\
font-weight:400;\
font-size:{}px;\
fill:#ffffff;",
avatar_font_size
font-size:{avatar_font_size}px;\
fill:#ffffff;"
),
)
})?

View File

@@ -135,7 +135,7 @@ impl fmt::Display for Reactions {
write!(f, " ")?;
}
first = false;
write!(f, "{}{}", emoji, frequency)?;
write!(f, "{emoji}{frequency}")?;
}
Ok(())
}
@@ -500,7 +500,7 @@ Content-Disposition: reaction\n\
Message-ID: <first@example.org>\n\
Date: Sun, 14 Nov 2021 00:10:00 +0000\
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.
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
{
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);
} else {
// change chat protection only when verification check passes
@@ -1013,7 +1013,7 @@ async fn add_parts(
chat::add_info_msg(
context,
chat_id,
&format!("Cannot set protection: {}", e),
&format!("Cannot set protection: {e}"),
sort_timestamp,
)
.await?;
@@ -1162,7 +1162,7 @@ SET rfc724_mid=excluded.rfc724_mid, chat_id=excluded.chat_id,
if part.typ == Viewtype::Text {
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 {
@@ -1254,7 +1254,7 @@ SET rfc724_mid=excluded.rfc724_mid, chat_id=excluded.chat_id,
info!(
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.
@@ -1522,7 +1522,7 @@ async fn create_or_lookup_group(
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 {
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);
}
ProtectionStatus::Protected
@@ -1573,7 +1573,7 @@ async fn create_or_lookup_group(
None,
)
.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_blocked = create_blocked;
@@ -1720,7 +1720,7 @@ async fn apply_group_changes(
if mime_parser.get_header(HeaderDef::ChatVerified).is_some() {
if let Err(err) = check_verified_properties(context, mime_parser, from_id, to_ids).await {
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);
}

View File

@@ -627,15 +627,14 @@ async fn test_parse_ndn(
&t,
format!(
"Received: (Postfix, from userid 1000); Mon, 4 Dec 2006 14:51:39 +0100 (CET)\n\
From: {}\n\
To: {}\n\
From: {self_addr}\n\
To: {foreign_addr}\n\
Subject: foo\n\
Message-ID: <{}>\n\
Message-ID: <{rfc724_mid_outgoing}>\n\
Chat-Version: 1.0\n\
Date: Sun, 22 Mar 2020 22:37:57 +0000\n\
\n\
hello\n",
self_addr, foreign_addr, rfc724_mid_outgoing
hello\n"
)
.as_bytes(),
false,
@@ -861,7 +860,7 @@ async fn test_classic_mailing_list() -> Result<()> {
let sent = t.send_text(chat.id, "Hello mailinglist!").await;
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("Subject: =?utf-8?q?Re=3A_=5Bdelta-dev=5D_What=27s_up=3F?=\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();
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();
assert_eq!(
@@ -1470,7 +1469,7 @@ async fn check_dont_show_in_contacts_list(addr: &str) {
&t,
format!(
"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>
<deltachat/deltachat-core-rust/pull/1625/c644661857@github.com>
From: alice@example.org
@@ -1481,8 +1480,7 @@ Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: 7bit
YEAAAAAA!.
",
addr
"
)
.as_bytes(),
false,
@@ -2814,7 +2812,7 @@ async fn test_long_filenames() -> Result<()> {
"a.a..a.a.a.a.tar.gz",
] {
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?;
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();
assert!(
resulting_filename.ends_with(".tar.gz"),
"{:?} doesn't end with .tar.gz, path: {:?}",
resulting_filename,
path
"{resulting_filename:?} doesn't end with .tar.gz, path: {path:?}"
);
assert!(
path.to_str().unwrap().ends_with(".tar.gz"),
"path {:?} doesn't end with .tar.gz",
path
"path {path:?} doesn't end with .tar.gz"
);
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 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 {
let mut folder_added = false;
@@ -436,7 +436,7 @@ impl Context {
// =============================================================================================
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;
ret += &*detailed.to_icon();
ret += " ";
@@ -452,7 +452,7 @@ impl Context {
let domain = &tools::EmailAddress::new(&self.get_primary_self_addr().await?)?.domain;
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;
if let Some(quota) = &*quota {
match &quota.recent {
@@ -488,7 +488,7 @@ impl Context {
)
}
Message => {
format!("<b>{}:</b> {}", part_of_total_used, messages)
format!("<b>{part_of_total_used}:</b> {messages}")
}
Storage => {
// do not use a special title needed for "Storage":
@@ -511,14 +511,14 @@ impl Context {
} else {
"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>";
}
}
}
Err(e) => {
ret += format!("<li>{}</li>", e).as_str();
ret += format!("<li>{e}</li>").as_str();
}
}
@@ -527,7 +527,7 @@ impl Context {
}
} else {
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?;
}
ret += "</ul>";

View File

@@ -179,7 +179,7 @@ async fn send_alice_handshake_msg(
) -> Result<()> {
let mut msg = Message {
viewtype: Viewtype::Text,
text: Some(format!("Secure-Join: {}", step)),
text: Some(format!("Secure-Join: {step}")),
hidden: true,
..Default::default()
};
@@ -625,7 +625,7 @@ pub(crate) async fn observe_securejoin_on_other_device(
context,
contact_id,
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?;
return Ok(HandshakeMessage::Ignore);
@@ -653,7 +653,7 @@ pub(crate) async fn observe_securejoin_on_other_device(
context,
contact_id,
info_chat_id(context, contact_id).await?,
format!("Fingerprint mismatch on observing {}.", step).as_ref(),
format!("Fingerprint mismatch on observing {step}.").as_ref(),
)
.await?;
return Ok(HandshakeMessage::Ignore);
@@ -1333,7 +1333,7 @@ mod tests {
if let chat::ChatItem::Message { msg_id } = item {
let msg = Message::load_from_db(&bob.ctx, msg_id).await.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)

View File

@@ -126,7 +126,7 @@ impl Smtp {
}
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);
@@ -227,7 +227,7 @@ pub(crate) async fn smtp_send(
) -> SendResult {
if std::env::var(crate::DCC_MIME_DEBUG).is_ok() {
info!(context, "smtp-sending out mime message:");
println!("{}", message);
println!("{message}");
}
smtp.connectivity.set_working(context).await;
@@ -237,7 +237,7 @@ pub(crate) async fn smtp_send(
.await
.context("Failed to open SMTP connection")
{
smtp.last_send_error = Some(format!("{:#}", err));
smtp.last_send_error = Some(format!("{err:#}"));
return SendResult::Retry;
}
@@ -374,7 +374,7 @@ pub(crate) async fn send_msg_to_smtp(
.await
.context("SMTP connection failure")
{
smtp.last_send_error = Some(format!("{:#}", err));
smtp.last_send_error = Some(format!("{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.
if !message::exists(context, msg_id)
.await
.with_context(|| format!("failed to check message {} existence", msg_id))?
.with_context(|| format!("failed to check message {msg_id} existence"))?
{
info!(
context,

View File

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

View File

@@ -125,7 +125,7 @@ impl Sql {
pub(crate) async fn export(&self, path: &Path, passphrase: String) -> Result<()> {
let path_str = path
.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?;
tokio::task::block_in_place(move || {
conn.execute(
@@ -148,7 +148,7 @@ impl Sql {
pub(crate) async fn import(&self, path: &Path, passphrase: String) -> Result<()> {
let path_str = path
.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?;
tokio::task::block_in_place(move || {
@@ -587,7 +587,7 @@ impl Sql {
let value = self
.query_get_value("SELECT value FROM config WHERE keyname=?;", paramsv![key])
.await
.context(format!("failed to fetch raw config: {}", key))?;
.context(format!("failed to fetch raw config: {key}"))?;
lock.insert(key.to_string(), value.clone());
drop(lock);
@@ -595,7 +595,7 @@ impl Sql {
}
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>> {
@@ -623,7 +623,7 @@ impl Sql {
}
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>> {
@@ -863,7 +863,7 @@ async fn maybe_add_from_param(
},
)
.await
.context(format!("housekeeping: failed to add_from_param {}", query))?;
.context(format!("housekeeping: failed to add_from_param {query}"))?;
Ok(())
}
@@ -986,8 +986,7 @@ mod tests {
match event.typ {
EventType::Info(s) => assert!(
!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)",
s
"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)"
),
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
transaction.execute(
"INSERT INTO config (keyname, value) VALUES (?, ?);",
paramsv![VERSION_CFG, format!("{}", dbversion_before_update)],
paramsv![VERSION_CFG, format!("{dbversion_before_update}")],
)?;
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;
lock.insert(
VERSION_CFG.to_string(),
Some(format!("{}", dbversion_before_update)),
Some(format!("{dbversion_before_update}")),
);
drop(lock);
} else {
@@ -320,11 +320,11 @@ ALTER TABLE msgs ADD COLUMN ephemeral_timestamp INTEGER DEFAULT 0;"#,
if dbversion < 67 {
for prefix in &["", "configured_"] {
if let Some(server_flags) = sql
.get_raw_config_int(&format!("{}server_flags", prefix))
.get_raw_config_int(&format!("{prefix}server_flags"))
.await?
{
let imap_socket_flags = server_flags & 0x700;
let key = &format!("{}mail_security", prefix);
let key = &format!("{prefix}mail_security");
match imap_socket_flags {
0x100 => sql.set_raw_config_int(key, 2).await?, // STARTTLS
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?,
}
let smtp_socket_flags = server_flags & 0x70000;
let key = &format!("{}send_security", prefix);
let key = &format!("{prefix}send_security");
match smtp_socket_flags {
0x10000 => sql.set_raw_config_int(key, 2).await?, // STARTTLS
0x20000 => sql.set_raw_config_int(key, 1).await?, // SSL/TLS
@@ -721,16 +721,16 @@ impl Sql {
// set raw config inside the transaction
transaction.execute(
"UPDATE config SET value=? WHERE keyname=?;",
paramsv![format!("{}", version), VERSION_CFG],
paramsv![format!("{version}"), VERSION_CFG],
)?;
Ok(())
})
.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;
lock.insert(VERSION_CFG.to_string(), Some(format!("{}", version)));
lock.insert(VERSION_CFG.to_string(), Some(format!("{version}")));
drop(lock);
Ok(())

View File

@@ -719,10 +719,7 @@ pub(crate) async fn secure_join_started(
.replace1(&contact.get_name_n_addr())
.replace2(contact.get_display_name())
} else {
format!(
"secure_join_started: unknown contact {}",
inviter_contact_id
)
format!("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
.replace1(contact.get_display_name())
} 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 {
addr.to_owned()
} else {
format!("{} ({})", display_name, addr)
format!("{display_name} ({addr})")
};
translated(context, StockMessage::SetupContactQRDescription)
.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 {
translated(context, StockMessage::QuotaExceedingMsgBody)
.await
.replace1(&format!("{}", highest_usage))
.replace1(&format!("{highest_usage}"))
.replace("%%", "%")
}

View File

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

View File

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

View File

@@ -656,7 +656,7 @@ impl TestContext {
},
match sel_chat.get_profile_image(self).await.unwrap() {
Some(icon) => match icon.to_str() {
Some(icon) => format!(" Icon: {}", icon),
Some(icon) => format!(" Icon: {icon}"),
_ => " Icon: Err".to_string(),
},
_ => "".to_string(),
@@ -931,7 +931,7 @@ pub(crate) async fn get_chat_msg(
fn print_logevent(logevent: &LogEvent) {
match logevent {
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 msg = match &event.typ {
EventType::Info(msg) => format!("INFO: {}", msg),
EventType::SmtpConnected(msg) => format!("[SMTP_CONNECTED] {}", msg),
EventType::ImapConnected(msg) => format!("[IMAP_CONNECTED] {}", msg),
EventType::SmtpMessageSent(msg) => format!("[SMTP_MESSAGE_SENT] {}", msg),
EventType::Info(msg) => format!("INFO: {msg}"),
EventType::SmtpConnected(msg) => format!("[SMTP_CONNECTED] {msg}"),
EventType::ImapConnected(msg) => format!("[IMAP_CONNECTED] {msg}"),
EventType::SmtpMessageSent(msg) => format!("[SMTP_MESSAGE_SENT] {msg}"),
EventType::Warning(msg) => format!("WARN: {}", yellow.paint(msg)),
EventType::Error(msg) => format!("ERROR: {}", red.paint(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!(
"{}",
green.paint(format!(
"Received MSGS_CHANGED(chat_id={}, msg_id={})",
chat_id, msg_id,
"Received MSGS_CHANGED(chat_id={chat_id}, msg_id={msg_id})",
))
),
EventType::ContactsChanged(_) => format!("{}", green.paint("Received CONTACTS_CHANGED()")),
EventType::LocationChanged(contact) => format!(
"{}",
green.paint(format!("Received LOCATION_CHANGED(contact={:?})", contact))
green.paint(format!("Received LOCATION_CHANGED(contact={contact:?})"))
),
EventType::ConfigureProgress { progress, comment } => {
if let Some(comment) = comment {
format!(
"{}",
green.paint(format!(
"Received CONFIGURE_PROGRESS({} ‰, {})",
progress, comment
"Received CONFIGURE_PROGRESS({progress} ‰, {comment})"
))
)
} else {
format!(
"{}",
green.paint(format!("Received CONFIGURE_PROGRESS({} ‰)", progress))
green.paint(format!("Received CONFIGURE_PROGRESS({progress} ‰)"))
)
}
}
EventType::ImexProgress(progress) => format!(
"{}",
green.paint(format!("Received IMEX_PROGRESS({} ‰)", progress))
green.paint(format!("Received IMEX_PROGRESS({progress} ‰)"))
),
EventType::ImexFileWritten(file) => format!(
"{}",
green.paint(format!("Received IMEX_FILE_WRITTEN({})", file.display()))
),
EventType::ChatModified(chat) => format!(
"{}",
green.paint(format!("Received CHAT_MODIFIED({})", chat))
),
_ => format!("Received {:?}", event),
EventType::ChatModified(chat) => {
format!("{}", green.paint(format!("Received CHAT_MODIFIED({chat})")))
}
_ => format!("Received {event:?}"),
};
let context_names = CONTEXT_NAMES.read().unwrap();
match context_names.get(&event.id) {
Some(name) => println!("{} {}", name, msg),
Some(name) => println!("{name} {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 {
Ok(contact) => contact,
Err(e) => {
println!("Can't log message: invalid contact: {}", e);
println!("Can't log message: invalid contact: {e}");
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.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 recvd = alice.recv_msg(&sent).await;
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;
assert!(
last_info_msg.is_none(),
"{:?} shouldn't be there (or it's an unrelated info msg)",
last_info_msg
"{last_info_msg:?} shouldn't be there (or it's an unrelated info msg)"
);
}
}

View File

@@ -95,7 +95,7 @@ pub(crate) fn truncate_by_lines(
};
if let Some(truncated_text) = text {
(format!("{}{}", truncated_text, DC_ELLIPSIS), true)
(format!("{truncated_text}{DC_ELLIPSIS}"), true)
} else {
// In case of indexing/slicing error, we return an error
// 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 m = (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 {
@@ -383,7 +383,7 @@ pub(crate) async fn delete_file(context: &Context, path: impl AsRef<Path>) -> Re
let dpath = format!("{}", path.to_string_lossy());
fs::remove_file(path_abs)
.await
.with_context(|| format!("cannot delete {:?}", dpath))?;
.with_context(|| format!("cannot delete {dpath:?}"))?;
context.emit_event(EventType::DeletedBlobFile(dpath));
Ok(())
}

View File

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